Files
google-apis-rs/gen/recommender1_beta1/src/lib.rs
2020-07-10 09:41:44 +08:00

3413 lines
155 KiB
Rust

// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
//! This documentation was generated from *Recommender* crate version *1.0.14+20200704*, where *20200704* is the exact revision of the *recommender:v1beta1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.14*.
//!
//! Everything else about the *Recommender* *v1_beta1* API can be found at the
//! [official documentation site](https://cloud.google.com/recommender/docs/).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/recommender1_beta1).
//! # Features
//!
//! Handle the following *Resources* with ease from the central [hub](struct.Recommender.html) ...
//!
//! * projects
//! * [*locations insight types insights get*](struct.ProjectLocationInsightTypeInsightGetCall.html), [*locations insight types insights list*](struct.ProjectLocationInsightTypeInsightListCall.html), [*locations insight types insights mark accepted*](struct.ProjectLocationInsightTypeInsightMarkAcceptedCall.html), [*locations recommenders recommendations get*](struct.ProjectLocationRecommenderRecommendationGetCall.html), [*locations recommenders recommendations list*](struct.ProjectLocationRecommenderRecommendationListCall.html), [*locations recommenders recommendations mark claimed*](struct.ProjectLocationRecommenderRecommendationMarkClaimedCall.html), [*locations recommenders recommendations mark failed*](struct.ProjectLocationRecommenderRecommendationMarkFailedCall.html) and [*locations recommenders recommendations mark succeeded*](struct.ProjectLocationRecommenderRecommendationMarkSucceededCall.html)
//!
//!
//!
//!
//! Not what you are looking for ? Find all other Google APIs in their Rust [documentation index](http://byron.github.io/google-apis-rs).
//!
//! # Structure of this Library
//!
//! The API is structured into the following primary items:
//!
//! * **[Hub](struct.Recommender.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().locations_recommenders_recommendations_mark_succeeded(...).doit()
//! let r = hub.projects().locations_recommenders_recommendations_mark_claimed(...).doit()
//! let r = hub.projects().locations_recommenders_recommendations_mark_failed(...).doit()
//! let r = hub.projects().locations_recommenders_recommendations_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-recommender1_beta1 = "*"
//! # This project intentionally uses an old version of Hyper. See
//! # https://github.com/Byron/google-apis-rs/issues/173 for more
//! # information.
//! hyper = "^0.10"
//! hyper-rustls = "^0.6"
//! serde = "^1.0"
//! serde_json = "^1.0"
//! yup-oauth2 = "^1.0"
//! ```
//!
//! ## A complete example
//!
//! ```test_harness,no_run
//! extern crate hyper;
//! extern crate hyper_rustls;
//! extern crate yup_oauth2 as oauth2;
//! extern crate google_recommender1_beta1 as recommender1_beta1;
//! use recommender1_beta1::GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest;
//! use recommender1_beta1::{Result, Error};
//! # #[test] fn egal() {
//! use std::default::Default;
//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
//! use recommender1_beta1::Recommender;
//!
//! // 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::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
//! <MemoryStorage as Default>::default(), None);
//! let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
//! // As the method needs a request, you would usually fill it with the desired information
//! // into the respective structure. Some of the parts shown here might not be applicable !
//! // Values shown here are possibly random and not representative !
//! let mut req = GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest::default();
//!
//! // You can configure optional parameters by calling 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().locations_recommenders_recommendations_mark_succeeded(req, "name")
//! .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](https://docs.rs/yup-oauth2/*/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 [encodable](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)]
// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
#[macro_use]
extern crate serde_derive;
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::mem;
use std::thread::sleep;
use std::time::Duration;
pub use cmn::*;
// ##############
// 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<str> 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 Recommender related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_recommender1_beta1 as recommender1_beta1;
/// use recommender1_beta1::GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest;
/// use recommender1_beta1::{Result, Error};
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use recommender1_beta1::Recommender;
///
/// // 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::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest::default();
///
/// // You can configure optional parameters by calling 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().locations_recommenders_recommendations_mark_succeeded(req, "name")
/// .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 Recommender<C, A> {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, C, A> Hub for Recommender<C, A> {}
impl<'a, C, A> Recommender<C, A>
where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
pub fn new(client: C, authenticator: A) -> Recommender<C, A> {
Recommender {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "google-api-rust-client/1.0.14".to_string(),
_base_url: "https://recommender.googleapis.com/".to_string(),
_root_url: "https://recommender.googleapis.com/".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/1.0.14`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://recommender.googleapis.com/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
mem::replace(&mut self._base_url, new_base_url)
}
/// Set the root url to use in all requests to the server.
/// It defaults to `https://recommender.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// Request for the `MarkInsightAccepted` 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*).
///
/// * [locations insight types insights mark accepted projects](struct.ProjectLocationInsightTypeInsightMarkAcceptedCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest {
/// Required. Fingerprint of the Insight. Provides optimistic locking.
pub etag: Option<String>,
/// Optional. State properties user wish to include with this state. Full replace of the
/// current state_metadata.
#[serde(rename="stateMetadata")]
pub state_metadata: Option<HashMap<String, String>>,
}
impl RequestValue for GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest {}
/// Information related to insight state.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1InsightStateInfo {
/// Insight state.
pub state: Option<String>,
/// A map of metadata for the state, provided by user or automations systems.
#[serde(rename="stateMetadata")]
pub state_metadata: Option<HashMap<String, String>>,
}
impl Part for GoogleCloudRecommenderV1beta1InsightStateInfo {}
/// Reference to an associated recommendation.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1InsightRecommendationReference {
/// Recommendation resource name, e.g.
/// projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]/recommendations/[RECOMMENDATION_ID]
pub recommendation: Option<String>,
}
impl Part for GoogleCloudRecommenderV1beta1InsightRecommendationReference {}
/// Request for the `MarkRecommendationSucceeded` 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*).
///
/// * [locations recommenders recommendations mark succeeded projects](struct.ProjectLocationRecommenderRecommendationMarkSucceededCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest {
/// Required. Fingerprint of the Recommendation. Provides optimistic locking.
pub etag: Option<String>,
/// State properties to include with this state. Overwrites any existing
/// `state_metadata`.
/// Keys must match the regex /^a-z0-9{0,62}$/.
/// Values must match the regex /^[a-zA-Z0-9_./-]{0,255}$/.
#[serde(rename="stateMetadata")]
pub state_metadata: Option<HashMap<String, String>>,
}
impl RequestValue for GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest {}
/// Contains what resources are changing and how they are changing.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1RecommendationContent {
/// Operations to one or more Google Cloud resources grouped in such a way
/// that, all operations within one group are expected to be performed
/// atomically and in an order.
#[serde(rename="operationGroups")]
pub operation_groups: Option<Vec<GoogleCloudRecommenderV1beta1OperationGroup>>,
}
impl Part for GoogleCloudRecommenderV1beta1RecommendationContent {}
/// Information for state. Contains state and metadata.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1RecommendationStateInfo {
/// The state of the recommendation, Eg ACTIVE, SUCCEEDED, FAILED.
pub state: Option<String>,
/// A map of metadata for the state, provided by user or automations systems.
#[serde(rename="stateMetadata")]
pub state_metadata: Option<HashMap<String, String>>,
}
impl Part for GoogleCloudRecommenderV1beta1RecommendationStateInfo {}
/// Response to the `ListRecommendations` 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*).
///
/// * [locations recommenders recommendations list projects](struct.ProjectLocationRecommenderRecommendationListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1ListRecommendationsResponse {
/// A token that can be used to request the next page of results. This field is
/// empty if there are no additional results.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// The set of recommendations for the `parent` resource.
pub recommendations: Option<Vec<GoogleCloudRecommenderV1beta1Recommendation>>,
}
impl ResponseResult for GoogleCloudRecommenderV1beta1ListRecommendationsResponse {}
/// Contains an operation for a resource loosely based on the JSON-PATCH format
/// with support for:
///
/// * Custom filters for describing partial array patch.
/// * Extended path values for describing nested arrays.
/// * Custom fields for describing the resource for which the operation is being
/// described.
/// * Allows extension to custom operations not natively supported by RFC6902.
/// See https://tools.ietf.org/html/rfc6902 for details on the original RFC.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1Operation {
/// Can be set for action 'test' for advanced matching for the value of
/// 'path' field. Either this or `value` will be set for 'test' operation.
#[serde(rename="valueMatcher")]
pub value_matcher: Option<GoogleCloudRecommenderV1beta1ValueMatcher>,
/// Contains the fully qualified resource name. This field is always populated.
/// ex: //cloudresourcemanager.googleapis.com/projects/foo.
pub resource: Option<String>,
/// Type of GCP resource being modified/tested. This field is always populated.
/// Example: cloudresourcemanager.googleapis.com/Project,
/// compute.googleapis.com/Instance
#[serde(rename="resourceType")]
pub resource_type: Option<String>,
/// Value for the `path` field. Will be set for actions:'add'/'replace'.
/// Maybe set for action: 'test'. Either this or `value_matcher` will be set
/// for 'test' operation. An exact match must be performed.
pub value: Option<String>,
/// Can be set with action 'copy' or 'move' to indicate the source field within
/// resource or source_resource, ignored if provided for other operation types.
#[serde(rename="sourcePath")]
pub source_path: Option<String>,
/// Similar to path_filters, this contains set of filters to apply if `path`
/// field referes to array elements. This is meant to support value matching
/// beyond exact match. To perform exact match, use path_filters.
/// When both path_filters and path_value_matchers are set, an implicit AND
/// must be performed.
#[serde(rename="pathValueMatchers")]
pub path_value_matchers: Option<HashMap<String, GoogleCloudRecommenderV1beta1ValueMatcher>>,
/// Set of filters to apply if `path` refers to array elements or nested array
/// elements in order to narrow down to a single unique element that is being
/// tested/modified.
/// This is intended to be an exact match per filter. To perform advanced
/// matching, use path_value_matchers.
///
/// * Example: {
/// "/versions/*/name" : "it-123"
/// "/versions/*/targetSize/percent": 20
/// }
/// * Example: {
/// "/bindings/*/role": "roles/admin"
/// "/bindings/*/condition" : null
/// }
/// * Example: {
/// "/bindings/*/role": "roles/admin"
/// "/bindings/*/members/*" : ["x@google.com", "y@google.com"]
/// }
/// When both path_filters and path_value_matchers are set, an implicit AND
/// must be performed.
#[serde(rename="pathFilters")]
pub path_filters: Option<HashMap<String, String>>,
/// Type of this operation. Contains one of 'and', 'remove', 'replace', 'move',
/// 'copy', 'test' and 'custom' operations. This field is case-insensitive and
/// always populated.
pub action: Option<String>,
/// Can be set with action 'copy' to copy resource configuration across
/// different resources of the same type. Example: A resource clone can be
/// done via action = 'copy', path = "/", from = "/",
/// source_resource = <source> and resource_name = <target>.
/// This field is empty for all other values of `action`.
#[serde(rename="sourceResource")]
pub source_resource: Option<String>,
/// Path to the target field being operated on. If the operation is at the
/// resource level, then path should be "/". This field is always populated.
pub path: Option<String>,
}
impl Part for GoogleCloudRecommenderV1beta1Operation {}
/// Request for the `MarkRecommendationFailed` 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*).
///
/// * [locations recommenders recommendations mark failed projects](struct.ProjectLocationRecommenderRecommendationMarkFailedCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest {
/// Required. Fingerprint of the Recommendation. Provides optimistic locking.
pub etag: Option<String>,
/// State properties to include with this state. Overwrites any existing
/// `state_metadata`.
/// Keys must match the regex /^a-z0-9{0,62}$/.
/// Values must match the regex /^[a-zA-Z0-9_./-]{0,255}$/.
#[serde(rename="stateMetadata")]
pub state_metadata: Option<HashMap<String, String>>,
}
impl RequestValue for GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest {}
/// Response to the `ListInsights` 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*).
///
/// * [locations insight types insights list projects](struct.ProjectLocationInsightTypeInsightListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1ListInsightsResponse {
/// A token that can be used to request the next page of results. This field is
/// empty if there are no additional results.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// The set of insights for the `parent` resource.
pub insights: Option<Vec<GoogleCloudRecommenderV1beta1Insight>>,
}
impl ResponseResult for GoogleCloudRecommenderV1beta1ListInsightsResponse {}
/// Request for the `MarkRecommendationClaimed` 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*).
///
/// * [locations recommenders recommendations mark claimed projects](struct.ProjectLocationRecommenderRecommendationMarkClaimedCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest {
/// Required. Fingerprint of the Recommendation. Provides optimistic locking.
pub etag: Option<String>,
/// State properties to include with this state. Overwrites any existing
/// `state_metadata`.
/// Keys must match the regex /^a-z0-9{0,62}$/.
/// Values must match the regex /^[a-zA-Z0-9_./-]{0,255}$/.
#[serde(rename="stateMetadata")]
pub state_metadata: Option<HashMap<String, String>>,
}
impl RequestValue for GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest {}
/// Group of operations that need to be performed atomically.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1OperationGroup {
/// List of operations across one or more resources that belong to this group.
/// Loosely based on RFC6902 and should be performed in the order they appear.
pub operations: Option<Vec<GoogleCloudRecommenderV1beta1Operation>>,
}
impl Part for GoogleCloudRecommenderV1beta1OperationGroup {}
/// Contains metadata about how much money a recommendation can save or incur.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1CostProjection {
/// Duration for which this cost applies.
pub duration: Option<String>,
/// An approximate projection on amount saved or amount incurred. Negative cost
/// units indicate cost savings and positive cost units indicate increase.
/// See google.type.Money documentation for positive/negative units.
pub cost: Option<GoogleTypeMoney>,
}
impl Part for GoogleCloudRecommenderV1beta1CostProjection {}
/// An insight along with the information used to derive the insight. The insight
/// may have associated recomendations as well.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations insight types insights mark accepted projects](struct.ProjectLocationInsightTypeInsightMarkAcceptedCall.html) (response)
/// * [locations insight types insights get projects](struct.ProjectLocationInsightTypeInsightGetCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1Insight {
/// Category being targeted by the insight.
pub category: Option<String>,
/// Free-form human readable summary in English. The maximum length is 500
/// characters.
pub description: Option<String>,
/// Observation period that led to the insight. The source data used to
/// generate the insight ends at last_refresh_time and begins at
/// (last_refresh_time - observation_period).
#[serde(rename="observationPeriod")]
pub observation_period: Option<String>,
/// Timestamp of the latest data used to generate the insight.
#[serde(rename="lastRefreshTime")]
pub last_refresh_time: Option<String>,
/// Insight subtype. Insight content schema will be stable for a given subtype.
#[serde(rename="insightSubtype")]
pub insight_subtype: Option<String>,
/// Information state and metadata.
#[serde(rename="stateInfo")]
pub state_info: Option<GoogleCloudRecommenderV1beta1InsightStateInfo>,
/// A struct of custom fields to explain the insight.
/// Example: "grantedPermissionsCount": "1000"
pub content: Option<HashMap<String, String>>,
/// Fingerprint of the Insight. Provides optimistic locking when updating
/// states.
pub etag: Option<String>,
/// Fully qualified resource names that this insight is targeting.
#[serde(rename="targetResources")]
pub target_resources: Option<Vec<String>>,
/// Recommendations derived from this insight.
#[serde(rename="associatedRecommendations")]
pub associated_recommendations: Option<Vec<GoogleCloudRecommenderV1beta1InsightRecommendationReference>>,
/// Name of the insight.
pub name: Option<String>,
}
impl ResponseResult for GoogleCloudRecommenderV1beta1Insight {}
/// Contains various matching options for values for a GCP resource field.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1ValueMatcher {
/// To be used for full regex matching. The regular expression is using the
/// Google RE2 syntax (https://github.com/google/re2/wiki/Syntax), so to be
/// used with RE2::FullMatch
#[serde(rename="matchesPattern")]
pub matches_pattern: Option<String>,
}
impl Part for GoogleCloudRecommenderV1beta1ValueMatcher {}
/// Reference to an associated insight.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1RecommendationInsightReference {
/// Insight resource name, e.g.
/// projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]/insights/[INSIGHT_ID]
pub insight: Option<String>,
}
impl Part for GoogleCloudRecommenderV1beta1RecommendationInsightReference {}
/// 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 GoogleTypeMoney {
/// 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<i32>,
/// The whole units of the amount.
/// For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar.
pub units: Option<String>,
/// The 3-letter currency code defined in ISO 4217.
#[serde(rename="currencyCode")]
pub currency_code: Option<String>,
}
impl Part for GoogleTypeMoney {}
/// Contains the impact a recommendation can have for a given category.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1Impact {
/// Category that is being targeted.
pub category: Option<String>,
/// Use with CategoryType.COST
#[serde(rename="costProjection")]
pub cost_projection: Option<GoogleCloudRecommenderV1beta1CostProjection>,
}
impl Part for GoogleCloudRecommenderV1beta1Impact {}
/// A recommendation along with a suggested action. E.g., a rightsizing
/// recommendation for an underutilized VM, IAM role recommendations, etc
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations recommenders recommendations mark succeeded projects](struct.ProjectLocationRecommenderRecommendationMarkSucceededCall.html) (response)
/// * [locations recommenders recommendations mark claimed projects](struct.ProjectLocationRecommenderRecommendationMarkClaimedCall.html) (response)
/// * [locations recommenders recommendations mark failed projects](struct.ProjectLocationRecommenderRecommendationMarkFailedCall.html) (response)
/// * [locations recommenders recommendations get projects](struct.ProjectLocationRecommenderRecommendationGetCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GoogleCloudRecommenderV1beta1Recommendation {
/// The primary impact that this recommendation can have while trying to
/// optimize for one category.
#[serde(rename="primaryImpact")]
pub primary_impact: Option<GoogleCloudRecommenderV1beta1Impact>,
/// Optional set of additional impact that this recommendation may have when
/// trying to optimize for the primary category. These may be positive
/// or negative.
#[serde(rename="additionalImpact")]
pub additional_impact: Option<Vec<GoogleCloudRecommenderV1beta1Impact>>,
/// Last time this recommendation was refreshed by the system that created it
/// in the first place.
#[serde(rename="lastRefreshTime")]
pub last_refresh_time: Option<String>,
/// Free-form human readable summary in English. The maximum length is 500
/// characters.
pub description: Option<String>,
/// Information for state. Contains state and metadata.
#[serde(rename="stateInfo")]
pub state_info: Option<GoogleCloudRecommenderV1beta1RecommendationStateInfo>,
/// Content of the recommendation describing recommended changes to resources.
pub content: Option<GoogleCloudRecommenderV1beta1RecommendationContent>,
/// Fingerprint of the Recommendation. Provides optimistic locking when
/// updating states.
pub etag: Option<String>,
/// Contains an identifier for a subtype of recommendations produced for the
/// same recommender. Subtype is a function of content and impact, meaning a
/// new subtype might be added when significant changes to `content` or
/// `primary_impact.category` are introduced. See the Recommenders section
/// to see a list of subtypes for a given Recommender.
///
/// Examples:
/// For recommender = "google.iam.policy.Recommender",
/// recommender_subtype can be one of "REMOVE_ROLE"/"REPLACE_ROLE"
#[serde(rename="recommenderSubtype")]
pub recommender_subtype: Option<String>,
/// Insights that led to this recommendation.
#[serde(rename="associatedInsights")]
pub associated_insights: Option<Vec<GoogleCloudRecommenderV1beta1RecommendationInsightReference>>,
/// Name of recommendation.
pub name: Option<String>,
}
impl ResponseResult for GoogleCloudRecommenderV1beta1Recommendation {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *project* resources.
/// It is not used directly, but through the `Recommender` hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate yup_oauth2 as oauth2;
/// extern crate google_recommender1_beta1 as recommender1_beta1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use recommender1_beta1::Recommender;
///
/// let secret: ApplicationSecret = Default::default();
/// let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// <MemoryStorage as Default>::default(), None);
/// let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `locations_insight_types_insights_get(...)`, `locations_insight_types_insights_list(...)`, `locations_insight_types_insights_mark_accepted(...)`, `locations_recommenders_recommendations_get(...)`, `locations_recommenders_recommendations_list(...)`, `locations_recommenders_recommendations_mark_claimed(...)`, `locations_recommenders_recommendations_mark_failed(...)` and `locations_recommenders_recommendations_mark_succeeded(...)`
/// // to build up your call.
/// let rb = hub.projects();
/// # }
/// ```
pub struct ProjectMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
}
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:
///
/// Marks the Recommendation State as Failed. Users can use this method to
/// indicate to the Recommender API that they have applied the recommendation
/// themselves, and the operation failed. This stops the recommendation content
/// from being updated. Associated insights are frozen and placed in the
/// ACCEPTED state.
///
/// MarkRecommendationFailed can be applied to recommendations in ACTIVE,
/// CLAIMED, SUCCEEDED, or FAILED state.
///
/// Requires the recommender.*.update IAM permission for the specified
/// recommender.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. Name of the recommendation.
pub fn locations_recommenders_recommendations_mark_failed(&self, request: GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest, name: &str) -> ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A> {
ProjectLocationRecommenderRecommendationMarkFailedCall {
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:
///
/// Lists insights for a Cloud project. Requires the recommender.*.list IAM
/// permission for the specified insight type.
///
/// # Arguments
///
/// * `parent` - Required. The container resource on which to execute the request.
/// Acceptable formats:
/// 1.
/// "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]",
/// LOCATION here refers to GCP Locations:
/// https://cloud.google.com/about/locations/
pub fn locations_insight_types_insights_list(&self, parent: &str) -> ProjectLocationInsightTypeInsightListCall<'a, C, A> {
ProjectLocationInsightTypeInsightListCall {
hub: self.hub,
_parent: parent.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:
///
/// Lists recommendations for a Cloud project. Requires the recommender.*.list
/// IAM permission for the specified recommender.
///
/// # Arguments
///
/// * `parent` - Required. The container resource on which to execute the request.
/// Acceptable formats:
/// 1.
/// "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]",
/// LOCATION here refers to GCP Locations:
/// https://cloud.google.com/about/locations/
pub fn locations_recommenders_recommendations_list(&self, parent: &str) -> ProjectLocationRecommenderRecommendationListCall<'a, C, A> {
ProjectLocationRecommenderRecommendationListCall {
hub: self.hub,
_parent: parent.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:
///
/// Marks the Insight State as Accepted. Users can use this method to
/// indicate to the Recommender API that they have applied some action based
/// on the insight. This stops the insight content from being updated.
///
/// MarkInsightAccepted can be applied to insights in ACTIVE state. Requires
/// the recommender.*.update IAM permission for the specified insight.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. Name of the insight.
pub fn locations_insight_types_insights_mark_accepted(&self, request: GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest, name: &str) -> ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A> {
ProjectLocationInsightTypeInsightMarkAcceptedCall {
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:
///
/// Marks the Recommendation State as Claimed. Users can use this method to
/// indicate to the Recommender API that they are starting to apply the
/// recommendation themselves. This stops the recommendation content from being
/// updated. Associated insights are frozen and placed in the ACCEPTED state.
///
/// MarkRecommendationClaimed can be applied to recommendations in CLAIMED or
/// ACTIVE state.
///
/// Requires the recommender.*.update IAM permission for the specified
/// recommender.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. Name of the recommendation.
pub fn locations_recommenders_recommendations_mark_claimed(&self, request: GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest, name: &str) -> ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A> {
ProjectLocationRecommenderRecommendationMarkClaimedCall {
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:
///
/// Marks the Recommendation State as Succeeded. Users can use this method to
/// indicate to the Recommender API that they have applied the recommendation
/// themselves, and the operation was successful. This stops the recommendation
/// content from being updated. Associated insights are frozen and placed in
/// the ACCEPTED state.
///
/// MarkRecommendationSucceeded can be applied to recommendations in ACTIVE,
/// CLAIMED, SUCCEEDED, or FAILED state.
///
/// Requires the recommender.*.update IAM permission for the specified
/// recommender.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. Name of the recommendation.
pub fn locations_recommenders_recommendations_mark_succeeded(&self, request: GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest, name: &str) -> ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A> {
ProjectLocationRecommenderRecommendationMarkSucceededCall {
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 requested recommendation. Requires the recommender.*.get
/// IAM permission for the specified recommender.
///
/// # Arguments
///
/// * `name` - Required. Name of the recommendation.
pub fn locations_recommenders_recommendations_get(&self, name: &str) -> ProjectLocationRecommenderRecommendationGetCall<'a, C, A> {
ProjectLocationRecommenderRecommendationGetCall {
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:
///
/// Gets the requested insight. Requires the recommender.*.get IAM permission
/// for the specified insight type.
///
/// # Arguments
///
/// * `name` - Required. Name of the insight.
pub fn locations_insight_types_insights_get(&self, name: &str) -> ProjectLocationInsightTypeInsightGetCall<'a, C, A> {
ProjectLocationInsightTypeInsightGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Marks the Recommendation State as Failed. Users can use this method to
/// indicate to the Recommender API that they have applied the recommendation
/// themselves, and the operation failed. This stops the recommendation content
/// from being updated. Associated insights are frozen and placed in the
/// ACCEPTED state.
///
/// MarkRecommendationFailed can be applied to recommendations in ACTIVE,
/// CLAIMED, SUCCEEDED, or FAILED state.
///
/// Requires the recommender.*.update IAM permission for the specified
/// recommender.
///
/// A builder for the *locations.recommenders.recommendations.markFailed* 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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// use recommender1_beta1::GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest::default();
///
/// // You can configure optional parameters by calling 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().locations_recommenders_recommendations_mark_failed(req, "name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_request: GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1Recommendation)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.recommenders.recommendations.markFailed",
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 = self.hub._base_url.clone() + "v1beta1/{+name}:markFailed";
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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = 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);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: GoogleCloudRecommenderV1beta1MarkRecommendationFailedRequest) -> ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. Name of the recommendation.
///
/// 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) -> ProjectLocationRecommenderRecommendationMarkFailedCall<'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 dyn Delegate) -> ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationRecommenderRecommendationMarkFailedCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Lists insights for a Cloud project. Requires the recommender.*.list IAM
/// permission for the specified insight type.
///
/// A builder for the *locations.insightTypes.insights.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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling 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().locations_insight_types_insights_list("parent")
/// .page_token("dolores")
/// .page_size(-63)
/// .filter("accusam")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationInsightTypeInsightListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationInsightTypeInsightListCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationInsightTypeInsightListCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1ListInsightsResponse)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.insightTypes.insights.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("parent", self._parent.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", "parent", "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 = self.hub._base_url.clone() + "v1beta1/{+parent}/insights";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{+parent}", "parent")].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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["parent"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
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 container resource on which to execute the request.
/// Acceptable formats:
///
/// 1.
/// "projects/[PROJECT_NUMBER]/locations/[LOCATION]/insightTypes/[INSIGHT_TYPE_ID]",
///
/// LOCATION here refers to GCP Locations:
/// https://cloud.google.com/about/locations/
///
/// Sets the *parent* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn parent(mut self, new_value: &str) -> ProjectLocationInsightTypeInsightListCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// Optional. If present, retrieves the next batch of results from the preceding call to
/// this method. `page_token` must be the value of `next_page_token` from the
/// previous response. The values of other method parameters must be identical
/// to those in the previous call.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationInsightTypeInsightListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. The maximum number of results to return from this request. Non-positive
/// values are ignored. If not specified, the server will determine the number
/// of results to return.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationInsightTypeInsightListCall<'a, C, A> {
self._page_size = Some(new_value);
self
}
/// Optional. Filter expression to restrict the insights returned. Supported
/// filter fields: state
/// Eg: `state:"DISMISSED" or state:"ACTIVE"
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ProjectLocationInsightTypeInsightListCall<'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 dyn Delegate) -> ProjectLocationInsightTypeInsightListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationInsightTypeInsightListCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationInsightTypeInsightListCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Lists recommendations for a Cloud project. Requires the recommender.*.list
/// IAM permission for the specified recommender.
///
/// A builder for the *locations.recommenders.recommendations.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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling 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().locations_recommenders_recommendations_list("parent")
/// .page_token("justo")
/// .page_size(-1)
/// .filter("erat")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationRecommenderRecommendationListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationRecommenderRecommendationListCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationRecommenderRecommendationListCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1ListRecommendationsResponse)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.recommenders.recommendations.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("parent", self._parent.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", "parent", "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 = self.hub._base_url.clone() + "v1beta1/{+parent}/recommendations";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
for &(find_this, param_name) in [("{+parent}", "parent")].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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = Vec::with_capacity(1);
for param_name in ["parent"].iter() {
if let Some(index) = params.iter().position(|t| &t.0 == param_name) {
indices_for_removal.push(index);
}
}
for &index in indices_for_removal.iter() {
params.remove(index);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
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 container resource on which to execute the request.
/// Acceptable formats:
///
/// 1.
/// "projects/[PROJECT_NUMBER]/locations/[LOCATION]/recommenders/[RECOMMENDER_ID]",
///
/// LOCATION here refers to GCP Locations:
/// https://cloud.google.com/about/locations/
///
/// Sets the *parent* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn parent(mut self, new_value: &str) -> ProjectLocationRecommenderRecommendationListCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// Optional. If present, retrieves the next batch of results from the preceding call to
/// this method. `page_token` must be the value of `next_page_token` from the
/// previous response. The values of other method parameters must be identical
/// to those in the previous call.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationRecommenderRecommendationListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. The maximum number of results to return from this request. Non-positive
/// values are ignored. If not specified, the server will determine the number
/// of results to return.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationRecommenderRecommendationListCall<'a, C, A> {
self._page_size = Some(new_value);
self
}
/// Filter expression to restrict the recommendations returned. Supported
/// filter fields: state_info.state
/// Eg: `state_info.state:"DISMISSED" or state_info.state:"FAILED"
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ProjectLocationRecommenderRecommendationListCall<'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 dyn Delegate) -> ProjectLocationRecommenderRecommendationListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationRecommenderRecommendationListCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationRecommenderRecommendationListCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Marks the Insight State as Accepted. Users can use this method to
/// indicate to the Recommender API that they have applied some action based
/// on the insight. This stops the insight content from being updated.
///
/// MarkInsightAccepted can be applied to insights in ACTIVE state. Requires
/// the recommender.*.update IAM permission for the specified insight.
///
/// A builder for the *locations.insightTypes.insights.markAccepted* 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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// use recommender1_beta1::GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest::default();
///
/// // You can configure optional parameters by calling 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().locations_insight_types_insights_mark_accepted(req, "name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_request: GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1Insight)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.insightTypes.insights.markAccepted",
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 = self.hub._base_url.clone() + "v1beta1/{+name}:markAccepted";
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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = 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);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: GoogleCloudRecommenderV1beta1MarkInsightAcceptedRequest) -> ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. Name of the insight.
///
/// 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) -> ProjectLocationInsightTypeInsightMarkAcceptedCall<'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 dyn Delegate) -> ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationInsightTypeInsightMarkAcceptedCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Marks the Recommendation State as Claimed. Users can use this method to
/// indicate to the Recommender API that they are starting to apply the
/// recommendation themselves. This stops the recommendation content from being
/// updated. Associated insights are frozen and placed in the ACCEPTED state.
///
/// MarkRecommendationClaimed can be applied to recommendations in CLAIMED or
/// ACTIVE state.
///
/// Requires the recommender.*.update IAM permission for the specified
/// recommender.
///
/// A builder for the *locations.recommenders.recommendations.markClaimed* 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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// use recommender1_beta1::GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest::default();
///
/// // You can configure optional parameters by calling 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().locations_recommenders_recommendations_mark_claimed(req, "name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_request: GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1Recommendation)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.recommenders.recommendations.markClaimed",
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 = self.hub._base_url.clone() + "v1beta1/{+name}:markClaimed";
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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = 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);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: GoogleCloudRecommenderV1beta1MarkRecommendationClaimedRequest) -> ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. Name of the recommendation.
///
/// 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) -> ProjectLocationRecommenderRecommendationMarkClaimedCall<'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 dyn Delegate) -> ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationRecommenderRecommendationMarkClaimedCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Marks the Recommendation State as Succeeded. Users can use this method to
/// indicate to the Recommender API that they have applied the recommendation
/// themselves, and the operation was successful. This stops the recommendation
/// content from being updated. Associated insights are frozen and placed in
/// the ACCEPTED state.
///
/// MarkRecommendationSucceeded can be applied to recommendations in ACTIVE,
/// CLAIMED, SUCCEEDED, or FAILED state.
///
/// Requires the recommender.*.update IAM permission for the specified
/// recommender.
///
/// A builder for the *locations.recommenders.recommendations.markSucceeded* 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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// use recommender1_beta1::GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest::default();
///
/// // You can configure optional parameters by calling 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().locations_recommenders_recommendations_mark_succeeded(req, "name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_request: GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1Recommendation)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.recommenders.recommendations.markSucceeded",
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 = self.hub._base_url.clone() + "v1beta1/{+name}:markSucceeded";
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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = 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);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
let mut json_mime_type = mime::Mime(mime::TopLevel::Application, mime::SubLevel::Json, Default::default());
let mut request_value_reader =
{
let mut value = json::value::to_value(&self._request).expect("serde to work");
remove_json_null_values(&mut value);
let mut dst = io::Cursor::new(Vec::with_capacity(128));
json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader.seek(io::SeekFrom::End(0)).unwrap();
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
request_value_reader.seek(io::SeekFrom::Start(0)).unwrap();
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Post, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone())
.header(ContentType(json_mime_type.clone()))
.header(ContentLength(request_size as u64))
.body(&mut request_value_reader);
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
Err(err) => {
dlg.response_json_decode_error(&json_response, &err);
return Err(Error::JsonDecodeError(json_response, err));
}
}
};
dlg.finished(true);
return Ok(result_value)
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: GoogleCloudRecommenderV1beta1MarkRecommendationSucceededRequest) -> ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. Name of the recommendation.
///
/// 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) -> ProjectLocationRecommenderRecommendationMarkSucceededCall<'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 dyn Delegate) -> ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationRecommenderRecommendationMarkSucceededCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Gets the requested recommendation. Requires the recommender.*.get
/// IAM permission for the specified recommender.
///
/// A builder for the *locations.recommenders.recommendations.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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling 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().locations_recommenders_recommendations_get("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationRecommenderRecommendationGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationRecommenderRecommendationGetCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationRecommenderRecommendationGetCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1Recommendation)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.recommenders.recommendations.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 = self.hub._base_url.clone() + "v1beta1/{+name}";
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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = 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);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
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. Name of the recommendation.
///
/// 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) -> ProjectLocationRecommenderRecommendationGetCall<'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 dyn Delegate) -> ProjectLocationRecommenderRecommendationGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationRecommenderRecommendationGetCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationRecommenderRecommendationGetCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}
/// Gets the requested insight. Requires the recommender.*.get IAM permission
/// for the specified insight type.
///
/// A builder for the *locations.insightTypes.insights.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 hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_recommender1_beta1 as recommender1_beta1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use recommender1_beta1::Recommender;
///
/// # let secret: ApplicationSecret = Default::default();
/// # let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate,
/// # hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())),
/// # <MemoryStorage as Default>::default(), None);
/// # let mut hub = Recommender::new(hyper::Client::with_connector(hyper::net::HttpsConnector::new(hyper_rustls::TlsClient::new())), auth);
/// // You can configure optional parameters by calling 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().locations_insight_types_insights_get("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationInsightTypeInsightGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Recommender<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationInsightTypeInsightGetCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationInsightTypeInsightGetCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, GoogleCloudRecommenderV1beta1Insight)> {
use url::percent_encoding::{percent_encode, DEFAULT_ENCODE_SET};
use std::io::{Read, Seek};
use hyper::header::{ContentType, ContentLength, Authorization, Bearer, UserAgent, Location};
let mut dd = DefaultDelegate;
let mut dlg: &mut dyn Delegate = match self._delegate {
Some(d) => d,
None => &mut dd
};
dlg.begin(MethodInfo { id: "recommender.projects.locations.insightTypes.insights.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 = self.hub._base_url.clone() + "v1beta1/{+name}";
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(), DEFAULT_ENCODE_SET).to_string();
}
url = url.replace(find_this, &replace_with);
}
{
let mut indices_for_removal: Vec<usize> = 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);
}
}
let url = hyper::Url::parse_with_params(&url, params).unwrap();
loop {
let token = match self.hub.auth.borrow_mut().token(self._scopes.keys()) {
Ok(token) => token,
Err(err) => {
match dlg.token(&*err) {
Some(token) => token,
None => {
dlg.finished(false);
return Err(Error::MissingToken(err))
}
}
}
};
let auth_header = Authorization(Bearer { token: token.access_token });
let mut req_result = {
let mut client = &mut *self.hub.client.borrow_mut();
let mut req = client.borrow_mut().request(hyper::method::Method::Get, url.clone())
.header(UserAgent(self.hub._user_agent.clone()))
.header(auth_header.clone());
dlg.pre_request();
req.send()
};
match req_result {
Err(err) => {
if let oauth2::Retry::After(d) = dlg.http_error(&err) {
sleep(d);
continue;
}
dlg.finished(false);
return Err(Error::HttpError(err))
}
Ok(mut res) => {
if !res.status.is_success() {
let mut json_err = String::new();
res.read_to_string(&mut json_err).unwrap();
let json_server_error = json::from_str::<JsonServerError>(&json_err).ok();
let server_error = json::from_str::<ServerError>(&json_err)
.or_else(|_| json::from_str::<ErrorResponse>(&json_err).map(|r| r.error))
.ok();
if let oauth2::Retry::After(d) = dlg.http_failure(&res,
json_server_error,
server_error) {
sleep(d);
continue;
}
dlg.finished(false);
return match json::from_str::<ErrorResponse>(&json_err){
Err(_) => Err(Error::Failure(res)),
Ok(serr) => Err(Error::BadRequest(serr))
}
}
let result_value = {
let mut json_response = String::new();
res.read_to_string(&mut json_response).unwrap();
match json::from_str(&json_response) {
Ok(decoded) => (res, decoded),
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. Name of the insight.
///
/// 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) -> ProjectLocationInsightTypeInsightGetCall<'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 dyn Delegate) -> ProjectLocationInsightTypeInsightGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known parameters
/// which have their own setter method. If done anyway, the request will fail.
///
/// # Additional Parameters
///
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
/// * *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.
/// * *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<T>(mut self, name: T, value: T) -> ProjectLocationInsightTypeInsightGetCall<'a, C, A>
where T: AsRef<str> {
self._additional_params.insert(name.as_ref().to_string(), value.as_ref().to_string());
self
}
/// Identifies the authorization 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.
/// If `None` is specified, then all scopes will be removed and no default scope will be used either.
/// In that case, you have to specify your API-key using the `key` parameter (see the `param()`
/// function for details).
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<T, S>(mut self, scope: T) -> ProjectLocationInsightTypeInsightGetCall<'a, C, A>
where T: Into<Option<S>>,
S: AsRef<str> {
match scope.into() {
Some(scope) => self._scopes.insert(scope.as_ref().to_string(), ()),
None => None,
};
self
}
}