// DO NOT EDIT !
// This file was generated automatically from 'src/mako/api/lib.rs.mako'
// DO NOT EDIT !
//! This documentation was generated from *Vision* crate version *1.0.14+20200619*, where *20200619* is the exact revision of the *vision:v1* schema built by the [mako](http://www.makotemplates.org/) code generator *v1.0.14*.
//!
//! Everything else about the *Vision* *v1* API can be found at the
//! [official documentation site](https://cloud.google.com/vision/).
//! The original source code is [on github](https://github.com/Byron/google-apis-rs/tree/master/gen/vision1).
//! # Features
//!
//! Handle the following *Resources* with ease from the central [hub](struct.Vision.html) ...
//!
//! * files
//! * [*annotate*](struct.FileAnnotateCall.html) and [*async batch annotate*](struct.FileAsyncBatchAnnotateCall.html)
//! * [images](struct.Image.html)
//! * [*annotate*](struct.ImageAnnotateCall.html) and [*async batch annotate*](struct.ImageAsyncBatchAnnotateCall.html)
//! * locations
//! * [*operations get*](struct.LocationOperationGetCall.html)
//! * [operations](struct.Operation.html)
//! * [*cancel*](struct.OperationCancelCall.html), [*delete*](struct.OperationDeleteCall.html), [*get*](struct.OperationGetCall.html) and [*list*](struct.OperationListCall.html)
//! * projects
//! * [*files annotate*](struct.ProjectFileAnnotateCall.html), [*files async batch annotate*](struct.ProjectFileAsyncBatchAnnotateCall.html), [*images annotate*](struct.ProjectImageAnnotateCall.html), [*images async batch annotate*](struct.ProjectImageAsyncBatchAnnotateCall.html), [*locations files annotate*](struct.ProjectLocationFileAnnotateCall.html), [*locations files async batch annotate*](struct.ProjectLocationFileAsyncBatchAnnotateCall.html), [*locations images annotate*](struct.ProjectLocationImageAnnotateCall.html), [*locations images async batch annotate*](struct.ProjectLocationImageAsyncBatchAnnotateCall.html), [*locations operations get*](struct.ProjectLocationOperationGetCall.html), [*locations product sets add product*](struct.ProjectLocationProductSetAddProductCall.html), [*locations product sets create*](struct.ProjectLocationProductSetCreateCall.html), [*locations product sets delete*](struct.ProjectLocationProductSetDeleteCall.html), [*locations product sets get*](struct.ProjectLocationProductSetGetCall.html), [*locations product sets import*](struct.ProjectLocationProductSetImportCall.html), [*locations product sets list*](struct.ProjectLocationProductSetListCall.html), [*locations product sets patch*](struct.ProjectLocationProductSetPatchCall.html), [*locations product sets products list*](struct.ProjectLocationProductSetProductListCall.html), [*locations product sets remove product*](struct.ProjectLocationProductSetRemoveProductCall.html), [*locations products create*](struct.ProjectLocationProductCreateCall.html), [*locations products delete*](struct.ProjectLocationProductDeleteCall.html), [*locations products get*](struct.ProjectLocationProductGetCall.html), [*locations products list*](struct.ProjectLocationProductListCall.html), [*locations products patch*](struct.ProjectLocationProductPatchCall.html), [*locations products purge*](struct.ProjectLocationProductPurgeCall.html), [*locations products reference images create*](struct.ProjectLocationProductReferenceImageCreateCall.html), [*locations products reference images delete*](struct.ProjectLocationProductReferenceImageDeleteCall.html), [*locations products reference images get*](struct.ProjectLocationProductReferenceImageGetCall.html), [*locations products reference images list*](struct.ProjectLocationProductReferenceImageListCall.html) and [*operations get*](struct.ProjectOperationGetCall.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.Vision.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().operations_get(...).doit()
//! let r = hub.operations().list(...).doit()
//! let r = hub.projects().files_async_batch_annotate(...).doit()
//! let r = hub.images().async_batch_annotate(...).doit()
//! let r = hub.projects().images_async_batch_annotate(...).doit()
//! let r = hub.projects().locations_files_async_batch_annotate(...).doit()
//! let r = hub.operations().cancel(...).doit()
//! let r = hub.locations().operations_get(...).doit()
//! let r = hub.files().async_batch_annotate(...).doit()
//! let r = hub.operations().delete(...).doit()
//! let r = hub.projects().locations_images_async_batch_annotate(...).doit()
//! let r = hub.projects().locations_products_purge(...).doit()
//! let r = hub.operations().get(...).doit()
//! let r = hub.projects().locations_operations_get(...).doit()
//! let r = hub.projects().locations_product_sets_import(...).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-vision1 = "*"
//! # 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_vision1 as vision1;
//! use vision1::{Result, Error};
//! # #[test] fn egal() {
//! use std::default::Default;
//! use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
//! use vision1::Vision;
//!
//! // 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 = Vision::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.operations().list("name")
//! .page_token("dolores")
//! .page_size(-63)
//! .filter("accusam")
//! .doit();
//!
//! match result {
//! Err(e) => match e {
//! // The Error enum provides details about what exactly happened.
//! // You can also just use its `Debug`, `Display` or `Error` traits
//! Error::HttpError(_)
//! |Error::MissingAPIKey
//! |Error::MissingToken(_)
//! |Error::Cancelled
//! |Error::UploadSizeLimitExceeded(_, _)
//! |Error::Failure(_)
//! |Error::BadRequest(_)
//! |Error::FieldClash(_)
//! |Error::JsonDecodeError(_, _) => println!("{}", e),
//! },
//! Ok(res) => println!("Success: {:?}", res),
//! }
//! # }
//! ```
//! ## 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 {
/// Apply machine learning models to understand and label images
CloudVision,
/// View and manage your data across Google Cloud Platform services
CloudPlatform,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::CloudVision => "https://www.googleapis.com/auth/cloud-vision",
Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
}
}
}
impl Default for Scope {
fn default() -> Scope {
Scope::CloudVision
}
}
// ########
// HUB ###
// ######
/// Central instance to access all Vision 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_vision1 as vision1;
/// use vision1::{Result, Error};
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use vision1::Vision;
///
/// // 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 = Vision::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.operations().list("name")
/// .page_token("justo")
/// .page_size(-1)
/// .filter("erat")
/// .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 Vision<C, A> {
client: RefCell<C>,
auth: RefCell<A>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<'a, C, A> Hub for Vision<C, A> {}
impl<'a, C, A> Vision<C, A>
where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
pub fn new(client: C, authenticator: A) -> Vision<C, A> {
Vision {
client: RefCell::new(client),
auth: RefCell::new(authenticator),
_user_agent: "google-api-rust-client/1.0.14".to_string(),
_base_url: "https://vision.googleapis.com/".to_string(),
_root_url: "https://vision.googleapis.com/".to_string(),
}
}
pub fn files(&'a self) -> FileMethods<'a, C, A> {
FileMethods { hub: &self }
}
pub fn images(&'a self) -> ImageMethods<'a, C, A> {
ImageMethods { hub: &self }
}
pub fn locations(&'a self) -> LocationMethods<'a, C, A> {
LocationMethods { hub: &self }
}
pub fn operations(&'a self) -> OperationMethods<'a, C, A> {
OperationMethods { hub: &self }
}
pub fn projects(&'a self) -> ProjectMethods<'a, C, A> {
ProjectMethods { hub: &self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/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://vision.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://vision.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 async image annotation for a list of images.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 images async batch annotate projects](struct.ProjectLocationImageAsyncBatchAnnotateCall.html) (request)
/// * [async batch annotate images](struct.ImageAsyncBatchAnnotateCall.html) (request)
/// * [images async batch annotate projects](struct.ProjectImageAsyncBatchAnnotateCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AsyncBatchAnnotateImagesRequest {
/// Required. The desired output location and metadata (e.g. format).
#[serde(rename="outputConfig")]
pub output_config: Option<OutputConfig>,
/// Required. Individual image annotation requests for this batch.
pub requests: Option<Vec<AnnotateImageRequest>>,
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
pub parent: Option<String>,
}
impl RequestValue for AsyncBatchAnnotateImagesRequest {}
/// Request message for the `AddProductToProductSet` 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 product sets add product projects](struct.ProjectLocationProductSetAddProductCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AddProductToProductSetRequest {
/// Required. The resource name for the Product to be added to this ProductSet.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
pub product: Option<String>,
}
impl RequestValue for AddProductToProductSetRequest {}
/// A vertex represents a 2D point in the image.
/// NOTE: the vertex coordinates are in the same scale as the original image.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Vertex {
/// Y coordinate.
pub y: Option<i32>,
/// X coordinate.
pub x: Option<i32>,
}
impl Part for Vertex {}
/// A product label represented as a key-value pair.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct KeyValue {
/// The key of the label attached to the product. Cannot be empty and cannot
/// exceed 128 bytes.
pub key: Option<String>,
/// The value of the label attached to the product. Cannot be empty and
/// cannot exceed 128 bytes.
pub value: Option<String>,
}
impl Part for KeyValue {}
/// The desired output location 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 OutputConfig {
/// The max number of response protos to put into each output JSON file on
/// Google Cloud Storage.
/// The valid range is [1, 100]. If not specified, the default value is 20.
///
/// For example, for one pdf file with 100 pages, 100 response protos will
/// be generated. If `batch_size` = 20, then 5 json files each
/// containing 20 response protos will be written under the prefix
/// `gcs_destination`.`uri`.
///
/// Currently, batch_size only applies to GcsDestination, with potential future
/// support for other output configurations.
#[serde(rename="batchSize")]
pub batch_size: Option<i32>,
/// The Google Cloud Storage location to write the output(s) to.
#[serde(rename="gcsDestination")]
pub gcs_destination: Option<GcsDestination>,
}
impl Part for OutputConfig {}
/// Structural unit of text representing a number of words in certain order.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Paragraph {
/// The bounding box for the paragraph.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
///
/// * when the text is horizontal it might look like:
/// 0----1
/// | |
/// 3----2
/// * when it's rotated 180 degrees around the top-left corner it becomes:
/// 2----3
/// | |
/// 1----0
/// and the vertex order will still be (0, 1, 2, 3).
#[serde(rename="boundingBox")]
pub bounding_box: Option<BoundingPoly>,
/// Confidence of the OCR results for the paragraph. Range [0, 1].
pub confidence: Option<f32>,
/// Additional information detected for the paragraph.
pub property: Option<TextProperty>,
/// List of all words in this paragraph.
pub words: Option<Vec<Word>>,
}
impl Part for Paragraph {}
/// Multiple image annotation requests are batched into a single service call.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [annotate images](struct.ImageAnnotateCall.html) (request)
/// * [images annotate projects](struct.ProjectImageAnnotateCall.html) (request)
/// * [locations images annotate projects](struct.ProjectLocationImageAnnotateCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BatchAnnotateImagesRequest {
/// Required. Individual image annotation requests for this batch.
pub requests: Option<Vec<AnnotateImageRequest>>,
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
pub parent: Option<String>,
}
impl RequestValue for BatchAnnotateImagesRequest {}
/// Label to provide extra metadata for the web detection.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct WebLabel {
/// The BCP-47 language code for `label`, such as "en-US" or "sr-Latn".
/// For more information, see
/// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
#[serde(rename="languageCode")]
pub language_code: Option<String>,
/// Label for extra metadata.
pub label: Option<String>,
}
impl Part for WebLabel {}
/// TextAnnotation contains a structured representation of OCR extracted text.
/// The hierarchy of an OCR extracted text structure is like this:
/// TextAnnotation -> Page -> Block -> Paragraph -> Word -> Symbol
/// Each structural component, starting from Page, may further have their own
/// properties. Properties describe detected languages, breaks etc.. Please refer
/// to the TextAnnotation.TextProperty message definition below for more
/// detail.
///
/// This type is not used in any activity, and only used as *part* of another schema.
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TextAnnotation {
/// UTF-8 text detected on the pages.
pub text: Option<String>,
/// List of pages detected by OCR.
pub pages: Option<Vec<Page>>,
}
impl Part for TextAnnotation {}
/// Prediction for what the object in the bounding box is.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ObjectAnnotation {
/// The BCP-47 language code, such as "en-US" or "sr-Latn". For more
/// information, see
/// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
#[serde(rename="languageCode")]
pub language_code: Option<String>,
/// Score of the result. Range [0, 1].
pub score: Option<f32>,
/// Object ID that should align with EntityAnnotation mid.
pub mid: Option<String>,
/// Object name, expressed in its `language_code` language.
pub name: Option<String>,
}
impl Part for ObjectAnnotation {}
/// Stores image properties, such as dominant colors.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImageProperties {
/// If present, dominant colors completed successfully.
#[serde(rename="dominantColors")]
pub dominant_colors: Option<DominantColorsAnnotation>,
}
impl Part for ImageProperties {}
/// A list of requests to annotate files using the BatchAnnotateFiles API.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [files annotate projects](struct.ProjectFileAnnotateCall.html) (request)
/// * [annotate files](struct.FileAnnotateCall.html) (request)
/// * [locations files annotate projects](struct.ProjectLocationFileAnnotateCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BatchAnnotateFilesRequest {
/// Required. The list of file annotation requests. Right now we support only one
/// AnnotateFileRequest in BatchAnnotateFilesRequest.
pub requests: Option<Vec<AnnotateFileRequest>>,
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
pub parent: Option<String>,
}
impl RequestValue for BatchAnnotateFilesRequest {}
/// Information about the products similar to a single product in a query
/// image.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GroupedResult {
/// List of generic predictions for the object in the bounding box.
#[serde(rename="objectAnnotations")]
pub object_annotations: Option<Vec<ObjectAnnotation>>,
/// List of results, one for each product match.
pub results: Option<Vec<ResultType>>,
/// The bounding polygon around the product detected in the query image.
#[serde(rename="boundingPoly")]
pub bounding_poly: Option<BoundingPoly>,
}
impl Part for GroupedResult {}
/// An object representing a latitude/longitude pair. This is expressed as a pair
/// of doubles representing degrees latitude and degrees longitude. Unless
/// specified otherwise, this must conform to the
/// <a href="http://www.unoosa.org/pdf/icg/2012/template/WGS_84.pdf">WGS84
/// standard</a>. Values must be within normalized ranges.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LatLng {
/// The latitude in degrees. It must be in the range [-90.0, +90.0].
pub latitude: Option<f64>,
/// The longitude in degrees. It must be in the range [-180.0, +180.0].
pub longitude: Option<f64>,
}
impl Part for LatLng {}
/// Information about a product.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ResultType {
/// The resource name of the image from the product that is the closest match
/// to the query.
pub image: Option<String>,
/// A confidence level on the match, ranging from 0 (no confidence) to
/// 1 (full confidence).
pub score: Option<f32>,
/// The Product.
pub product: Option<Product>,
}
impl Part for ResultType {}
/// A request to annotate one single file, e.g. a PDF, TIFF or GIF file.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AnnotateFileRequest {
/// Additional context that may accompany the image(s) in the file.
#[serde(rename="imageContext")]
pub image_context: Option<ImageContext>,
/// Pages of the file to perform image annotation.
///
/// Pages starts from 1, we assume the first page of the file is page 1.
/// At most 5 pages are supported per request. Pages can be negative.
///
/// Page 1 means the first page.
/// Page 2 means the second page.
/// Page -1 means the last page.
/// Page -2 means the second to the last page.
///
/// If the file is GIF instead of PDF or TIFF, page refers to GIF frames.
///
/// If this field is empty, by default the service performs image annotation
/// for the first 5 pages of the file.
pub pages: Option<Vec<i32>>,
/// Required. Requested features.
pub features: Option<Vec<Feature>>,
/// Required. Information about the input file.
#[serde(rename="inputConfig")]
pub input_config: Option<InputConfig>,
}
impl Part for AnnotateFileRequest {}
/// Parameters for a product search request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ProductSearchParams {
/// The filtering expression. This can be used to restrict search results based
/// on Product labels. We currently support an AND of OR of key-value
/// expressions, where each expression within an OR must have the same key. An
/// '=' should be used to connect the key and value.
///
/// For example, "(color = red OR color = blue) AND brand = Google" is
/// acceptable, but "(color = red OR brand = Google)" is not acceptable.
/// "color: red" is not acceptable because it uses a ':' instead of an '='.
pub filter: Option<String>,
/// The list of product categories to search in. Currently, we only consider
/// the first category, and either "homegoods-v2", "apparel-v2", "toys-v2",
/// "packagedgoods-v1", or "general-v1" should be specified. The legacy
/// categories "homegoods", "apparel", and "toys" are still supported but will
/// be deprecated. For new products, please use "homegoods-v2", "apparel-v2",
/// or "toys-v2" for better product search accuracy. It is recommended to
/// migrate existing products to these categories as well.
#[serde(rename="productCategories")]
pub product_categories: Option<Vec<String>>,
/// The resource name of a ProductSet to be searched for similar images.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
#[serde(rename="productSet")]
pub product_set: Option<String>,
/// The bounding polygon around the area of interest in the image.
/// If it is not specified, system discretion will be applied.
#[serde(rename="boundingPoly")]
pub bounding_poly: Option<BoundingPoly>,
}
impl Part for ProductSearchParams {}
/// The `Status` type defines a logical error model that is suitable for
/// different programming environments, including REST APIs and RPC APIs. It is
/// used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details.
///
/// You can find out more about this error model and how to work with it in the
/// [API Design Guide](https://cloud.google.com/apis/design/errors).
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Status {
/// A developer-facing error message, which should be in English. Any
/// user-facing error message should be localized and sent in the
/// google.rpc.Status.details field, or localized by the client.
pub message: Option<String>,
/// The status code, which should be an enum value of google.rpc.Code.
pub code: Option<i32>,
/// A list of messages that carry the error details. There is a common set of
/// message types for APIs to use.
pub details: Option<Vec<HashMap<String, String>>>,
}
impl Part for Status {}
/// Additional information detected on the structural component.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct TextProperty {
/// Detected start or end of a text segment.
#[serde(rename="detectedBreak")]
pub detected_break: Option<DetectedBreak>,
/// A list of detected languages together with confidence.
#[serde(rename="detectedLanguages")]
pub detected_languages: Option<Vec<DetectedLanguage>>,
}
impl Part for TextProperty {}
/// Logical element on the page.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Block {
/// The bounding box for the block.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
///
/// * when the text is horizontal it might look like:
///
/// ````text
/// 0----1
/// | |
/// 3----2
/// ````
///
/// * when it's rotated 180 degrees around the top-left corner it becomes:
///
/// ````text
/// 2----3
/// | |
/// 1----0
/// ````
///
/// and the vertex order will still be (0, 1, 2, 3).
#[serde(rename="boundingBox")]
pub bounding_box: Option<BoundingPoly>,
/// Detected block type (text, image etc) for this block.
#[serde(rename="blockType")]
pub block_type: Option<String>,
/// Additional information detected for the block.
pub property: Option<TextProperty>,
/// Confidence of the OCR results on the block. Range [0, 1].
pub confidence: Option<f32>,
/// List of paragraphs in this block (if this blocks is of type text).
pub paragraphs: Option<Vec<Paragraph>>,
}
impl Part for Block {}
/// The type of Google Cloud Vision API detection to perform, and the maximum
/// number of results to return for that type. Multiple `Feature` objects can
/// be specified in the `features` list.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Feature {
/// Model to use for the feature.
/// Supported values: "builtin/stable" (the default if unset) and
/// "builtin/latest".
pub model: Option<String>,
/// The feature type.
#[serde(rename="type")]
pub type_: Option<String>,
/// Maximum number of results of this type. Does not apply to
/// `TEXT_DETECTION`, `DOCUMENT_TEXT_DETECTION`, or `CROP_HINTS`.
#[serde(rename="maxResults")]
pub max_results: Option<i32>,
}
impl Part for Feature {}
/// Response message for the `ListReferenceImages` 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 products reference images list projects](struct.ProjectLocationProductReferenceImageListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ListReferenceImagesResponse {
/// The next_page_token returned from a previous List request, if any.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// The maximum number of items to return. Default 10, maximum 100.
#[serde(rename="pageSize")]
pub page_size: Option<i32>,
/// The list of reference images.
#[serde(rename="referenceImages")]
pub reference_images: Option<Vec<ReferenceImage>>,
}
impl ResponseResult for ListReferenceImagesResponse {}
/// Detected language for a structural component.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct DetectedLanguage {
/// The BCP-47 language code, such as "en-US" or "sr-Latn". For more
/// information, see
/// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
#[serde(rename="languageCode")]
pub language_code: Option<String>,
/// Confidence of detected language. Range [0, 1].
pub confidence: Option<f32>,
}
impl Part for DetectedLanguage {}
/// Parameters for crop hints annotation request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CropHintsParams {
/// Aspect ratios in floats, representing the ratio of the width to the height
/// of the image. For example, if the desired aspect ratio is 4/3, the
/// corresponding float value should be 1.33333. If not specified, the
/// best possible crop is returned. The number of provided aspect ratios is
/// limited to a maximum of 16; any aspect ratios provided after the 16th are
/// ignored.
#[serde(rename="aspectRatios")]
pub aspect_ratios: Option<Vec<f32>>,
}
impl Part for CropHintsParams {}
/// A vertex represents a 2D point in the image.
/// NOTE: the normalized vertex coordinates are relative to the original image
/// and range from 0 to 1.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct NormalizedVertex {
/// Y coordinate.
pub y: Option<f32>,
/// X coordinate.
pub x: Option<f32>,
}
impl Part for NormalizedVertex {}
/// Request for performing Google Cloud Vision API tasks over a user-provided
/// image, with user-requested features, and with context information.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AnnotateImageRequest {
/// Additional context that may accompany the image.
#[serde(rename="imageContext")]
pub image_context: Option<ImageContext>,
/// The image to be processed.
pub image: Option<Image>,
/// Requested features.
pub features: Option<Vec<Feature>>,
}
impl Part for AnnotateImageRequest {}
/// Set of crop hints that are used to generate new crops when serving images.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CropHintsAnnotation {
/// Crop hint results.
#[serde(rename="cropHints")]
pub crop_hints: Option<Vec<CropHint>>,
}
impl Part for CropHintsAnnotation {}
/// Set of detected entity features.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct EntityAnnotation {
/// **Deprecated. Use `score` instead.**
/// The accuracy of the entity detection in an image.
/// For example, for an image in which the "Eiffel Tower" entity is detected,
/// this field represents the confidence that there is a tower in the query
/// image. Range [0, 1].
pub confidence: Option<f32>,
/// Entity textual description, expressed in its `locale` language.
pub description: Option<String>,
/// The language code for the locale in which the entity textual
/// `description` is expressed.
pub locale: Option<String>,
/// The relevancy of the ICA (Image Content Annotation) label to the
/// image. For example, the relevancy of "tower" is likely higher to an image
/// containing the detected "Eiffel Tower" than to an image containing a
/// detected distant towering building, even though the confidence that
/// there is a tower in each image may be the same. Range [0, 1].
pub topicality: Option<f32>,
/// The location information for the detected entity. Multiple
/// `LocationInfo` elements can be present because one location may
/// indicate the location of the scene in the image, and another location
/// may indicate the location of the place where the image was taken.
/// Location information is usually present for landmarks.
pub locations: Option<Vec<LocationInfo>>,
/// Opaque entity ID. Some IDs may be available in
/// [Google Knowledge Graph Search
/// API](https://developers.google.com/knowledge-graph/).
pub mid: Option<String>,
/// Overall score of the result. Range [0, 1].
pub score: Option<f32>,
/// Image region to which this entity belongs. Not produced
/// for `LABEL_DETECTION` features.
#[serde(rename="boundingPoly")]
pub bounding_poly: Option<BoundingPoly>,
/// Some entities may have optional user-supplied `Property` (name/value)
/// fields, such a score or string that qualifies the entity.
pub properties: Option<Vec<Property>>,
}
impl Part for EntityAnnotation {}
/// Parameters for web detection request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct WebDetectionParams {
/// Whether to include results derived from the geo information in the image.
#[serde(rename="includeGeoResults")]
pub include_geo_results: Option<bool>,
}
impl Part for WebDetectionParams {}
/// Metadata for online images.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct WebImage {
/// The result image URL.
pub url: Option<String>,
/// (Deprecated) Overall relevancy score for the image.
pub score: Option<f32>,
}
impl Part for WebImage {}
/// A Product contains ReferenceImages.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 products get projects](struct.ProjectLocationProductGetCall.html) (response)
/// * [locations products patch projects](struct.ProjectLocationProductPatchCall.html) (request|response)
/// * [locations products create projects](struct.ProjectLocationProductCreateCall.html) (request|response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Product {
/// Key-value pairs that can be attached to a product. At query time,
/// constraints can be specified based on the product_labels.
///
/// Note that integer values can be provided as strings, e.g. "1199". Only
/// strings with integer values can match a range-based restriction which is
/// to be supported soon.
///
/// Multiple values can be assigned to the same key. One product may have up to
/// 500 product_labels.
///
/// Notice that the total number of distinct product_labels over all products
/// in one ProductSet cannot exceed 1M, otherwise the product search pipeline
/// will refuse to work for that ProductSet.
#[serde(rename="productLabels")]
pub product_labels: Option<Vec<KeyValue>>,
/// The user-provided name for this Product. Must not be empty. Must be at most
/// 4096 characters long.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// User-provided metadata to be stored with this product. Must be at most 4096
/// characters long.
pub description: Option<String>,
/// Immutable. The category for the product identified by the reference image. This should
/// be either "homegoods-v2", "apparel-v2", or "toys-v2". The legacy categories
/// "homegoods", "apparel", and "toys" are still supported, but these should
/// not be used for new products.
#[serde(rename="productCategory")]
pub product_category: Option<String>,
/// The resource name of the product.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
///
/// This field is ignored when creating a product.
pub name: Option<String>,
}
impl RequestValue for Product {}
impl ResponseResult for Product {}
/// Set of features pertaining to the image, computed by computer vision
/// methods over safe-search verticals (for example, adult, spoof, medical,
/// violence).
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct SafeSearchAnnotation {
/// Likelihood that this is a medical image.
pub medical: Option<String>,
/// Likelihood that this image contains violent content.
pub violence: Option<String>,
/// Spoof likelihood. The likelihood that an modification
/// was made to the image's canonical version to make it appear
/// funny or offensive.
pub spoof: Option<String>,
/// Likelihood that the request image contains racy content. Racy content may
/// include (but is not limited to) skimpy or sheer clothing, strategically
/// covered nudity, lewd or provocative poses, or close-ups of sensitive
/// body areas.
pub racy: Option<String>,
/// Represents the adult content likelihood for the image. Adult content may
/// contain elements such as nudity, pornographic images or cartoons, or
/// sexual activities.
pub adult: Option<String>,
}
impl Part for SafeSearchAnnotation {}
/// The request message for Operations.CancelOperation.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [cancel operations](struct.OperationCancelCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CancelOperationRequest { _never_set: Option<bool> }
impl RequestValue for CancelOperationRequest {}
/// Config to control which ProductSet contains the Products to be deleted.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ProductSetPurgeConfig {
/// The ProductSet that contains the Products to delete. If a Product is a
/// member of product_set_id in addition to other ProductSets, the Product will
/// still be deleted.
#[serde(rename="productSetId")]
pub product_set_id: Option<String>,
}
impl Part for ProductSetPurgeConfig {}
/// Color information consists of RGB channels, score, and the fraction of
/// the image that the color occupies in the image.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ColorInfo {
/// RGB components of the color.
pub color: Option<Color>,
/// The fraction of pixels the color occupies in the image.
/// Value in range [0, 1].
#[serde(rename="pixelFraction")]
pub pixel_fraction: Option<f32>,
/// Image-specific score for this color. Value in range [0, 1].
pub score: Option<f32>,
}
impl Part for ColorInfo {}
/// An offline file annotation request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AsyncAnnotateFileRequest {
/// Additional context that may accompany the image(s) in the file.
#[serde(rename="imageContext")]
pub image_context: Option<ImageContext>,
/// Required. The desired output location and metadata (e.g. format).
#[serde(rename="outputConfig")]
pub output_config: Option<OutputConfig>,
/// Required. Requested features.
pub features: Option<Vec<Feature>>,
/// Required. Information about the input file.
#[serde(rename="inputConfig")]
pub input_config: Option<InputConfig>,
}
impl Part for AsyncAnnotateFileRequest {}
/// Response message for the `ListProductSets` 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 product sets list projects](struct.ProjectLocationProductSetListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ListProductSetsResponse {
/// Token to retrieve the next page of results, or empty if there are no more
/// results in the list.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// List of ProductSets.
#[serde(rename="productSets")]
pub product_sets: Option<Vec<ProductSet>>,
}
impl ResponseResult for ListProductSetsResponse {}
/// Response to an image annotation request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AnnotateImageResponse {
/// If present, safe-search annotation has completed successfully.
#[serde(rename="safeSearchAnnotation")]
pub safe_search_annotation: Option<SafeSearchAnnotation>,
/// If present, image properties were extracted successfully.
#[serde(rename="imagePropertiesAnnotation")]
pub image_properties_annotation: Option<ImageProperties>,
/// If present, web detection has completed successfully.
#[serde(rename="webDetection")]
pub web_detection: Option<WebDetection>,
/// If present, localized object detection has completed successfully.
/// This will be sorted descending by confidence score.
#[serde(rename="localizedObjectAnnotations")]
pub localized_object_annotations: Option<Vec<LocalizedObjectAnnotation>>,
/// If present, text (OCR) detection or document (OCR) text detection has
/// completed successfully.
/// This annotation provides the structural hierarchy for the OCR detected
/// text.
#[serde(rename="fullTextAnnotation")]
pub full_text_annotation: Option<TextAnnotation>,
/// If present, label detection has completed successfully.
#[serde(rename="labelAnnotations")]
pub label_annotations: Option<Vec<EntityAnnotation>>,
/// If present, text (OCR) detection has completed successfully.
#[serde(rename="textAnnotations")]
pub text_annotations: Option<Vec<EntityAnnotation>>,
/// If present, face detection has completed successfully.
#[serde(rename="faceAnnotations")]
pub face_annotations: Option<Vec<FaceAnnotation>>,
/// If present, product search has completed successfully.
#[serde(rename="productSearchResults")]
pub product_search_results: Option<ProductSearchResults>,
/// If present, logo detection has completed successfully.
#[serde(rename="logoAnnotations")]
pub logo_annotations: Option<Vec<EntityAnnotation>>,
/// If present, landmark detection has completed successfully.
#[serde(rename="landmarkAnnotations")]
pub landmark_annotations: Option<Vec<EntityAnnotation>>,
/// If present, contextual information is needed to understand where this image
/// comes from.
pub context: Option<ImageAnnotationContext>,
/// If set, represents the error message for the operation.
/// Note that filled-in image annotations are guaranteed to be
/// correct, even when `error` is set.
pub error: Option<Status>,
/// If present, crop hints have completed successfully.
#[serde(rename="cropHintsAnnotation")]
pub crop_hints_annotation: Option<CropHintsAnnotation>,
}
impl Part for AnnotateImageResponse {}
/// A ProductSet contains Products. A ProductSet can contain a maximum of 1
/// million reference images. If the limit is exceeded, periodic indexing will
/// fail.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 product sets get projects](struct.ProjectLocationProductSetGetCall.html) (response)
/// * [locations product sets create projects](struct.ProjectLocationProductSetCreateCall.html) (request|response)
/// * [locations product sets patch projects](struct.ProjectLocationProductSetPatchCall.html) (request|response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ProductSet {
/// The user-provided name for this ProductSet. Must not be empty. Must be at
/// most 4096 characters long.
#[serde(rename="displayName")]
pub display_name: Option<String>,
/// Output only. If there was an error with indexing the product set, the field
/// is populated.
///
/// This field is ignored when creating a ProductSet.
#[serde(rename="indexError")]
pub index_error: Option<Status>,
/// The resource name of the ProductSet.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
///
/// This field is ignored when creating a ProductSet.
pub name: Option<String>,
/// Output only. The time at which this ProductSet was last indexed. Query
/// results will reflect all updates before this time. If this ProductSet has
/// never been indexed, this timestamp is the default value
/// "1970-01-01T00:00:00Z".
///
/// This field is ignored when creating a ProductSet.
#[serde(rename="indexTime")]
pub index_time: Option<String>,
}
impl RequestValue for ProductSet {}
impl ResponseResult for ProductSet {}
/// Metadata for web pages.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct WebPage {
/// Title for the web page, may contain HTML markups.
#[serde(rename="pageTitle")]
pub page_title: Option<String>,
/// The result web page URL.
pub url: Option<String>,
/// (Deprecated) Overall relevancy score for the web page.
pub score: Option<f32>,
/// Partial matching images on the page.
/// Those images are similar enough to share some key-point features. For
/// example an original image will likely have partial matching for its
/// crops.
#[serde(rename="partialMatchingImages")]
pub partial_matching_images: Option<Vec<WebImage>>,
/// Fully matching images on the page.
/// Can include resized copies of the query image.
#[serde(rename="fullMatchingImages")]
pub full_matching_images: Option<Vec<WebImage>>,
}
impl Part for WebPage {}
/// The Google Cloud Storage location where the input will be read from.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GcsSource {
/// Google Cloud Storage URI for the input file. This must only be a
/// Google Cloud Storage object. Wildcards are not currently supported.
pub uri: Option<String>,
}
impl Part for GcsSource {}
/// A face-specific landmark (for example, a face feature).
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Landmark {
/// Face landmark position.
pub position: Option<Position>,
/// Face landmark type.
#[serde(rename="type")]
pub type_: Option<String>,
}
impl Part for Landmark {}
/// A 3D position in the image, used primarily for Face detection landmarks.
/// A valid Position must have both x and y coordinates.
/// The position coordinates are in the same scale as the original image.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Position {
/// Y coordinate.
pub y: Option<f32>,
/// X coordinate.
pub x: Option<f32>,
/// Z coordinate (or depth).
pub z: Option<f32>,
}
impl Part for Position {}
/// Request message for the `ImportProductSets` 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 product sets import projects](struct.ProjectLocationProductSetImportCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImportProductSetsRequest {
/// Required. The input content for the list of requests.
#[serde(rename="inputConfig")]
pub input_config: Option<ImportProductSetsInputConfig>,
}
impl RequestValue for ImportProductSetsRequest {}
/// The input content for the `ImportProductSets` method.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImportProductSetsInputConfig {
/// The Google Cloud Storage location for a csv file which preserves a list
/// of ImportProductSetRequests in each line.
#[serde(rename="gcsSource")]
pub gcs_source: Option<ImportProductSetsGcsSource>,
}
impl Part for ImportProductSetsInputConfig {}
/// This resource represents a long-running operation that is the result of a
/// network API call.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [operations get projects](struct.ProjectOperationGetCall.html) (response)
/// * [list operations](struct.OperationListCall.html) (none)
/// * [files async batch annotate projects](struct.ProjectFileAsyncBatchAnnotateCall.html) (response)
/// * [async batch annotate images](struct.ImageAsyncBatchAnnotateCall.html) (response)
/// * [images async batch annotate projects](struct.ProjectImageAsyncBatchAnnotateCall.html) (response)
/// * [locations files async batch annotate projects](struct.ProjectLocationFileAsyncBatchAnnotateCall.html) (response)
/// * [cancel operations](struct.OperationCancelCall.html) (none)
/// * [operations get locations](struct.LocationOperationGetCall.html) (response)
/// * [async batch annotate files](struct.FileAsyncBatchAnnotateCall.html) (response)
/// * [delete operations](struct.OperationDeleteCall.html) (none)
/// * [locations images async batch annotate projects](struct.ProjectLocationImageAsyncBatchAnnotateCall.html) (response)
/// * [locations products purge projects](struct.ProjectLocationProductPurgeCall.html) (response)
/// * [get operations](struct.OperationGetCall.html) (response)
/// * [locations operations get projects](struct.ProjectLocationOperationGetCall.html) (response)
/// * [locations product sets import projects](struct.ProjectLocationProductSetImportCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Operation {
/// The error result of the operation in case of failure or cancellation.
pub error: Option<Status>,
/// If the value is `false`, it means the operation is still in progress.
/// If `true`, the operation is completed, and either `error` or `response` is
/// available.
pub done: Option<bool>,
/// The normal response of the operation in case of success. If the original
/// method returns no data on success, such as `Delete`, the response is
/// `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other
/// methods, the response should have the type `XxxResponse`, where `Xxx`
/// is the original method name. For example, if the original method name
/// is `TakeSnapshot()`, the inferred response type is
/// `TakeSnapshotResponse`.
pub response: Option<HashMap<String, String>>,
/// The server-assigned name, which is only unique within the same service that
/// originally returns it. If you use the default HTTP mapping, the
/// `name` should be a resource name ending with `operations/{unique_id}`.
pub name: Option<String>,
/// Service-specific metadata associated with the operation. It typically
/// contains progress information and common metadata such as create time.
/// Some services might not provide such metadata. Any method that returns a
/// long-running operation should document the metadata type, if any.
pub metadata: Option<HashMap<String, String>>,
}
impl Resource for Operation {}
impl ResponseResult for Operation {}
/// The Google Cloud Storage location for a csv file which preserves a list of
/// ImportProductSetRequests in each line.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImportProductSetsGcsSource {
/// The Google Cloud Storage URI of the input csv file.
///
/// The URI must start with `gs://`.
///
/// The format of the input csv file should be one image per line.
/// In each line, there are 8 columns.
///
/// 1. image-uri
/// 1. image-id
/// 1. product-set-id
/// 1. product-id
/// 1. product-category
/// 1. product-display-name
/// 1. labels
/// 1. bounding-poly
///
/// The `image-uri`, `product-set-id`, `product-id`, and `product-category`
/// columns are required. All other columns are optional.
///
/// If the `ProductSet` or `Product` specified by the `product-set-id` and
/// `product-id` values does not exist, then the system will create a new
/// `ProductSet` or `Product` for the image. In this case, the
/// `product-display-name` column refers to
/// display_name, the
/// `product-category` column refers to
/// product_category, and the
/// `labels` column refers to product_labels.
///
/// The `image-id` column is optional but must be unique if provided. If it is
/// empty, the system will automatically assign a unique id to the image.
///
/// The `product-display-name` column is optional. If it is empty, the system
/// sets the display_name field for the product to a
/// space (" "). You can update the `display_name` later by using the API.
///
/// If a `Product` with the specified `product-id` already exists, then the
/// system ignores the `product-display-name`, `product-category`, and `labels`
/// columns.
///
/// The `labels` column (optional) is a line containing a list of
/// comma-separated key-value pairs, in the following format:
///
/// ````text
/// "key_1=value_1,key_2=value_2,...,key_n=value_n"
/// ````
///
/// The `bounding-poly` column (optional) identifies one region of
/// interest from the image in the same manner as `CreateReferenceImage`. If
/// you do not specify the `bounding-poly` column, then the system will try to
/// detect regions of interest automatically.
///
/// At most one `bounding-poly` column is allowed per line. If the image
/// contains multiple regions of interest, add a line to the CSV file that
/// includes the same product information, and the `bounding-poly` values for
/// each region of interest.
///
/// The `bounding-poly` column must contain an even number of comma-separated
/// numbers, in the format "p1_x,p1_y,p2_x,p2_y,...,pn_x,pn_y". Use
/// non-negative integers for absolute bounding polygons, and float values
/// in [0, 1] for normalized bounding polygons.
///
/// The system will resize the image if the image resolution is too
/// large to process (larger than 20MP).
#[serde(rename="csvFileUri")]
pub csv_file_uri: Option<String>,
}
impl Part for ImportProductSetsGcsSource {}
/// Response to a batch image annotation request.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [annotate images](struct.ImageAnnotateCall.html) (response)
/// * [images annotate projects](struct.ProjectImageAnnotateCall.html) (response)
/// * [locations images annotate projects](struct.ProjectLocationImageAnnotateCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BatchAnnotateImagesResponse {
/// Individual responses to image annotation requests within the batch.
pub responses: Option<Vec<AnnotateImageResponse>>,
}
impl ResponseResult for BatchAnnotateImagesResponse {}
/// The desired input location 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 InputConfig {
/// File content, represented as a stream of bytes.
/// Note: As with all `bytes` fields, protobuffers use a pure binary
/// representation, whereas JSON representations use base64.
///
/// Currently, this field only works for BatchAnnotateFiles requests. It does
/// not work for AsyncBatchAnnotateFiles requests.
pub content: Option<String>,
/// The type of the file. Currently only "application/pdf", "image/tiff" and
/// "image/gif" are supported. Wildcards are not supported.
#[serde(rename="mimeType")]
pub mime_type: Option<String>,
/// The Google Cloud Storage location to read the input from.
#[serde(rename="gcsSource")]
pub gcs_source: Option<GcsSource>,
}
impl Part for InputConfig {}
/// Rectangle determined by min and max `LatLng` pairs.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LatLongRect {
/// Min lat/long pair.
#[serde(rename="minLatLng")]
pub min_lat_lng: Option<LatLng>,
/// Max lat/long pair.
#[serde(rename="maxLatLng")]
pub max_lat_lng: Option<LatLng>,
}
impl Part for LatLongRect {}
/// Request message for the `RemoveProductFromProductSet` 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 product sets remove product projects](struct.ProjectLocationProductSetRemoveProductCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct RemoveProductFromProductSetRequest {
/// Required. The resource name for the Product to be removed from this ProductSet.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
pub product: Option<String>,
}
impl RequestValue for RemoveProductFromProductSetRequest {}
/// Set of detected objects with bounding boxes.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LocalizedObjectAnnotation {
/// The BCP-47 language code, such as "en-US" or "sr-Latn". For more
/// information, see
/// http://www.unicode.org/reports/tr35/#Unicode_locale_identifier.
#[serde(rename="languageCode")]
pub language_code: Option<String>,
/// Score of the result. Range [0, 1].
pub score: Option<f32>,
/// Object ID that should align with EntityAnnotation mid.
pub mid: Option<String>,
/// Image region to which this object belongs. This must be populated.
#[serde(rename="boundingPoly")]
pub bounding_poly: Option<BoundingPoly>,
/// Object name, expressed in its `language_code` language.
pub name: Option<String>,
}
impl Part for LocalizedObjectAnnotation {}
/// The Google Cloud Storage location where the output will be written to.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct GcsDestination {
/// Google Cloud Storage URI prefix where the results will be stored. Results
/// will be in JSON format and preceded by its corresponding input URI prefix.
/// This field can either represent a gcs file prefix or gcs directory. In
/// either case, the uri should be unique because in order to get all of the
/// output files, you will need to do a wildcard gcs search on the uri prefix
/// you provide.
///
/// Examples:
///
/// * File Prefix: gs://bucket-name/here/filenameprefix The output files
/// will be created in gs://bucket-name/here/ and the names of the
/// output files will begin with "filenameprefix".
///
/// * Directory Prefix: gs://bucket-name/some/location/ The output files
/// will be created in gs://bucket-name/some/location/ and the names of the
/// output files could be anything because there was no filename prefix
/// specified.
///
/// If multiple outputs, each response is still AnnotateFileResponse, each of
/// which contains some subset of the full list of AnnotateImageResponse.
/// Multiple outputs can happen if, for example, the output JSON is too large
/// and overflows into multiple sharded files.
pub uri: Option<String>,
}
impl Part for GcsDestination {}
/// A list of file annotation responses.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [files annotate projects](struct.ProjectFileAnnotateCall.html) (response)
/// * [annotate files](struct.FileAnnotateCall.html) (response)
/// * [locations files annotate projects](struct.ProjectLocationFileAnnotateCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BatchAnnotateFilesResponse {
/// The list of file annotation responses, each response corresponding to each
/// AnnotateFileRequest in BatchAnnotateFilesRequest.
pub responses: Option<Vec<AnnotateFileResponse>>,
}
impl ResponseResult for BatchAnnotateFilesResponse {}
/// Response message for the `ListProductsInProductSet` 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 product sets products list projects](struct.ProjectLocationProductSetProductListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ListProductsInProductSetResponse {
/// Token to retrieve the next page of results, or empty if there are no more
/// results in the list.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// The list of Products.
pub products: Option<Vec<Product>>,
}
impl ResponseResult for ListProductsInProductSetResponse {}
/// Detected entity location information.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct LocationInfo {
/// lat/long location coordinates.
#[serde(rename="latLng")]
pub lat_lng: Option<LatLng>,
}
impl Part for LocationInfo {}
/// Multiple async file annotation requests are batched into a single service
/// call.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [files async batch annotate projects](struct.ProjectFileAsyncBatchAnnotateCall.html) (request)
/// * [async batch annotate files](struct.FileAsyncBatchAnnotateCall.html) (request)
/// * [locations files async batch annotate projects](struct.ProjectLocationFileAsyncBatchAnnotateCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AsyncBatchAnnotateFilesRequest {
/// Required. Individual async file annotation requests for this batch.
pub requests: Option<Vec<AsyncAnnotateFileRequest>>,
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
pub parent: Option<String>,
}
impl RequestValue for AsyncBatchAnnotateFilesRequest {}
/// A `Property` consists of a user-supplied name/value pair.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Property {
/// Value of numeric properties.
#[serde(rename="uint64Value")]
pub uint64_value: Option<String>,
/// Name of the property.
pub name: Option<String>,
/// Value of the property.
pub value: Option<String>,
}
impl Part for Property {}
/// Set of dominant colors and their corresponding scores.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct DominantColorsAnnotation {
/// RGB color values with their score and pixel fraction.
pub colors: Option<Vec<ColorInfo>>,
}
impl Part for DominantColorsAnnotation {}
/// Client image to perform Google Cloud Vision API tasks over.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [annotate images](struct.ImageAnnotateCall.html) (none)
/// * [async batch annotate images](struct.ImageAsyncBatchAnnotateCall.html) (none)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Image {
/// Image content, represented as a stream of bytes.
/// Note: As with all `bytes` fields, protobuffers use a pure binary
/// representation, whereas JSON representations use base64.
pub content: Option<String>,
/// Google Cloud Storage image location, or publicly-accessible image
/// URL. If both `content` and `source` are provided for an image, `content`
/// takes precedence and is used to perform the image annotation request.
pub source: Option<ImageSource>,
}
impl Resource for Image {}
/// Entity deduced from similar images on the Internet.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct WebEntity {
/// Opaque entity ID.
#[serde(rename="entityId")]
pub entity_id: Option<String>,
/// Overall relevancy score for the entity.
/// Not normalized and not comparable across different image queries.
pub score: Option<f32>,
/// Canonical description of the entity, in English.
pub description: Option<String>,
}
impl Part for WebEntity {}
/// A word representation.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Word {
/// The bounding box for the word.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
///
/// * when the text is horizontal it might look like:
/// 0----1
/// | |
/// 3----2
/// * when it's rotated 180 degrees around the top-left corner it becomes:
/// 2----3
/// | |
/// 1----0
/// and the vertex order will still be (0, 1, 2, 3).
#[serde(rename="boundingBox")]
pub bounding_box: Option<BoundingPoly>,
/// List of symbols in the word.
/// The order of the symbols follows the natural reading order.
pub symbols: Option<Vec<Symbol>>,
/// Confidence of the OCR results for the word. Range [0, 1].
pub confidence: Option<f32>,
/// Additional information detected for the word.
pub property: Option<TextProperty>,
}
impl Part for Word {}
/// Response message for the `ListProducts` 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 products list projects](struct.ProjectLocationProductListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ListProductsResponse {
/// Token to retrieve the next page of results, or empty if there are no more
/// results in the list.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// List of products.
pub products: Option<Vec<Product>>,
}
impl ResponseResult for ListProductsResponse {}
/// A generic empty message that you can re-use to avoid defining duplicated
/// empty messages in your APIs. A typical example is to use it as the request
/// or the response type of an API method. For instance:
///
/// ````text
/// service Foo {
/// rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty);
/// }
/// ````
///
/// The JSON representation for `Empty` is empty JSON object `{}`.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [delete operations](struct.OperationDeleteCall.html) (response)
/// * [locations product sets delete projects](struct.ProjectLocationProductSetDeleteCall.html) (response)
/// * [locations products delete projects](struct.ProjectLocationProductDeleteCall.html) (response)
/// * [cancel operations](struct.OperationCancelCall.html) (response)
/// * [locations products reference images delete projects](struct.ProjectLocationProductReferenceImageDeleteCall.html) (response)
/// * [locations product sets add product projects](struct.ProjectLocationProductSetAddProductCall.html) (response)
/// * [locations product sets remove product projects](struct.ProjectLocationProductSetRemoveProductCall.html) (response)
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Empty { _never_set: Option<bool> }
impl ResponseResult for Empty {}
/// If an image was produced from a file (e.g. a PDF), this message gives
/// information about the source of that image.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImageAnnotationContext {
/// If the file was a PDF or TIFF, this field gives the page number within
/// the file used to produce the image.
#[serde(rename="pageNumber")]
pub page_number: Option<i32>,
/// The URI of the file used to produce the image.
pub uri: Option<String>,
}
impl Part for ImageAnnotationContext {}
/// A single symbol representation.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Symbol {
/// The bounding box for the symbol.
/// The vertices are in the order of top-left, top-right, bottom-right,
/// bottom-left. When a rotation of the bounding box is detected the rotation
/// is represented as around the top-left corner as defined when the text is
/// read in the 'natural' orientation.
/// For example:
///
/// * when the text is horizontal it might look like:
/// 0----1
/// | |
/// 3----2
/// * when it's rotated 180 degrees around the top-left corner it becomes:
/// 2----3
/// | |
/// 1----0
/// and the vertex order will still be (0, 1, 2, 3).
#[serde(rename="boundingBox")]
pub bounding_box: Option<BoundingPoly>,
/// The actual UTF-8 representation of the symbol.
pub text: Option<String>,
/// Confidence of the OCR results for the symbol. Range [0, 1].
pub confidence: Option<f32>,
/// Additional information detected for the symbol.
pub property: Option<TextProperty>,
}
impl Part for Symbol {}
/// External image source (Google Cloud Storage or web URL image location).
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImageSource {
/// **Use `image_uri` instead.**
///
/// The Google Cloud Storage URI of the form
/// `gs://bucket_name/object_name`. Object versioning is not supported. See
/// [Google Cloud Storage Request
/// URIs](https://cloud.google.com/storage/docs/reference-uris) for more info.
#[serde(rename="gcsImageUri")]
pub gcs_image_uri: Option<String>,
/// The URI of the source image. Can be either:
///
/// 1. A Google Cloud Storage URI of the form
/// `gs://bucket_name/object_name`. Object versioning is not supported. See
/// [Google Cloud Storage Request
/// URIs](https://cloud.google.com/storage/docs/reference-uris) for more
/// info.
///
/// 2. A publicly-accessible image HTTP/HTTPS URL. When fetching images from
/// HTTP/HTTPS URLs, Google cannot guarantee that the request will be
/// completed. Your request may fail if the specified host denies the
/// request (e.g. due to request throttling or DOS prevention), or if Google
/// throttles requests to the site for abuse prevention. You should not
/// depend on externally-hosted images for production applications.
///
/// When both `gcs_image_uri` and `image_uri` are specified, `image_uri` takes
/// precedence.
#[serde(rename="imageUri")]
pub image_uri: Option<String>,
}
impl Part for ImageSource {}
/// A bounding polygon for the detected image annotation.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct BoundingPoly {
/// The bounding polygon normalized vertices.
#[serde(rename="normalizedVertices")]
pub normalized_vertices: Option<Vec<NormalizedVertex>>,
/// The bounding polygon vertices.
pub vertices: Option<Vec<Vertex>>,
}
impl Part for BoundingPoly {}
/// Detected start or end of a structural component.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct DetectedBreak {
/// True if break prepends the element.
#[serde(rename="isPrefix")]
pub is_prefix: Option<bool>,
/// Detected break type.
#[serde(rename="type")]
pub type_: Option<String>,
}
impl Part for DetectedBreak {}
/// The response message for Operations.ListOperations.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [list operations](struct.OperationListCall.html) (response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ListOperationsResponse {
/// The standard List next-page token.
#[serde(rename="nextPageToken")]
pub next_page_token: Option<String>,
/// A list of operations that matches the specified filter in the request.
pub operations: Option<Vec<Operation>>,
}
impl ResponseResult for ListOperationsResponse {}
/// Results for a product search request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ProductSearchResults {
/// List of results grouped by products detected in the query image. Each entry
/// corresponds to one bounding polygon in the query image, and contains the
/// matching products specific to that region. There may be duplicate product
/// matches in the union of all the per-product results.
#[serde(rename="productGroupedResults")]
pub product_grouped_results: Option<Vec<GroupedResult>>,
/// List of results, one for each product match.
pub results: Option<Vec<ResultType>>,
/// Timestamp of the index which provided these results. Products added to the
/// product set and products removed from the product set after this time are
/// not reflected in the current results.
#[serde(rename="indexTime")]
pub index_time: Option<String>,
}
impl Part for ProductSearchResults {}
/// Single crop hint that is used to generate a new crop when serving an image.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct CropHint {
/// Confidence of this being a salient region. Range [0, 1].
pub confidence: Option<f32>,
/// The bounding polygon for the crop region. The coordinates of the bounding
/// box are in the original image's scale.
#[serde(rename="boundingPoly")]
pub bounding_poly: Option<BoundingPoly>,
/// Fraction of importance of this salient region with respect to the original
/// image.
#[serde(rename="importanceFraction")]
pub importance_fraction: Option<f32>,
}
impl Part for CropHint {}
/// Request message for the `PurgeProducts` 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 products purge projects](struct.ProjectLocationProductPurgeCall.html) (request)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct PurgeProductsRequest {
/// If delete_orphan_products is true, all Products that are not in any
/// ProductSet will be deleted.
#[serde(rename="deleteOrphanProducts")]
pub delete_orphan_products: Option<bool>,
/// The default value is false. Override this value to true to actually perform
/// the purge.
pub force: Option<bool>,
/// Specify which ProductSet contains the Products to be deleted.
#[serde(rename="productSetPurgeConfig")]
pub product_set_purge_config: Option<ProductSetPurgeConfig>,
}
impl RequestValue for PurgeProductsRequest {}
/// Image context and/or feature-specific parameters.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ImageContext {
/// Not used.
#[serde(rename="latLongRect")]
pub lat_long_rect: Option<LatLongRect>,
/// List of languages to use for TEXT_DETECTION. In most cases, an empty value
/// yields the best results since it enables automatic language detection. For
/// languages based on the Latin alphabet, setting `language_hints` is not
/// needed. In rare cases, when the language of the text in the image is known,
/// setting a hint will help get better results (although it will be a
/// significant hindrance if the hint is wrong). Text detection returns an
/// error if one or more of the specified languages is not one of the
/// [supported languages](https://cloud.google.com/vision/docs/languages).
#[serde(rename="languageHints")]
pub language_hints: Option<Vec<String>>,
/// Parameters for product search.
#[serde(rename="productSearchParams")]
pub product_search_params: Option<ProductSearchParams>,
/// Parameters for crop hints annotation request.
#[serde(rename="cropHintsParams")]
pub crop_hints_params: Option<CropHintsParams>,
/// Parameters for web detection.
#[serde(rename="webDetectionParams")]
pub web_detection_params: Option<WebDetectionParams>,
}
impl Part for ImageContext {}
/// A `ReferenceImage` represents a product image and its associated metadata,
/// such as bounding boxes.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 products reference images get projects](struct.ProjectLocationProductReferenceImageGetCall.html) (response)
/// * [locations products reference images create projects](struct.ProjectLocationProductReferenceImageCreateCall.html) (request|response)
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct ReferenceImage {
/// Optional. Bounding polygons around the areas of interest in the reference image.
/// If this field is empty, the system will try to detect regions of
/// interest. At most 10 bounding polygons will be used.
///
/// The provided shape is converted into a non-rotated rectangle. Once
/// converted, the small edge of the rectangle must be greater than or equal
/// to 300 pixels. The aspect ratio must be 1:4 or less (i.e. 1:3 is ok; 1:5
/// is not).
#[serde(rename="boundingPolys")]
pub bounding_polys: Option<Vec<BoundingPoly>>,
/// The resource name of the reference image.
///
/// Format is:
///
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`.
///
/// This field is ignored when creating a reference image.
pub name: Option<String>,
/// Required. The Google Cloud Storage URI of the reference image.
///
/// The URI must start with `gs://`.
pub uri: Option<String>,
}
impl RequestValue for ReferenceImage {}
impl ResponseResult for ReferenceImage {}
/// Detected page from OCR.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Page {
/// Page width. For PDFs the unit is points. For images (including
/// TIFFs) the unit is pixels.
pub width: Option<i32>,
/// Confidence of the OCR results on the page. Range [0, 1].
pub confidence: Option<f32>,
/// Additional information detected on the page.
pub property: Option<TextProperty>,
/// List of blocks of text, images etc on this page.
pub blocks: Option<Vec<Block>>,
/// Page height. For PDFs the unit is points. For images (including
/// TIFFs) the unit is pixels.
pub height: Option<i32>,
}
impl Part for Page {}
/// Represents a color in the RGBA color space. This representation is designed
/// for simplicity of conversion to/from color representations in various
/// languages over compactness; for example, the fields of this representation
/// can be trivially provided to the constructor of "java.awt.Color" in Java; it
/// can also be trivially provided to UIColor's "+colorWithRed:green:blue:alpha"
/// method in iOS; and, with just a little work, it can be easily formatted into
/// a CSS "rgba()" string in JavaScript, as well.
///
/// Note: this proto does not carry information about the absolute color space
/// that should be used to interpret the RGB value (e.g. sRGB, Adobe RGB,
/// DCI-P3, BT.2020, etc.). By default, applications SHOULD assume the sRGB color
/// space.
///
/// Note: when color equality needs to be decided, implementations, unless
/// documented otherwise, will treat two colors to be equal if all their red,
/// green, blue and alpha values each differ by at most 1e-5.
///
/// Example (Java):
///
/// ````text
/// import com.google.type.Color;
///
/// // ...
/// public static java.awt.Color fromProto(Color protocolor) {
/// float alpha = protocolor.hasAlpha()
/// ? protocolor.getAlpha().getValue()
/// : 1.0;
///
/// return new java.awt.Color(
/// protocolor.getRed(),
/// protocolor.getGreen(),
/// protocolor.getBlue(),
/// alpha);
/// }
///
/// public static Color toProto(java.awt.Color color) {
/// float red = (float) color.getRed();
/// float green = (float) color.getGreen();
/// float blue = (float) color.getBlue();
/// float denominator = 255.0;
/// Color.Builder resultBuilder =
/// Color
/// .newBuilder()
/// .setRed(red / denominator)
/// .setGreen(green / denominator)
/// .setBlue(blue / denominator);
/// int alpha = color.getAlpha();
/// if (alpha != 255) {
/// result.setAlpha(
/// FloatValue
/// .newBuilder()
/// .setValue(((float) alpha) / denominator)
/// .build());
/// }
/// return resultBuilder.build();
/// }
/// // ...
/// ````
///
/// Example (iOS / Obj-C):
///
/// ````text
/// // ...
/// static UIColor* fromProto(Color* protocolor) {
/// float red = [protocolor red];
/// float green = [protocolor green];
/// float blue = [protocolor blue];
/// FloatValue* alpha_wrapper = [protocolor alpha];
/// float alpha = 1.0;
/// if (alpha_wrapper != nil) {
/// alpha = [alpha_wrapper value];
/// }
/// return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
/// }
///
/// static Color* toProto(UIColor* color) {
/// CGFloat red, green, blue, alpha;
/// if (![color getRed:&red green:&green blue:&blue alpha:&alpha]) {
/// return nil;
/// }
/// Color* result = [[Color alloc] init];
/// [result setRed:red];
/// [result setGreen:green];
/// [result setBlue:blue];
/// if (alpha <= 0.9999) {
/// [result setAlpha:floatWrapperWithValue(alpha)];
/// }
/// [result autorelease];
/// return result;
/// }
/// // ...
/// ````
///
/// Example (JavaScript):
///
/// ````text
/// // ...
///
/// var protoToCssColor = function(rgb_color) {
/// var redFrac = rgb_color.red || 0.0;
/// var greenFrac = rgb_color.green || 0.0;
/// var blueFrac = rgb_color.blue || 0.0;
/// var red = Math.floor(redFrac * 255);
/// var green = Math.floor(greenFrac * 255);
/// var blue = Math.floor(blueFrac * 255);
///
/// if (!('alpha' in rgb_color)) {
/// return rgbToCssColor_(red, green, blue);
/// }
///
/// var alphaFrac = rgb_color.alpha.value || 0.0;
/// var rgbParams = [red, green, blue].join(',');
/// return ['rgba(', rgbParams, ',', alphaFrac, ')'].join('');
/// };
///
/// var rgbToCssColor_ = function(red, green, blue) {
/// var rgbNumber = new Number((red << 16) | (green << 8) | blue);
/// var hexString = rgbNumber.toString(16);
/// var missingZeros = 6 - hexString.length;
/// var resultBuilder = ['#'];
/// for (var i = 0; i < missingZeros; i++) {
/// resultBuilder.push('0');
/// }
/// resultBuilder.push(hexString);
/// return resultBuilder.join('');
/// };
///
/// // ...
/// ````
///
/// This type is not used in any activity, and only used as *part* of another schema.
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct Color {
/// The amount of blue in the color as a value in the interval [0, 1].
pub blue: Option<f32>,
/// The fraction of this color that should be applied to the pixel. That is,
/// the final pixel color is defined by the equation:
///
/// pixel color = alpha * (this color) + (1.0 - alpha) * (background color)
///
/// This means that a value of 1.0 corresponds to a solid color, whereas
/// a value of 0.0 corresponds to a completely transparent color. This
/// uses a wrapper message rather than a simple float scalar so that it is
/// possible to distinguish between a default value and the value being unset.
/// If omitted, this color object is to be rendered as a solid color
/// (as if the alpha value had been explicitly given with a value of 1.0).
pub alpha: Option<f32>,
/// The amount of green in the color as a value in the interval [0, 1].
pub green: Option<f32>,
/// The amount of red in the color as a value in the interval [0, 1].
pub red: Option<f32>,
}
impl Part for Color {}
/// A face annotation object contains the results of face detection.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct FaceAnnotation {
/// Yaw angle, which indicates the leftward/rightward angle that the face is
/// pointing relative to the vertical plane perpendicular to the image. Range
/// [-180,180].
#[serde(rename="panAngle")]
pub pan_angle: Option<f32>,
/// Under-exposed likelihood.
#[serde(rename="underExposedLikelihood")]
pub under_exposed_likelihood: Option<String>,
/// Face landmarking confidence. Range [0, 1].
#[serde(rename="landmarkingConfidence")]
pub landmarking_confidence: Option<f32>,
/// Detection confidence. Range [0, 1].
#[serde(rename="detectionConfidence")]
pub detection_confidence: Option<f32>,
/// Joy likelihood.
#[serde(rename="joyLikelihood")]
pub joy_likelihood: Option<String>,
/// Detected face landmarks.
pub landmarks: Option<Vec<Landmark>>,
/// Sorrow likelihood.
#[serde(rename="sorrowLikelihood")]
pub sorrow_likelihood: Option<String>,
/// Blurred likelihood.
#[serde(rename="blurredLikelihood")]
pub blurred_likelihood: Option<String>,
/// Pitch angle, which indicates the upwards/downwards angle that the face is
/// pointing relative to the image's horizontal plane. Range [-180,180].
#[serde(rename="tiltAngle")]
pub tilt_angle: Option<f32>,
/// Anger likelihood.
#[serde(rename="angerLikelihood")]
pub anger_likelihood: Option<String>,
/// The bounding polygon around the face. The coordinates of the bounding box
/// are in the original image's scale.
/// The bounding box is computed to "frame" the face in accordance with human
/// expectations. It is based on the landmarker results.
/// Note that one or more x and/or y coordinates may not be generated in the
/// `BoundingPoly` (the polygon will be unbounded) if only a partial face
/// appears in the image to be annotated.
#[serde(rename="boundingPoly")]
pub bounding_poly: Option<BoundingPoly>,
/// Roll angle, which indicates the amount of clockwise/anti-clockwise rotation
/// of the face relative to the image vertical about the axis perpendicular to
/// the face. Range [-180,180].
#[serde(rename="rollAngle")]
pub roll_angle: Option<f32>,
/// Headwear likelihood.
#[serde(rename="headwearLikelihood")]
pub headwear_likelihood: Option<String>,
/// Surprise likelihood.
#[serde(rename="surpriseLikelihood")]
pub surprise_likelihood: Option<String>,
/// The `fd_bounding_poly` bounding polygon is tighter than the
/// `boundingPoly`, and encloses only the skin part of the face. Typically, it
/// is used to eliminate the face from any image analysis that detects the
/// "amount of skin" visible in an image. It is not based on the
/// landmarker results, only on the initial face detection, hence
/// the <code>fd</code> (face detection) prefix.
#[serde(rename="fdBoundingPoly")]
pub fd_bounding_poly: Option<BoundingPoly>,
}
impl Part for FaceAnnotation {}
/// Relevant information for the image from the Internet.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct WebDetection {
/// Web pages containing the matching images from the Internet.
#[serde(rename="pagesWithMatchingImages")]
pub pages_with_matching_images: Option<Vec<WebPage>>,
/// The visually similar image results.
#[serde(rename="visuallySimilarImages")]
pub visually_similar_images: Option<Vec<WebImage>>,
/// Partial matching images from the Internet.
/// Those images are similar enough to share some key-point features. For
/// example an original image will likely have partial matching for its crops.
#[serde(rename="partialMatchingImages")]
pub partial_matching_images: Option<Vec<WebImage>>,
/// Deduced entities from similar images on the Internet.
#[serde(rename="webEntities")]
pub web_entities: Option<Vec<WebEntity>>,
/// Fully matching images from the Internet.
/// Can include resized copies of the query image.
#[serde(rename="fullMatchingImages")]
pub full_matching_images: Option<Vec<WebImage>>,
/// The service's best guess as to the topic of the request image.
/// Inferred from similar images on the open web.
#[serde(rename="bestGuessLabels")]
pub best_guess_labels: Option<Vec<WebLabel>>,
}
impl Part for WebDetection {}
/// Response to a single file annotation request. A file may contain one or more
/// images, which individually have their own responses.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[derive(Default, Clone, Debug, Serialize, Deserialize)]
pub struct AnnotateFileResponse {
/// This field gives the total number of pages in the file.
#[serde(rename="totalPages")]
pub total_pages: Option<i32>,
/// If set, represents the error message for the failed request. The
/// `responses` field will not be set in this case.
pub error: Option<Status>,
/// Information about the file for which this response is generated.
#[serde(rename="inputConfig")]
pub input_config: Option<InputConfig>,
/// Individual responses to images found within the file. This field will be
/// empty if the `error` field is set.
pub responses: Option<Vec<AnnotateImageResponse>>,
}
impl Part for AnnotateFileResponse {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *operation* resources.
/// It is not used directly, but through the `Vision` 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_vision1 as vision1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use vision1::Vision;
///
/// 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 = Vision::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 `cancel(...)`, `delete(...)`, `get(...)` and `list(...)`
/// // to build up your call.
/// let rb = hub.operations();
/// # }
/// ```
pub struct OperationMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
}
impl<'a, C, A> MethodsBuilder for OperationMethods<'a, C, A> {}
impl<'a, C, A> OperationMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Lists operations that match the specified filter in the request. If the
/// server doesn't support this method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding
/// to use different resource name schemes, such as `users/*/operations`. To
/// override the binding, API services can add a binding such as
/// `"/v1/{name=users/*}/operations"` to their service configuration.
/// For backwards compatibility, the default name includes the operations
/// collection id, however overriding users must ensure the name binding
/// is the parent resource, without the operations collection id.
///
/// # Arguments
///
/// * `name` - The name of the operation's parent resource.
pub fn list(&self, name: &str) -> OperationListCall<'a, C, A> {
OperationListCall {
hub: self.hub,
_name: name.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets the latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// # Arguments
///
/// * `name` - The name of the operation resource.
pub fn get(&self, name: &str) -> OperationGetCall<'a, C, A> {
OperationGetCall {
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:
///
/// Deletes a long-running operation. This method indicates that the client is
/// no longer interested in the operation result. It does not cancel the
/// operation. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`.
///
/// # Arguments
///
/// * `name` - The name of the operation resource to be deleted.
pub fn delete(&self, name: &str) -> OperationDeleteCall<'a, C, A> {
OperationDeleteCall {
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:
///
/// Starts asynchronous cancellation on a long-running operation. The server
/// makes a best effort to cancel the operation, but success is not
/// guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use
/// Operations.GetOperation or
/// other methods to check whether the cancellation succeeded or whether the
/// operation completed despite cancellation. On successful cancellation,
/// the operation is not deleted; instead, it becomes an operation with
/// an Operation.error value with a google.rpc.Status.code of 1,
/// corresponding to `Code.CANCELLED`.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - The name of the operation resource to be cancelled.
pub fn cancel(&self, request: CancelOperationRequest, name: &str) -> OperationCancelCall<'a, C, A> {
OperationCancelCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *file* resources.
/// It is not used directly, but through the `Vision` 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_vision1 as vision1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use vision1::Vision;
///
/// 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 = Vision::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 `annotate(...)` and `async_batch_annotate(...)`
/// // to build up your call.
/// let rb = hub.files();
/// # }
/// ```
pub struct FileMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
}
impl<'a, C, A> MethodsBuilder for FileMethods<'a, C, A> {}
impl<'a, C, A> FileMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Service that performs image detection and annotation for a batch of files.
/// Now only "application/pdf", "image/tiff" and "image/gif" are supported.
///
/// This service will extract at most 5 (customers can specify which 5 in
/// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each
/// file provided and perform detection and annotation for each image
/// extracted.
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn annotate(&self, request: BatchAnnotateFilesRequest) -> FileAnnotateCall<'a, C, A> {
FileAnnotateCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Run asynchronous image detection and annotation for a list of generic
/// files, such as PDF files, which may contain multiple pages and multiple
/// images per page. Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn async_batch_annotate(&self, request: AsyncBatchAnnotateFilesRequest) -> FileAsyncBatchAnnotateCall<'a, C, A> {
FileAsyncBatchAnnotateCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *image* resources.
/// It is not used directly, but through the `Vision` 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_vision1 as vision1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use vision1::Vision;
///
/// 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 = Vision::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 `annotate(...)` and `async_batch_annotate(...)`
/// // to build up your call.
/// let rb = hub.images();
/// # }
/// ```
pub struct ImageMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
}
impl<'a, C, A> MethodsBuilder for ImageMethods<'a, C, A> {}
impl<'a, C, A> ImageMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Run image detection and annotation for a batch of images.
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn annotate(&self, request: BatchAnnotateImagesRequest) -> ImageAnnotateCall<'a, C, A> {
ImageAnnotateCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Run asynchronous image detection and annotation for a list of images.
///
/// Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results).
///
/// This service will write image annotation outputs to json files in customer
/// GCS bucket, each json file containing BatchAnnotateImagesResponse proto.
///
/// # Arguments
///
/// * `request` - No description provided.
pub fn async_batch_annotate(&self, request: AsyncBatchAnnotateImagesRequest) -> ImageAsyncBatchAnnotateCall<'a, C, A> {
ImageAsyncBatchAnnotateCall {
hub: self.hub,
_request: request,
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *location* resources.
/// It is not used directly, but through the `Vision` 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_vision1 as vision1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use vision1::Vision;
///
/// 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 = Vision::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 `operations_get(...)`
/// // to build up your call.
/// let rb = hub.locations();
/// # }
/// ```
pub struct LocationMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
}
impl<'a, C, A> MethodsBuilder for LocationMethods<'a, C, A> {}
impl<'a, C, A> LocationMethods<'a, C, A> {
/// Create a builder to help you perform the following task:
///
/// Gets the latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// # Arguments
///
/// * `name` - The name of the operation resource.
pub fn operations_get(&self, name: &str) -> LocationOperationGetCall<'a, C, A> {
LocationOperationGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
/// A builder providing access to all methods supported on *project* resources.
/// It is not used directly, but through the `Vision` 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_vision1 as vision1;
///
/// # #[test] fn egal() {
/// use std::default::Default;
/// use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// use vision1::Vision;
///
/// 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 = Vision::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 `files_annotate(...)`, `files_async_batch_annotate(...)`, `images_annotate(...)`, `images_async_batch_annotate(...)`, `locations_files_annotate(...)`, `locations_files_async_batch_annotate(...)`, `locations_images_annotate(...)`, `locations_images_async_batch_annotate(...)`, `locations_operations_get(...)`, `locations_product_sets_add_product(...)`, `locations_product_sets_create(...)`, `locations_product_sets_delete(...)`, `locations_product_sets_get(...)`, `locations_product_sets_import(...)`, `locations_product_sets_list(...)`, `locations_product_sets_patch(...)`, `locations_product_sets_products_list(...)`, `locations_product_sets_remove_product(...)`, `locations_products_create(...)`, `locations_products_delete(...)`, `locations_products_get(...)`, `locations_products_list(...)`, `locations_products_patch(...)`, `locations_products_purge(...)`, `locations_products_reference_images_create(...)`, `locations_products_reference_images_delete(...)`, `locations_products_reference_images_get(...)`, `locations_products_reference_images_list(...)` and `operations_get(...)`
/// // to build up your call.
/// let rb = hub.projects();
/// # }
/// ```
pub struct ProjectMethods<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<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:
///
/// Run image detection and annotation for a batch of images.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn locations_images_annotate(&self, request: BatchAnnotateImagesRequest, parent: &str) -> ProjectLocationImageAnnotateCall<'a, C, A> {
ProjectLocationImageAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Run asynchronous image detection and annotation for a list of images.
///
/// Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results).
///
/// This service will write image annotation outputs to json files in customer
/// GCS bucket, each json file containing BatchAnnotateImagesResponse proto.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn images_async_batch_annotate(&self, request: AsyncBatchAnnotateImagesRequest, parent: &str) -> ProjectImageAsyncBatchAnnotateCall<'a, C, A> {
ProjectImageAsyncBatchAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets information associated with a Product.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the Product does not exist.
///
/// # Arguments
///
/// * `name` - Required. Resource name of the Product to get.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
pub fn locations_products_get(&self, name: &str) -> ProjectLocationProductGetCall<'a, C, A> {
ProjectLocationProductGetCall {
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:
///
/// Permanently deletes a product and its reference images.
///
/// Metadata of the product and all its images will be deleted right away, but
/// search queries against ProductSets containing the product may still work
/// until all related caches are refreshed.
///
/// # Arguments
///
/// * `name` - Required. Resource name of product to delete.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
pub fn locations_products_delete(&self, name: &str) -> ProjectLocationProductDeleteCall<'a, C, A> {
ProjectLocationProductDeleteCall {
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:
///
/// Run image detection and annotation for a batch of images.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn images_annotate(&self, request: BatchAnnotateImagesRequest, parent: &str) -> ProjectImageAnnotateCall<'a, C, A> {
ProjectImageAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists the Products in a ProductSet, in an unspecified order. If the
/// ProductSet does not exist, the products field of the response will be
/// empty.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1.
///
/// # Arguments
///
/// * `name` - Required. The ProductSet resource for which to retrieve Products.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
pub fn locations_product_sets_products_list(&self, name: &str) -> ProjectLocationProductSetProductListCall<'a, C, A> {
ProjectLocationProductSetProductListCall {
hub: self.hub,
_name: name.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets the latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// # Arguments
///
/// * `name` - The name of the operation resource.
pub fn locations_operations_get(&self, name: &str) -> ProjectLocationOperationGetCall<'a, C, A> {
ProjectLocationOperationGetCall {
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:
///
/// Asynchronous API to delete all Products in a ProductSet or all Products
/// that are in no ProductSet.
///
/// If a Product is a member of the specified ProductSet in addition to other
/// ProductSets, the Product will still be deleted.
///
/// It is recommended to not delete the specified ProductSet until after this
/// operation has completed. It is also recommended to not add any of the
/// Products involved in the batch delete to a new ProductSet while this
/// operation is running because those Products may still end up deleted.
///
/// It's not possible to undo the PurgeProducts operation. Therefore, it is
/// recommended to keep the csv files used in ImportProductSets (if that was
/// how you originally built the Product Set) before starting PurgeProducts, in
/// case you need to re-import the data after deletion.
///
/// If the plan is to purge all of the Products from a ProductSet and then
/// re-use the empty ProductSet to re-import new Products into the empty
/// ProductSet, you must wait until the PurgeProducts operation has finished
/// for that ProductSet.
///
/// The google.longrunning.Operation API can be used to keep track of the
/// progress and results of the request.
/// `Operation.metadata` contains `BatchOperationMetadata`. (progress)
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The project and location in which the Products should be deleted.
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
pub fn locations_products_purge(&self, request: PurgeProductsRequest, parent: &str) -> ProjectLocationProductPurgeCall<'a, C, A> {
ProjectLocationProductPurgeCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Permanently deletes a ProductSet. Products and ReferenceImages in the
/// ProductSet are not deleted.
///
/// The actual image files are not deleted from Google Cloud Storage.
///
/// # Arguments
///
/// * `name` - Required. Resource name of the ProductSet to delete.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
pub fn locations_product_sets_delete(&self, name: &str) -> ProjectLocationProductSetDeleteCall<'a, C, A> {
ProjectLocationProductSetDeleteCall {
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:
///
/// Removes a Product from the specified ProductSet.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. The resource name for the ProductSet to modify.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
pub fn locations_product_sets_remove_product(&self, request: RemoveProductFromProductSetRequest, name: &str) -> ProjectLocationProductSetRemoveProductCall<'a, C, A> {
ProjectLocationProductSetRemoveProductCall {
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:
///
/// Run asynchronous image detection and annotation for a list of generic
/// files, such as PDF files, which may contain multiple pages and multiple
/// images per page. Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn files_async_batch_annotate(&self, request: AsyncBatchAnnotateFilesRequest, parent: &str) -> ProjectFileAsyncBatchAnnotateCall<'a, C, A> {
ProjectFileAsyncBatchAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets information associated with a ProductSet.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the ProductSet does not exist.
///
/// # Arguments
///
/// * `name` - Required. Resource name of the ProductSet to get.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
pub fn locations_product_sets_get(&self, name: &str) -> ProjectLocationProductSetGetCall<'a, C, A> {
ProjectLocationProductSetGetCall {
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 latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// # Arguments
///
/// * `name` - The name of the operation resource.
pub fn operations_get(&self, name: &str) -> ProjectOperationGetCall<'a, C, A> {
ProjectOperationGetCall {
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:
///
/// Creates and returns a new product resource.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096
/// characters.
/// * Returns INVALID_ARGUMENT if description is longer than 4096 characters.
/// * Returns INVALID_ARGUMENT if product_category is missing or invalid.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The project in which the Product should be created.
/// Format is
/// `projects/PROJECT_ID/locations/LOC_ID`.
pub fn locations_products_create(&self, request: Product, parent: &str) -> ProjectLocationProductCreateCall<'a, C, A> {
ProjectLocationProductCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_product_id: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists products in an unspecified order.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1.
///
/// # Arguments
///
/// * `parent` - Required. The project OR ProductSet from which Products should be listed.
/// Format:
/// `projects/PROJECT_ID/locations/LOC_ID`
pub fn locations_products_list(&self, parent: &str) -> ProjectLocationProductListCall<'a, C, A> {
ProjectLocationProductListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Run asynchronous image detection and annotation for a list of generic
/// files, such as PDF files, which may contain multiple pages and multiple
/// images per page. Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn locations_files_async_batch_annotate(&self, request: AsyncBatchAnnotateFilesRequest, parent: &str) -> ProjectLocationFileAsyncBatchAnnotateCall<'a, C, A> {
ProjectLocationFileAsyncBatchAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates and returns a new ProductSet resource.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if display_name is missing, or is longer than
/// 4096 characters.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The project in which the ProductSet should be created.
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
pub fn locations_product_sets_create(&self, request: ProductSet, parent: &str) -> ProjectLocationProductSetCreateCall<'a, C, A> {
ProjectLocationProductSetCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_product_set_id: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Service that performs image detection and annotation for a batch of files.
/// Now only "application/pdf", "image/tiff" and "image/gif" are supported.
///
/// This service will extract at most 5 (customers can specify which 5 in
/// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each
/// file provided and perform detection and annotation for each image
/// extracted.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn locations_files_annotate(&self, request: BatchAnnotateFilesRequest, parent: &str) -> ProjectLocationFileAnnotateCall<'a, C, A> {
ProjectLocationFileAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Adds a Product to the specified ProductSet. If the Product is already
/// present, no change is made.
///
/// One Product can be added to at most 100 ProductSets.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the Product or the ProductSet doesn't exist.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. The resource name for the ProductSet to modify.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
pub fn locations_product_sets_add_product(&self, request: AddProductToProductSetRequest, name: &str) -> ProjectLocationProductSetAddProductCall<'a, C, A> {
ProjectLocationProductSetAddProductCall {
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:
///
/// Asynchronous API that imports a list of reference images to specified
/// product sets based on a list of image information.
///
/// The google.longrunning.Operation API can be used to keep track of the
/// progress and results of the request.
/// `Operation.metadata` contains `BatchOperationMetadata`. (progress)
/// `Operation.response` contains `ImportProductSetsResponse`. (results)
///
/// The input source of this method is a csv file on Google Cloud Storage.
/// For the format of the csv file please see
/// ImportProductSetsGcsSource.csv_file_uri.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The project in which the ProductSets should be imported.
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
pub fn locations_product_sets_import(&self, request: ImportProductSetsRequest, parent: &str) -> ProjectLocationProductSetImportCall<'a, C, A> {
ProjectLocationProductSetImportCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Service that performs image detection and annotation for a batch of files.
/// Now only "application/pdf", "image/tiff" and "image/gif" are supported.
///
/// This service will extract at most 5 (customers can specify which 5 in
/// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each
/// file provided and perform detection and annotation for each image
/// extracted.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn files_annotate(&self, request: BatchAnnotateFilesRequest, parent: &str) -> ProjectFileAnnotateCall<'a, C, A> {
ProjectFileAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Makes changes to a Product resource.
/// Only the `display_name`, `description`, and `labels` fields can be updated
/// right now.
///
/// If labels are updated, the change will not be reflected in queries until
/// the next index time.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the Product does not exist.
/// * Returns INVALID_ARGUMENT if display_name is present in update_mask but is
/// missing from the request or longer than 4096 characters.
/// * Returns INVALID_ARGUMENT if description is present in update_mask but is
/// longer than 4096 characters.
/// * Returns INVALID_ARGUMENT if product_category is present in update_mask.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - The resource name of the product.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
/// This field is ignored when creating a product.
pub fn locations_products_patch(&self, request: Product, name: &str) -> ProjectLocationProductPatchCall<'a, C, A> {
ProjectLocationProductPatchCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_update_mask: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Makes changes to a ProductSet resource.
/// Only display_name can be updated currently.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the ProductSet does not exist.
/// * Returns INVALID_ARGUMENT if display_name is present in update_mask but
/// missing from the request or longer than 4096 characters.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - The resource name of the ProductSet.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
/// This field is ignored when creating a ProductSet.
pub fn locations_product_sets_patch(&self, request: ProductSet, name: &str) -> ProjectLocationProductSetPatchCall<'a, C, A> {
ProjectLocationProductSetPatchCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_update_mask: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists ProductSets in an unspecified order.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if page_size is greater than 100, or less
/// than 1.
///
/// # Arguments
///
/// * `parent` - Required. The project from which ProductSets should be listed.
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
pub fn locations_product_sets_list(&self, parent: &str) -> ProjectLocationProductSetListCall<'a, C, A> {
ProjectLocationProductSetListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Run asynchronous image detection and annotation for a list of images.
///
/// Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results).
///
/// This service will write image annotation outputs to json files in customer
/// GCS bucket, each json file containing BatchAnnotateImagesResponse proto.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Optional. Target project and location to make a call.
/// Format: `projects/{project-id}/locations/{location-id}`.
/// If no parent is specified, a region will be chosen automatically.
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
/// Example: `projects/project-A/locations/eu`.
pub fn locations_images_async_batch_annotate(&self, request: AsyncBatchAnnotateImagesRequest, parent: &str) -> ProjectLocationImageAsyncBatchAnnotateCall<'a, C, A> {
ProjectLocationImageAsyncBatchAnnotateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates and returns a new ReferenceImage resource.
///
/// The `bounding_poly` field is optional. If `bounding_poly` is not specified,
/// the system will try to detect regions of interest in the image that are
/// compatible with the product_category on the parent product. If it is
/// specified, detection is ALWAYS skipped. The system converts polygons into
/// non-rotated rectangles.
///
/// Note that the pipeline will resize the image if the image resolution is too
/// large to process (above 50MP).
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096
/// characters.
/// * Returns INVALID_ARGUMENT if the product does not exist.
/// * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing
/// compatible with the parent product's product_category is detected.
/// * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Resource name of the product in which to create the reference image.
/// Format is
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
pub fn locations_products_reference_images_create(&self, request: ReferenceImage, parent: &str) -> ProjectLocationProductReferenceImageCreateCall<'a, C, A> {
ProjectLocationProductReferenceImageCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_reference_image_id: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Permanently deletes a reference image.
///
/// The image metadata will be deleted right away, but search queries
/// against ProductSets containing the image may still work until all related
/// caches are refreshed.
///
/// The actual image files are not deleted from Google Cloud Storage.
///
/// # Arguments
///
/// * `name` - Required. The resource name of the reference image to delete.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`
pub fn locations_products_reference_images_delete(&self, name: &str) -> ProjectLocationProductReferenceImageDeleteCall<'a, C, A> {
ProjectLocationProductReferenceImageDeleteCall {
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 information associated with a ReferenceImage.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the specified image does not exist.
///
/// # Arguments
///
/// * `name` - Required. The resource name of the ReferenceImage to get.
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`.
pub fn locations_products_reference_images_get(&self, name: &str) -> ProjectLocationProductReferenceImageGetCall<'a, C, A> {
ProjectLocationProductReferenceImageGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists reference images.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the parent product does not exist.
/// * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less
/// than 1.
///
/// # Arguments
///
/// * `parent` - Required. Resource name of the product containing the reference images.
/// Format is
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
pub fn locations_products_reference_images_list(&self, parent: &str) -> ProjectLocationProductReferenceImageListCall<'a, C, A> {
ProjectLocationProductReferenceImageListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_scopes: Default::default(),
_additional_params: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Lists operations that match the specified filter in the request. If the
/// server doesn't support this method, it returns `UNIMPLEMENTED`.
///
/// NOTE: the `name` binding allows API services to override the binding
/// to use different resource name schemes, such as `users/*/operations`. To
/// override the binding, API services can add a binding such as
/// `"/v1/{name=users/*}/operations"` to their service configuration.
/// For backwards compatibility, the default name includes the operations
/// collection id, however overriding users must ensure the name binding
/// is the parent resource, without the operations collection id.
///
/// A builder for the *list* method supported by a *operation* resource.
/// It is not used directly, but through a `OperationMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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.operations().list("name")
/// .page_token("sea")
/// .page_size(-90)
/// .filter("dolores")
/// .doit();
/// # }
/// ```
pub struct OperationListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: 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 OperationListCall<'a, C, A> {}
impl<'a, C, A> OperationListCall<'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, ListOperationsResponse)> {
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: "vision.operations.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity(6 + self._additional_params.len());
params.push(("name", self._name.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._page_size {
params.push(("pageSize", value.to_string()));
}
if let Some(value) = self._filter {
params.push(("filter", value.to_string()));
}
for &field in ["alt", "name", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+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)
}
}
}
}
/// The name of the operation's parent resource.
///
/// Sets the *name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn name(mut self, new_value: &str) -> OperationListCall<'a, C, A> {
self._name = new_value.to_string();
self
}
/// The standard list page token.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> OperationListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// The standard list page size.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> OperationListCall<'a, C, A> {
self._page_size = Some(new_value);
self
}
/// The standard list filter.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> OperationListCall<'a, C, A> {
self._filter = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> OperationListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known 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) -> OperationListCall<'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) -> OperationListCall<'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 latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// A builder for the *get* method supported by a *operation* resource.
/// It is not used directly, but through a `OperationMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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.operations().get("name")
/// .doit();
/// # }
/// ```
pub struct OperationGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for OperationGetCall<'a, C, A> {}
impl<'a, C, A> OperationGetCall<'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, Operation)> {
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: "vision.operations.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() + "v1/{+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)
}
}
}
}
/// The name of the operation resource.
///
/// Sets the *name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn name(mut self, new_value: &str) -> OperationGetCall<'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) -> OperationGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters which are not yet available through their own
/// setters.
///
/// Please note that this method must not be used to set any of the known 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) -> OperationGetCall<'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) -> OperationGetCall<'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
}
}
/// Deletes a long-running operation. This method indicates that the client is
/// no longer interested in the operation result. It does not cancel the
/// operation. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`.
///
/// A builder for the *delete* method supported by a *operation* resource.
/// It is not used directly, but through a `OperationMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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.operations().delete("name")
/// .doit();
/// # }
/// ```
pub struct OperationDeleteCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for OperationDeleteCall<'a, C, A> {}
impl<'a, C, A> OperationDeleteCall<'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, Empty)> {
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: "vision.operations.delete",
http_method: hyper::method::Method::Delete });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("name", self._name.to_string()));
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+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::Delete, 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)
}
}
}
}
/// The name of the operation resource to be deleted.
///
/// Sets the *name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn name(mut self, new_value: &str) -> OperationDeleteCall<'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) -> OperationDeleteCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> OperationDeleteCall<'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) -> OperationDeleteCall<'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
}
}
/// Starts asynchronous cancellation on a long-running operation. The server
/// makes a best effort to cancel the operation, but success is not
/// guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use
/// Operations.GetOperation or
/// other methods to check whether the cancellation succeeded or whether the
/// operation completed despite cancellation. On successful cancellation,
/// the operation is not deleted; instead, it becomes an operation with
/// an Operation.error value with a google.rpc.Status.code of 1,
/// corresponding to `Code.CANCELLED`.
///
/// A builder for the *cancel* method supported by a *operation* resource.
/// It is not used directly, but through a `OperationMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// use vision1::CancelOperationRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = CancelOperationRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.operations().cancel(req, "name")
/// .doit();
/// # }
/// ```
pub struct OperationCancelCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: CancelOperationRequest,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for OperationCancelCall<'a, C, A> {}
impl<'a, C, A> OperationCancelCall<'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, Empty)> {
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: "vision.operations.cancel",
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() + "v1/{+name}:cancel";
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: CancelOperationRequest) -> OperationCancelCall<'a, C, A> {
self._request = new_value;
self
}
/// The name of the operation resource to be cancelled.
///
/// Sets the *name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn name(mut self, new_value: &str) -> OperationCancelCall<'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) -> OperationCancelCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> OperationCancelCall<'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) -> OperationCancelCall<'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
}
}
/// Service that performs image detection and annotation for a batch of files.
/// Now only "application/pdf", "image/tiff" and "image/gif" are supported.
///
/// This service will extract at most 5 (customers can specify which 5 in
/// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each
/// file provided and perform detection and annotation for each image
/// extracted.
///
/// A builder for the *annotate* method supported by a *file* resource.
/// It is not used directly, but through a `FileMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// use vision1::BatchAnnotateFilesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = BatchAnnotateFilesRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.files().annotate(req)
/// .doit();
/// # }
/// ```
pub struct FileAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: BatchAnnotateFilesRequest,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for FileAnnotateCall<'a, C, A> {}
impl<'a, C, A> FileAnnotateCall<'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, BatchAnnotateFilesResponse)> {
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: "vision.files.annotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/files:annotate";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
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: BatchAnnotateFilesRequest) -> FileAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> FileAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> FileAnnotateCall<'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) -> FileAnnotateCall<'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
}
}
/// Run asynchronous image detection and annotation for a list of generic
/// files, such as PDF files, which may contain multiple pages and multiple
/// images per page. Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).
///
/// A builder for the *asyncBatchAnnotate* method supported by a *file* resource.
/// It is not used directly, but through a `FileMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// use vision1::AsyncBatchAnnotateFilesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = AsyncBatchAnnotateFilesRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.files().async_batch_annotate(req)
/// .doit();
/// # }
/// ```
pub struct FileAsyncBatchAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: AsyncBatchAnnotateFilesRequest,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for FileAsyncBatchAnnotateCall<'a, C, A> {}
impl<'a, C, A> FileAsyncBatchAnnotateCall<'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, Operation)> {
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: "vision.files.asyncBatchAnnotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/files:asyncBatchAnnotate";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
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: AsyncBatchAnnotateFilesRequest) -> FileAsyncBatchAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> FileAsyncBatchAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> FileAsyncBatchAnnotateCall<'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) -> FileAsyncBatchAnnotateCall<'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
}
}
/// Run image detection and annotation for a batch of images.
///
/// A builder for the *annotate* method supported by a *image* resource.
/// It is not used directly, but through a `ImageMethods` 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_vision1 as vision1;
/// use vision1::BatchAnnotateImagesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = BatchAnnotateImagesRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.images().annotate(req)
/// .doit();
/// # }
/// ```
pub struct ImageAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: BatchAnnotateImagesRequest,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ImageAnnotateCall<'a, C, A> {}
impl<'a, C, A> ImageAnnotateCall<'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, BatchAnnotateImagesResponse)> {
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: "vision.images.annotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/images:annotate";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
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: BatchAnnotateImagesRequest) -> ImageAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ImageAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ImageAnnotateCall<'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) -> ImageAnnotateCall<'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
}
}
/// Run asynchronous image detection and annotation for a list of images.
///
/// Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results).
///
/// This service will write image annotation outputs to json files in customer
/// GCS bucket, each json file containing BatchAnnotateImagesResponse proto.
///
/// A builder for the *asyncBatchAnnotate* method supported by a *image* resource.
/// It is not used directly, but through a `ImageMethods` 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_vision1 as vision1;
/// use vision1::AsyncBatchAnnotateImagesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = AsyncBatchAnnotateImagesRequest::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.images().async_batch_annotate(req)
/// .doit();
/// # }
/// ```
pub struct ImageAsyncBatchAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: AsyncBatchAnnotateImagesRequest,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ImageAsyncBatchAnnotateCall<'a, C, A> {}
impl<'a, C, A> ImageAsyncBatchAnnotateCall<'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, Operation)> {
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: "vision.images.asyncBatchAnnotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
for &field in ["alt"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/images:asyncBatchAnnotate";
if self._scopes.len() == 0 {
self._scopes.insert(Scope::CloudPlatform.as_ref().to_string(), ());
}
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: AsyncBatchAnnotateImagesRequest) -> ImageAsyncBatchAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ImageAsyncBatchAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ImageAsyncBatchAnnotateCall<'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) -> ImageAsyncBatchAnnotateCall<'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 latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// A builder for the *operations.get* method supported by a *location* resource.
/// It is not used directly, but through a `LocationMethods` 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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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.locations().operations_get("name")
/// .doit();
/// # }
/// ```
pub struct LocationOperationGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for LocationOperationGetCall<'a, C, A> {}
impl<'a, C, A> LocationOperationGetCall<'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, Operation)> {
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: "vision.locations.operations.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() + "v1/{+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)
}
}
}
}
/// The name of the operation resource.
///
/// Sets the *name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn name(mut self, new_value: &str) -> LocationOperationGetCall<'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) -> LocationOperationGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> LocationOperationGetCall<'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) -> LocationOperationGetCall<'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
}
}
/// Run image detection and annotation for a batch of images.
///
/// A builder for the *locations.images.annotate* 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_vision1 as vision1;
/// use vision1::BatchAnnotateImagesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = BatchAnnotateImagesRequest::default();
///
/// // You can configure optional parameters by calling 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_images_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationImageAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: BatchAnnotateImagesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationImageAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationImageAnnotateCall<'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, BatchAnnotateImagesResponse)> {
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: "vision.projects.locations.images.annotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/images:annotate";
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();
let mut json_mime_type = 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: BatchAnnotateImagesRequest) -> ProjectLocationImageAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectLocationImageAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectLocationImageAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationImageAnnotateCall<'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) -> ProjectLocationImageAnnotateCall<'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
}
}
/// Run asynchronous image detection and annotation for a list of images.
///
/// Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results).
///
/// This service will write image annotation outputs to json files in customer
/// GCS bucket, each json file containing BatchAnnotateImagesResponse proto.
///
/// A builder for the *images.asyncBatchAnnotate* 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_vision1 as vision1;
/// use vision1::AsyncBatchAnnotateImagesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = AsyncBatchAnnotateImagesRequest::default();
///
/// // You can configure optional parameters by calling 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().images_async_batch_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectImageAsyncBatchAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: AsyncBatchAnnotateImagesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectImageAsyncBatchAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectImageAsyncBatchAnnotateCall<'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, Operation)> {
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: "vision.projects.images.asyncBatchAnnotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/images:asyncBatchAnnotate";
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();
let mut json_mime_type = 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: AsyncBatchAnnotateImagesRequest) -> ProjectImageAsyncBatchAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectImageAsyncBatchAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectImageAsyncBatchAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectImageAsyncBatchAnnotateCall<'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) -> ProjectImageAsyncBatchAnnotateCall<'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 information associated with a Product.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the Product does not exist.
///
/// A builder for the *locations.products.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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_products_get("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductGetCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductGetCall<'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, Product)> {
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: "vision.projects.locations.products.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() + "v1/{+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. Resource name of the Product to get.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
///
/// 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) -> ProjectLocationProductGetCall<'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) -> ProjectLocationProductGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductGetCall<'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) -> ProjectLocationProductGetCall<'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
}
}
/// Permanently deletes a product and its reference images.
///
/// Metadata of the product and all its images will be deleted right away, but
/// search queries against ProductSets containing the product may still work
/// until all related caches are refreshed.
///
/// A builder for the *locations.products.delete* method supported by a *project* resource.
/// It is not used directly, but through a `ProjectMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_products_delete("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductDeleteCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductDeleteCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductDeleteCall<'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, Empty)> {
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: "vision.projects.locations.products.delete",
http_method: hyper::method::Method::Delete });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("name", self._name.to_string()));
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+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::Delete, 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. Resource name of product to delete.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`
///
/// 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) -> ProjectLocationProductDeleteCall<'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) -> ProjectLocationProductDeleteCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductDeleteCall<'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) -> ProjectLocationProductDeleteCall<'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
}
}
/// Run image detection and annotation for a batch of images.
///
/// A builder for the *images.annotate* 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_vision1 as vision1;
/// use vision1::BatchAnnotateImagesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = BatchAnnotateImagesRequest::default();
///
/// // You can configure optional parameters by calling 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().images_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectImageAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: BatchAnnotateImagesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectImageAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectImageAnnotateCall<'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, BatchAnnotateImagesResponse)> {
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: "vision.projects.images.annotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/images:annotate";
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();
let mut json_mime_type = 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: BatchAnnotateImagesRequest) -> ProjectImageAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectImageAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectImageAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectImageAnnotateCall<'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) -> ProjectImageAnnotateCall<'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 the Products in a ProductSet, in an unspecified order. If the
/// ProductSet does not exist, the products field of the response will be
/// empty.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1.
///
/// A builder for the *locations.productSets.products.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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_product_sets_products_list("name")
/// .page_token("ipsum")
/// .page_size(-5)
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetProductListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetProductListCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetProductListCall<'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, ListProductsInProductSetResponse)> {
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: "vision.projects.locations.productSets.products.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("name", self._name.to_string()));
if let Some(value) = self._page_token {
params.push(("pageToken", value.to_string()));
}
if let Some(value) = self._page_size {
params.push(("pageSize", value.to_string()));
}
for &field in ["alt", "name", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+name}/products";
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. The ProductSet resource for which to retrieve Products.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
///
/// 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) -> ProjectLocationProductSetProductListCall<'a, C, A> {
self._name = new_value.to_string();
self
}
/// The next_page_token returned from a previous List request, if any.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationProductSetProductListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of items to return. Default 10, maximum 100.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationProductSetProductListCall<'a, C, A> {
self._page_size = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductSetProductListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetProductListCall<'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) -> ProjectLocationProductSetProductListCall<'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 latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// A builder for the *locations.operations.get* method supported by a *project* resource.
/// It is not used directly, but through a `ProjectMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_operations_get("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationOperationGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationOperationGetCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationOperationGetCall<'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, Operation)> {
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: "vision.projects.locations.operations.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() + "v1/{+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)
}
}
}
}
/// The name of the operation resource.
///
/// Sets the *name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn name(mut self, new_value: &str) -> ProjectLocationOperationGetCall<'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) -> ProjectLocationOperationGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationOperationGetCall<'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) -> ProjectLocationOperationGetCall<'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
}
}
/// Asynchronous API to delete all Products in a ProductSet or all Products
/// that are in no ProductSet.
///
/// If a Product is a member of the specified ProductSet in addition to other
/// ProductSets, the Product will still be deleted.
///
/// It is recommended to not delete the specified ProductSet until after this
/// operation has completed. It is also recommended to not add any of the
/// Products involved in the batch delete to a new ProductSet while this
/// operation is running because those Products may still end up deleted.
///
/// It's not possible to undo the PurgeProducts operation. Therefore, it is
/// recommended to keep the csv files used in ImportProductSets (if that was
/// how you originally built the Product Set) before starting PurgeProducts, in
/// case you need to re-import the data after deletion.
///
/// If the plan is to purge all of the Products from a ProductSet and then
/// re-use the empty ProductSet to re-import new Products into the empty
/// ProductSet, you must wait until the PurgeProducts operation has finished
/// for that ProductSet.
///
/// The google.longrunning.Operation API can be used to keep track of the
/// progress and results of the request.
/// `Operation.metadata` contains `BatchOperationMetadata`. (progress)
///
/// A builder for the *locations.products.purge* 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_vision1 as vision1;
/// use vision1::PurgeProductsRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = PurgeProductsRequest::default();
///
/// // You can configure optional parameters by calling 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_products_purge(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductPurgeCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: PurgeProductsRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductPurgeCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductPurgeCall<'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, Operation)> {
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: "vision.projects.locations.products.purge",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/products:purge";
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();
let mut json_mime_type = 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: PurgeProductsRequest) -> ProjectLocationProductPurgeCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. The project and location in which the Products should be deleted.
///
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
///
/// 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) -> ProjectLocationProductPurgeCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectLocationProductPurgeCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductPurgeCall<'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) -> ProjectLocationProductPurgeCall<'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
}
}
/// Permanently deletes a ProductSet. Products and ReferenceImages in the
/// ProductSet are not deleted.
///
/// The actual image files are not deleted from Google Cloud Storage.
///
/// A builder for the *locations.productSets.delete* method supported by a *project* resource.
/// It is not used directly, but through a `ProjectMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_product_sets_delete("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetDeleteCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetDeleteCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetDeleteCall<'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, Empty)> {
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: "vision.projects.locations.productSets.delete",
http_method: hyper::method::Method::Delete });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("name", self._name.to_string()));
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+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::Delete, 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. Resource name of the ProductSet to delete.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
///
/// 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) -> ProjectLocationProductSetDeleteCall<'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) -> ProjectLocationProductSetDeleteCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetDeleteCall<'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) -> ProjectLocationProductSetDeleteCall<'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
}
}
/// Removes a Product from the specified ProductSet.
///
/// A builder for the *locations.productSets.removeProduct* 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_vision1 as vision1;
/// use vision1::RemoveProductFromProductSetRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = RemoveProductFromProductSetRequest::default();
///
/// // You can configure optional parameters by calling 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_product_sets_remove_product(req, "name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetRemoveProductCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: RemoveProductFromProductSetRequest,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetRemoveProductCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetRemoveProductCall<'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, Empty)> {
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: "vision.projects.locations.productSets.removeProduct",
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() + "v1/{+name}:removeProduct";
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: RemoveProductFromProductSetRequest) -> ProjectLocationProductSetRemoveProductCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. The resource name for the ProductSet to modify.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
///
/// 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) -> ProjectLocationProductSetRemoveProductCall<'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) -> ProjectLocationProductSetRemoveProductCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetRemoveProductCall<'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) -> ProjectLocationProductSetRemoveProductCall<'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
}
}
/// Run asynchronous image detection and annotation for a list of generic
/// files, such as PDF files, which may contain multiple pages and multiple
/// images per page. Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).
///
/// A builder for the *files.asyncBatchAnnotate* 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_vision1 as vision1;
/// use vision1::AsyncBatchAnnotateFilesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = AsyncBatchAnnotateFilesRequest::default();
///
/// // You can configure optional parameters by calling 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().files_async_batch_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectFileAsyncBatchAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: AsyncBatchAnnotateFilesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectFileAsyncBatchAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectFileAsyncBatchAnnotateCall<'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, Operation)> {
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: "vision.projects.files.asyncBatchAnnotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/files:asyncBatchAnnotate";
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();
let mut json_mime_type = 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: AsyncBatchAnnotateFilesRequest) -> ProjectFileAsyncBatchAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectFileAsyncBatchAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectFileAsyncBatchAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectFileAsyncBatchAnnotateCall<'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) -> ProjectFileAsyncBatchAnnotateCall<'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 information associated with a ProductSet.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the ProductSet does not exist.
///
/// A builder for the *locations.productSets.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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_product_sets_get("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetGetCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetGetCall<'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, ProductSet)> {
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: "vision.projects.locations.productSets.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() + "v1/{+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. Resource name of the ProductSet to get.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
///
/// 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) -> ProjectLocationProductSetGetCall<'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) -> ProjectLocationProductSetGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetGetCall<'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) -> ProjectLocationProductSetGetCall<'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 latest state of a long-running operation. Clients can use this
/// method to poll the operation result at intervals as recommended by the API
/// service.
///
/// A builder for the *operations.get* method supported by a *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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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().operations_get("name")
/// .doit();
/// # }
/// ```
pub struct ProjectOperationGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectOperationGetCall<'a, C, A> {}
impl<'a, C, A> ProjectOperationGetCall<'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, Operation)> {
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: "vision.projects.operations.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() + "v1/{+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)
}
}
}
}
/// The name of the operation resource.
///
/// Sets the *name* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn name(mut self, new_value: &str) -> ProjectOperationGetCall<'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) -> ProjectOperationGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectOperationGetCall<'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) -> ProjectOperationGetCall<'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
}
}
/// Creates and returns a new product resource.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if display_name is missing or longer than 4096
/// characters.
/// * Returns INVALID_ARGUMENT if description is longer than 4096 characters.
/// * Returns INVALID_ARGUMENT if product_category is missing or invalid.
///
/// A builder for the *locations.products.create* method supported by a *project* resource.
/// It is not used directly, but through a `ProjectMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// use vision1::Product;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = Product::default();
///
/// // You can configure optional parameters by calling 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_products_create(req, "parent")
/// .product_id("dolor")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductCreateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: Product,
_parent: String,
_product_id: Option<String>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductCreateCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductCreateCall<'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, Product)> {
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: "vision.projects.locations.products.create",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
if let Some(value) = self._product_id {
params.push(("productId", value.to_string()));
}
for &field in ["alt", "parent", "productId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/products";
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();
let mut json_mime_type = 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: Product) -> ProjectLocationProductCreateCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. The project in which the Product should be created.
///
/// Format is
/// `projects/PROJECT_ID/locations/LOC_ID`.
///
/// 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) -> ProjectLocationProductCreateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// A user-supplied resource id for this Product. If set, the server will
/// attempt to use this value as the resource id. If it is already in use, an
/// error is returned with code ALREADY_EXISTS. Must be at most 128 characters
/// long. It cannot contain the character `/`.
///
/// Sets the *product id* query property to the given value.
pub fn product_id(mut self, new_value: &str) -> ProjectLocationProductCreateCall<'a, C, A> {
self._product_id = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductCreateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductCreateCall<'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) -> ProjectLocationProductCreateCall<'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 products in an unspecified order.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if page_size is greater than 100 or less than 1.
///
/// A builder for the *locations.products.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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_products_list("parent")
/// .page_token("elitr")
/// .page_size(-97)
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductListCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductListCall<'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, ListProductsResponse)> {
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: "vision.projects.locations.products.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + 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()));
}
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+parent}/products";
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 project OR ProductSet from which Products should be listed.
///
/// Format:
/// `projects/PROJECT_ID/locations/LOC_ID`
///
/// 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) -> ProjectLocationProductListCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The next_page_token returned from a previous List request, if any.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationProductListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of items to return. Default 10, maximum 100.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationProductListCall<'a, C, A> {
self._page_size = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductListCall<'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) -> ProjectLocationProductListCall<'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
}
}
/// Run asynchronous image detection and annotation for a list of generic
/// files, such as PDF files, which may contain multiple pages and multiple
/// images per page. Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateFilesResponse` (results).
///
/// A builder for the *locations.files.asyncBatchAnnotate* 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_vision1 as vision1;
/// use vision1::AsyncBatchAnnotateFilesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = AsyncBatchAnnotateFilesRequest::default();
///
/// // You can configure optional parameters by calling 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_files_async_batch_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationFileAsyncBatchAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: AsyncBatchAnnotateFilesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationFileAsyncBatchAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationFileAsyncBatchAnnotateCall<'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, Operation)> {
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: "vision.projects.locations.files.asyncBatchAnnotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/files:asyncBatchAnnotate";
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();
let mut json_mime_type = 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: AsyncBatchAnnotateFilesRequest) -> ProjectLocationFileAsyncBatchAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectLocationFileAsyncBatchAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectLocationFileAsyncBatchAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationFileAsyncBatchAnnotateCall<'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) -> ProjectLocationFileAsyncBatchAnnotateCall<'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
}
}
/// Creates and returns a new ProductSet resource.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if display_name is missing, or is longer than
/// 4096 characters.
///
/// A builder for the *locations.productSets.create* method supported by a *project* resource.
/// It is not used directly, but through a `ProjectMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// use vision1::ProductSet;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = ProductSet::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().locations_product_sets_create(req, "parent")
/// .product_set_id("eirmod")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetCreateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: ProductSet,
_parent: String,
_product_set_id: Option<String>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetCreateCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetCreateCall<'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, ProductSet)> {
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: "vision.projects.locations.productSets.create",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
if let Some(value) = self._product_set_id {
params.push(("productSetId", value.to_string()));
}
for &field in ["alt", "parent", "productSetId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/productSets";
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();
let mut json_mime_type = 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: ProductSet) -> ProjectLocationProductSetCreateCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. The project in which the ProductSet should be created.
///
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
///
/// 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) -> ProjectLocationProductSetCreateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// A user-supplied resource id for this ProductSet. If set, the server will
/// attempt to use this value as the resource id. If it is already in use, an
/// error is returned with code ALREADY_EXISTS. Must be at most 128 characters
/// long. It cannot contain the character `/`.
///
/// Sets the *product set id* query property to the given value.
pub fn product_set_id(mut self, new_value: &str) -> ProjectLocationProductSetCreateCall<'a, C, A> {
self._product_set_id = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductSetCreateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetCreateCall<'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) -> ProjectLocationProductSetCreateCall<'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
}
}
/// Service that performs image detection and annotation for a batch of files.
/// Now only "application/pdf", "image/tiff" and "image/gif" are supported.
///
/// This service will extract at most 5 (customers can specify which 5 in
/// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each
/// file provided and perform detection and annotation for each image
/// extracted.
///
/// A builder for the *locations.files.annotate* 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_vision1 as vision1;
/// use vision1::BatchAnnotateFilesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = BatchAnnotateFilesRequest::default();
///
/// // You can configure optional parameters by calling 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_files_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationFileAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: BatchAnnotateFilesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationFileAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationFileAnnotateCall<'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, BatchAnnotateFilesResponse)> {
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: "vision.projects.locations.files.annotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/files:annotate";
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();
let mut json_mime_type = 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: BatchAnnotateFilesRequest) -> ProjectLocationFileAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectLocationFileAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectLocationFileAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationFileAnnotateCall<'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) -> ProjectLocationFileAnnotateCall<'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
}
}
/// Adds a Product to the specified ProductSet. If the Product is already
/// present, no change is made.
///
/// One Product can be added to at most 100 ProductSets.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the Product or the ProductSet doesn't exist.
///
/// A builder for the *locations.productSets.addProduct* 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_vision1 as vision1;
/// use vision1::AddProductToProductSetRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = AddProductToProductSetRequest::default();
///
/// // You can configure optional parameters by calling 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_product_sets_add_product(req, "name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetAddProductCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: AddProductToProductSetRequest,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetAddProductCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetAddProductCall<'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, Empty)> {
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: "vision.projects.locations.productSets.addProduct",
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() + "v1/{+name}:addProduct";
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: AddProductToProductSetRequest) -> ProjectLocationProductSetAddProductCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. The resource name for the ProductSet to modify.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`
///
/// 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) -> ProjectLocationProductSetAddProductCall<'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) -> ProjectLocationProductSetAddProductCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetAddProductCall<'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) -> ProjectLocationProductSetAddProductCall<'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
}
}
/// Asynchronous API that imports a list of reference images to specified
/// product sets based on a list of image information.
///
/// The google.longrunning.Operation API can be used to keep track of the
/// progress and results of the request.
/// `Operation.metadata` contains `BatchOperationMetadata`. (progress)
/// `Operation.response` contains `ImportProductSetsResponse`. (results)
///
/// The input source of this method is a csv file on Google Cloud Storage.
/// For the format of the csv file please see
/// ImportProductSetsGcsSource.csv_file_uri.
///
/// A builder for the *locations.productSets.import* 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_vision1 as vision1;
/// use vision1::ImportProductSetsRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = ImportProductSetsRequest::default();
///
/// // You can configure optional parameters by calling 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_product_sets_import(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetImportCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: ImportProductSetsRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetImportCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetImportCall<'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, Operation)> {
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: "vision.projects.locations.productSets.import",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/productSets:import";
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();
let mut json_mime_type = 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: ImportProductSetsRequest) -> ProjectLocationProductSetImportCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. The project in which the ProductSets should be imported.
///
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
///
/// 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) -> ProjectLocationProductSetImportCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectLocationProductSetImportCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetImportCall<'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) -> ProjectLocationProductSetImportCall<'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
}
}
/// Service that performs image detection and annotation for a batch of files.
/// Now only "application/pdf", "image/tiff" and "image/gif" are supported.
///
/// This service will extract at most 5 (customers can specify which 5 in
/// AnnotateFileRequest.pages) frames (gif) or pages (pdf or tiff) from each
/// file provided and perform detection and annotation for each image
/// extracted.
///
/// A builder for the *files.annotate* 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_vision1 as vision1;
/// use vision1::BatchAnnotateFilesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = BatchAnnotateFilesRequest::default();
///
/// // You can configure optional parameters by calling 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().files_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectFileAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: BatchAnnotateFilesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectFileAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectFileAnnotateCall<'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, BatchAnnotateFilesResponse)> {
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: "vision.projects.files.annotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/files:annotate";
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();
let mut json_mime_type = 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: BatchAnnotateFilesRequest) -> ProjectFileAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectFileAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectFileAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectFileAnnotateCall<'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) -> ProjectFileAnnotateCall<'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
}
}
/// Makes changes to a Product resource.
/// Only the `display_name`, `description`, and `labels` fields can be updated
/// right now.
///
/// If labels are updated, the change will not be reflected in queries until
/// the next index time.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the Product does not exist.
/// * Returns INVALID_ARGUMENT if display_name is present in update_mask but is
/// missing from the request or longer than 4096 characters.
/// * Returns INVALID_ARGUMENT if description is present in update_mask but is
/// longer than 4096 characters.
/// * Returns INVALID_ARGUMENT if product_category is present in update_mask.
///
/// A builder for the *locations.products.patch* 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_vision1 as vision1;
/// use vision1::Product;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = Product::default();
///
/// // You can configure optional parameters by calling 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_products_patch(req, "name")
/// .update_mask("sea")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductPatchCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: Product,
_name: String,
_update_mask: Option<String>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductPatchCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductPatchCall<'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, Product)> {
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: "vision.projects.locations.products.patch",
http_method: hyper::method::Method::Patch });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("name", self._name.to_string()));
if let Some(value) = self._update_mask {
params.push(("updateMask", value.to_string()));
}
for &field in ["alt", "name", "updateMask"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+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();
let mut json_mime_type = 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::Patch, 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: Product) -> ProjectLocationProductPatchCall<'a, C, A> {
self._request = new_value;
self
}
/// The resource name of the product.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
///
/// This field is ignored when creating a product.
///
/// 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) -> ProjectLocationProductPatchCall<'a, C, A> {
self._name = new_value.to_string();
self
}
/// The FieldMask that specifies which fields
/// to update.
/// If update_mask isn't specified, all mutable fields are to be updated.
/// Valid mask paths include `product_labels`, `display_name`, and
/// `description`.
///
/// Sets the *update mask* query property to the given value.
pub fn update_mask(mut self, new_value: &str) -> ProjectLocationProductPatchCall<'a, C, A> {
self._update_mask = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductPatchCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductPatchCall<'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) -> ProjectLocationProductPatchCall<'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
}
}
/// Makes changes to a ProductSet resource.
/// Only display_name can be updated currently.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the ProductSet does not exist.
/// * Returns INVALID_ARGUMENT if display_name is present in update_mask but
/// missing from the request or longer than 4096 characters.
///
/// A builder for the *locations.productSets.patch* 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_vision1 as vision1;
/// use vision1::ProductSet;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = ProductSet::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().locations_product_sets_patch(req, "name")
/// .update_mask("duo")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetPatchCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: ProductSet,
_name: String,
_update_mask: Option<String>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetPatchCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetPatchCall<'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, ProductSet)> {
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: "vision.projects.locations.productSets.patch",
http_method: hyper::method::Method::Patch });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("name", self._name.to_string()));
if let Some(value) = self._update_mask {
params.push(("updateMask", value.to_string()));
}
for &field in ["alt", "name", "updateMask"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+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();
let mut json_mime_type = 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::Patch, 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: ProductSet) -> ProjectLocationProductSetPatchCall<'a, C, A> {
self._request = new_value;
self
}
/// The resource name of the ProductSet.
///
/// Format is:
/// `projects/PROJECT_ID/locations/LOC_ID/productSets/PRODUCT_SET_ID`.
///
/// This field is ignored when creating a ProductSet.
///
/// 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) -> ProjectLocationProductSetPatchCall<'a, C, A> {
self._name = new_value.to_string();
self
}
/// The FieldMask that specifies which fields to
/// update.
/// If update_mask isn't specified, all mutable fields are to be updated.
/// Valid mask path is `display_name`.
///
/// Sets the *update mask* query property to the given value.
pub fn update_mask(mut self, new_value: &str) -> ProjectLocationProductSetPatchCall<'a, C, A> {
self._update_mask = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductSetPatchCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetPatchCall<'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) -> ProjectLocationProductSetPatchCall<'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 ProductSets in an unspecified order.
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if page_size is greater than 100, or less
/// than 1.
///
/// A builder for the *locations.productSets.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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_product_sets_list("parent")
/// .page_token("eirmod")
/// .page_size(-58)
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductSetListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductSetListCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductSetListCall<'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, ListProductSetsResponse)> {
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: "vision.projects.locations.productSets.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + 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()));
}
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+parent}/productSets";
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 project from which ProductSets should be listed.
///
/// Format is `projects/PROJECT_ID/locations/LOC_ID`.
///
/// 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) -> ProjectLocationProductSetListCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The next_page_token returned from a previous List request, if any.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationProductSetListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of items to return. Default 10, maximum 100.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationProductSetListCall<'a, C, A> {
self._page_size = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductSetListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductSetListCall<'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) -> ProjectLocationProductSetListCall<'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
}
}
/// Run asynchronous image detection and annotation for a list of images.
///
/// Progress and results can be retrieved through the
/// `google.longrunning.Operations` interface.
/// `Operation.metadata` contains `OperationMetadata` (metadata).
/// `Operation.response` contains `AsyncBatchAnnotateImagesResponse` (results).
///
/// This service will write image annotation outputs to json files in customer
/// GCS bucket, each json file containing BatchAnnotateImagesResponse proto.
///
/// A builder for the *locations.images.asyncBatchAnnotate* 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_vision1 as vision1;
/// use vision1::AsyncBatchAnnotateImagesRequest;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = AsyncBatchAnnotateImagesRequest::default();
///
/// // You can configure optional parameters by calling 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_images_async_batch_annotate(req, "parent")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationImageAsyncBatchAnnotateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: AsyncBatchAnnotateImagesRequest,
_parent: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationImageAsyncBatchAnnotateCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationImageAsyncBatchAnnotateCall<'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, Operation)> {
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: "vision.projects.locations.images.asyncBatchAnnotate",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(4 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/images:asyncBatchAnnotate";
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();
let mut json_mime_type = 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: AsyncBatchAnnotateImagesRequest) -> ProjectLocationImageAsyncBatchAnnotateCall<'a, C, A> {
self._request = new_value;
self
}
/// Optional. Target project and location to make a call.
///
/// Format: `projects/{project-id}/locations/{location-id}`.
///
/// If no parent is specified, a region will be chosen automatically.
///
/// Supported location-ids:
/// `us`: USA country only,
/// `asia`: East asia areas, like Japan, Taiwan,
/// `eu`: The European Union.
///
/// Example: `projects/project-A/locations/eu`.
///
/// 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) -> ProjectLocationImageAsyncBatchAnnotateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and 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) -> ProjectLocationImageAsyncBatchAnnotateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationImageAsyncBatchAnnotateCall<'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) -> ProjectLocationImageAsyncBatchAnnotateCall<'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
}
}
/// Creates and returns a new ReferenceImage resource.
///
/// The `bounding_poly` field is optional. If `bounding_poly` is not specified,
/// the system will try to detect regions of interest in the image that are
/// compatible with the product_category on the parent product. If it is
/// specified, detection is ALWAYS skipped. The system converts polygons into
/// non-rotated rectangles.
///
/// Note that the pipeline will resize the image if the image resolution is too
/// large to process (above 50MP).
///
/// Possible errors:
///
/// * Returns INVALID_ARGUMENT if the image_uri is missing or longer than 4096
/// characters.
/// * Returns INVALID_ARGUMENT if the product does not exist.
/// * Returns INVALID_ARGUMENT if bounding_poly is not provided, and nothing
/// compatible with the parent product's product_category is detected.
/// * Returns INVALID_ARGUMENT if bounding_poly contains more than 10 polygons.
///
/// A builder for the *locations.products.referenceImages.create* method supported by a *project* resource.
/// It is not used directly, but through a `ProjectMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// use vision1::ReferenceImage;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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 = ReferenceImage::default();
///
/// // You can configure optional parameters by calling 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_products_reference_images_create(req, "parent")
/// .reference_image_id("et")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductReferenceImageCreateCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_request: ReferenceImage,
_parent: String,
_reference_image_id: Option<String>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductReferenceImageCreateCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductReferenceImageCreateCall<'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, ReferenceImage)> {
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: "vision.projects.locations.products.referenceImages.create",
http_method: hyper::method::Method::Post });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + self._additional_params.len());
params.push(("parent", self._parent.to_string()));
if let Some(value) = self._reference_image_id {
params.push(("referenceImageId", value.to_string()));
}
for &field in ["alt", "parent", "referenceImageId"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::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() + "v1/{+parent}/referenceImages";
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();
let mut json_mime_type = 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: ReferenceImage) -> ProjectLocationProductReferenceImageCreateCall<'a, C, A> {
self._request = new_value;
self
}
/// Required. Resource name of the product in which to create the reference image.
///
/// Format is
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
///
/// 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) -> ProjectLocationProductReferenceImageCreateCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// A user-supplied resource id for the ReferenceImage to be added. If set,
/// the server will attempt to use this value as the resource id. If it is
/// already in use, an error is returned with code ALREADY_EXISTS. Must be at
/// most 128 characters long. It cannot contain the character `/`.
///
/// Sets the *reference image id* query property to the given value.
pub fn reference_image_id(mut self, new_value: &str) -> ProjectLocationProductReferenceImageCreateCall<'a, C, A> {
self._reference_image_id = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductReferenceImageCreateCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductReferenceImageCreateCall<'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) -> ProjectLocationProductReferenceImageCreateCall<'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
}
}
/// Permanently deletes a reference image.
///
/// The image metadata will be deleted right away, but search queries
/// against ProductSets containing the image may still work until all related
/// caches are refreshed.
///
/// The actual image files are not deleted from Google Cloud Storage.
///
/// A builder for the *locations.products.referenceImages.delete* method supported by a *project* resource.
/// It is not used directly, but through a `ProjectMethods` instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate yup_oauth2 as oauth2;
/// # extern crate google_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_products_reference_images_delete("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductReferenceImageDeleteCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductReferenceImageDeleteCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductReferenceImageDeleteCall<'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, Empty)> {
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: "vision.projects.locations.products.referenceImages.delete",
http_method: hyper::method::Method::Delete });
let mut params: Vec<(&str, String)> = Vec::with_capacity(3 + self._additional_params.len());
params.push(("name", self._name.to_string()));
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+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::Delete, 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 resource name of the reference image to delete.
///
/// Format is:
///
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`
///
/// 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) -> ProjectLocationProductReferenceImageDeleteCall<'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) -> ProjectLocationProductReferenceImageDeleteCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductReferenceImageDeleteCall<'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) -> ProjectLocationProductReferenceImageDeleteCall<'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 information associated with a ReferenceImage.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the specified image does not exist.
///
/// A builder for the *locations.products.referenceImages.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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_products_reference_images_get("name")
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductReferenceImageGetCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_name: String,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductReferenceImageGetCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductReferenceImageGetCall<'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, ReferenceImage)> {
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: "vision.projects.locations.products.referenceImages.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() + "v1/{+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. The resource name of the ReferenceImage to get.
///
/// Format is:
///
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID/referenceImages/IMAGE_ID`.
///
/// 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) -> ProjectLocationProductReferenceImageGetCall<'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) -> ProjectLocationProductReferenceImageGetCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductReferenceImageGetCall<'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) -> ProjectLocationProductReferenceImageGetCall<'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 reference images.
///
/// Possible errors:
///
/// * Returns NOT_FOUND if the parent product does not exist.
/// * Returns INVALID_ARGUMENT if the page_size is greater than 100, or less
/// than 1.
///
/// A builder for the *locations.products.referenceImages.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_vision1 as vision1;
/// # #[test] fn egal() {
/// # use std::default::Default;
/// # use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage};
/// # use vision1::Vision;
///
/// # 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 = Vision::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_products_reference_images_list("parent")
/// .page_token("sed")
/// .page_size(-3)
/// .doit();
/// # }
/// ```
pub struct ProjectLocationProductReferenceImageListCall<'a, C, A>
where C: 'a, A: 'a {
hub: &'a Vision<C, A>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeMap<String, ()>
}
impl<'a, C, A> CallBuilder for ProjectLocationProductReferenceImageListCall<'a, C, A> {}
impl<'a, C, A> ProjectLocationProductReferenceImageListCall<'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, ListReferenceImagesResponse)> {
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: "vision.projects.locations.products.referenceImages.list",
http_method: hyper::method::Method::Get });
let mut params: Vec<(&str, String)> = Vec::with_capacity(5 + 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()));
}
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(Error::FieldClash(field));
}
}
for (name, value) in self._additional_params.iter() {
params.push((&name, value.clone()));
}
params.push(("alt", "json".to_string()));
let mut url = self.hub._base_url.clone() + "v1/{+parent}/referenceImages";
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. Resource name of the product containing the reference images.
///
/// Format is
/// `projects/PROJECT_ID/locations/LOC_ID/products/PRODUCT_ID`.
///
/// 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) -> ProjectLocationProductReferenceImageListCall<'a, C, A> {
self._parent = new_value.to_string();
self
}
/// A token identifying a page of results to be returned. This is the value
/// of `nextPageToken` returned in a previous reference image list request.
///
/// Defaults to the first page if not specified.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationProductReferenceImageListCall<'a, C, A> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of items to return. Default 10, maximum 100.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationProductReferenceImageListCall<'a, C, A> {
self._page_size = Some(new_value);
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// It should be used to handle progress information, and to implement a certain level of resilience.
///
/// Sets the *delegate* property to the given value.
pub fn delegate(mut self, new_value: &'a mut dyn Delegate) -> ProjectLocationProductReferenceImageListCall<'a, C, A> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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) -> ProjectLocationProductReferenceImageListCall<'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) -> ProjectLocationProductReferenceImageListCall<'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
}
}