#![allow(clippy::ptr_arg)]
use std::collections::{BTreeSet, HashMap};
use tokio::time::sleep;
// ##############
// 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, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
pub enum Scope {
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
CloudPlatform,
/// Translate text from one language to another using Google Translate
CloudTranslation,
}
impl AsRef<str> for Scope {
fn as_ref(&self) -> &str {
match *self {
Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
Scope::CloudTranslation => "https://www.googleapis.com/auth/cloud-translation",
}
}
}
#[allow(clippy::derivable_impls)]
impl Default for Scope {
fn default() -> Scope {
Scope::CloudPlatform
}
}
// ########
// HUB ###
// ######
/// Central instance to access all Translate related resource activities
///
/// # Examples
///
/// Instantiate a new hub
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_translate3 as translate3;
/// use translate3::api::Glossary;
/// use translate3::{Result, Error};
/// # async fn dox() {
/// use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
/// // `client_secret`, among other things.
/// let secret: yup_oauth2::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 = yup_oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http1()
/// .build()
/// );
/// let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Glossary::default();
///
/// // You can configure optional parameters by calling 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_glossaries_patch(req, "name")
/// .update_mask(FieldMask::new::<&str>(&[]))
/// .doit().await;
///
/// 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::Io(_)
/// |Error::MissingAPIKey
/// |Error::MissingToken(_)
/// |Error::Cancelled
/// |Error::UploadSizeLimitExceeded(_, _)
/// |Error::Failure(_)
/// |Error::BadRequest(_)
/// |Error::FieldClash(_)
/// |Error::JsonDecodeError(_, _) => println!("{}", e),
/// },
/// Ok(res) => println!("Success: {:?}", res),
/// }
/// # }
/// ```
#[derive(Clone)]
pub struct Translate<C> {
pub client: common::Client<C>,
pub auth: Box<dyn common::GetToken>,
_user_agent: String,
_base_url: String,
_root_url: String,
}
impl<C> common::Hub for Translate<C> {}
impl<'a, C> Translate<C> {
pub fn new<A: 'static + common::GetToken>(client: common::Client<C>, auth: A) -> Translate<C> {
Translate {
client,
auth: Box::new(auth),
_user_agent: "google-api-rust-client/6.0.0".to_string(),
_base_url: "https://translation.googleapis.com/".to_string(),
_root_url: "https://translation.googleapis.com/".to_string(),
}
}
pub fn projects(&'a self) -> ProjectMethods<'a, C> {
ProjectMethods { hub: self }
}
/// Set the user-agent header field to use in all requests to the server.
/// It defaults to `google-api-rust-client/6.0.0`.
///
/// Returns the previously set user-agent.
pub fn user_agent(&mut self, agent_name: String) -> String {
std::mem::replace(&mut self._user_agent, agent_name)
}
/// Set the base url to use in all requests to the server.
/// It defaults to `https://translation.googleapis.com/`.
///
/// Returns the previously set base url.
pub fn base_url(&mut self, new_base_url: String) -> String {
std::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://translation.googleapis.com/`.
///
/// Returns the previously set root url.
pub fn root_url(&mut self, new_root_url: String) -> String {
std::mem::replace(&mut self._root_url, new_root_url)
}
}
// ############
// SCHEMAS ###
// ##########
/// An Adaptive MT Dataset.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations adaptive mt datasets create projects](ProjectLocationAdaptiveMtDatasetCreateCall) (request|response)
/// * [locations adaptive mt datasets get projects](ProjectLocationAdaptiveMtDatasetGetCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AdaptiveMtDataset {
/// Output only. Timestamp when this dataset was created.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The name of the dataset to show in the interface. The name can be up to 32 characters long and can consist only of ASCII Latin letters A-Z and a-z, underscores (_), and ASCII digits 0-9.
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// The number of examples in the dataset.
#[serde(rename = "exampleCount")]
pub example_count: Option<i32>,
/// Required. The resource name of the dataset, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset_id}`
pub name: Option<String>,
/// The BCP-47 language code of the source language.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// The BCP-47 language code of the target language.
#[serde(rename = "targetLanguageCode")]
pub target_language_code: Option<String>,
/// Output only. Timestamp when this dataset was last updated.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::RequestValue for AdaptiveMtDataset {}
impl common::ResponseResult for AdaptiveMtDataset {}
/// An AdaptiveMtFile.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 adaptive mt datasets adaptive mt files get projects](ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AdaptiveMtFile {
/// Output only. Timestamp when this file was created.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The file's display name.
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// The number of entries that the file contains.
#[serde(rename = "entryCount")]
pub entry_count: Option<i32>,
/// Required. The resource name of the file, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
pub name: Option<String>,
/// Output only. Timestamp when this file was last updated.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::ResponseResult for AdaptiveMtFile {}
/// An AdaptiveMt sentence entry.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AdaptiveMtSentence {
/// Output only. Timestamp when this sentence was created.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Required. The resource name of the file, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}/adaptiveMtSentences/{sentence}`
pub name: Option<String>,
/// Required. The source sentence.
#[serde(rename = "sourceSentence")]
pub source_sentence: Option<String>,
/// Required. The target sentence.
#[serde(rename = "targetSentence")]
pub target_sentence: Option<String>,
/// Output only. Timestamp when this sentence was last updated.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::Part for AdaptiveMtSentence {}
/// The request for sending an AdaptiveMt translation query.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations adaptive mt translate projects](ProjectLocationAdaptiveMtTranslateCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AdaptiveMtTranslateRequest {
/// Required. The content of the input in string format. For now only one sentence per request is supported.
pub content: Option<Vec<String>>,
/// Required. The resource name for the dataset to use for adaptive MT. `projects/{project}/locations/{location-id}/adaptiveMtDatasets/{dataset}`
pub dataset: Option<String>,
}
impl common::RequestValue for AdaptiveMtTranslateRequest {}
/// An AdaptiveMtTranslate response.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations adaptive mt translate projects](ProjectLocationAdaptiveMtTranslateCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AdaptiveMtTranslateResponse {
/// Output only. The translation's language code.
#[serde(rename = "languageCode")]
pub language_code: Option<String>,
/// Output only. The translation.
pub translations: Option<Vec<AdaptiveMtTranslation>>,
}
impl common::ResponseResult for AdaptiveMtTranslateResponse {}
/// An AdaptiveMt translation.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AdaptiveMtTranslation {
/// Output only. The translated text.
#[serde(rename = "translatedText")]
pub translated_text: Option<String>,
}
impl common::Part for AdaptiveMtTranslation {}
/// Input configuration for BatchTranslateDocument request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BatchDocumentInputConfig {
/// Google Cloud Storage location for the source input. This can be a single file (for example, `gs://translation-test/input.docx`) or a wildcard (for example, `gs://translation-test/*`). File mime type is determined based on extension. Supported mime type includes: - `pdf`, application/pdf - `docx`, application/vnd.openxmlformats-officedocument.wordprocessingml.document - `pptx`, application/vnd.openxmlformats-officedocument.presentationml.presentation - `xlsx`, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet The max file size to support for `.docx`, `.pptx` and `.xlsx` is 100MB. The max file size to support for `.pdf` is 1GB and the max page limit is 1000 pages. The max file size to support for all input documents is 1GB.
#[serde(rename = "gcsSource")]
pub gcs_source: Option<GcsSource>,
}
impl common::Part for BatchDocumentInputConfig {}
/// Output configuration for BatchTranslateDocument request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BatchDocumentOutputConfig {
/// Google Cloud Storage destination for output content. For every single input document (for example, gs://a/b/c.[extension]), we generate at most 2 * n output files. (n is the # of target_language_codes in the BatchTranslateDocumentRequest). While the input documents are being processed, we write/update an index file `index.csv` under `gcs_destination.output_uri_prefix` (for example, gs://translation_output/index.csv) The index file is generated/updated as new files are being translated. The format is: input_document,target_language_code,translation_output,error_output, glossary_translation_output,glossary_error_output `input_document` is one file we matched using gcs_source.input_uri. `target_language_code` is provided in the request. `translation_output` contains the translations. (details provided below) `error_output` contains the error message during processing of the file. Both translations_file and errors_file could be empty strings if we have no content to output. `glossary_translation_output` and `glossary_error_output` are the translated output/error when we apply glossaries. They could also be empty if we have no content to output. Once a row is present in index.csv, the input/output matching never changes. Callers should also expect all the content in input_file are processed and ready to be consumed (that is, no partial output file is written). Since index.csv will be keeping updated during the process, please make sure there is no custom retention policy applied on the output bucket that may avoid file updating. (https://cloud.google.com/storage/docs/bucket-lock#retention-policy) The naming format of translation output files follows (for target language code [trg]): `translation_output`: `gs://translation_output/a_b_c_[trg]_translation.[extension]` `glossary_translation_output`: `gs://translation_test/a_b_c_[trg]_glossary_translation.[extension]`. The output document will maintain the same file format as the input document. The naming format of error output files follows (for target language code [trg]): `error_output`: `gs://translation_test/a_b_c_[trg]_errors.txt` `glossary_error_output`: `gs://translation_test/a_b_c_[trg]_glossary_translation.txt`. The error output is a txt file containing error details.
#[serde(rename = "gcsDestination")]
pub gcs_destination: Option<GcsDestination>,
}
impl common::Part for BatchDocumentOutputConfig {}
/// The BatchTranslateDocument 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*).
///
/// * [locations batch translate document projects](ProjectLocationBatchTranslateDocumentCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BatchTranslateDocumentRequest {
/// Optional. This flag is to support user customized attribution. If not provided, the default is `Machine Translated by Google`. Customized attribution should follow rules in https://cloud.google.com/translate/attribution#attribution_and_logos
#[serde(rename = "customizedAttribution")]
pub customized_attribution: Option<String>,
/// Optional. If true, enable auto rotation correction in DVS.
#[serde(rename = "enableRotationCorrection")]
pub enable_rotation_correction: Option<bool>,
/// Optional. If true, use the text removal server to remove the shadow text on background image for native pdf translation. Shadow removal feature can only be enabled when is_translate_native_pdf_only: false && pdf_native_only: false
#[serde(rename = "enableShadowRemovalNativePdf")]
pub enable_shadow_removal_native_pdf: Option<bool>,
/// Optional. The file format conversion map that is applied to all input files. The map key is the original mime_type. The map value is the target mime_type of translated documents. Supported file format conversion includes: - `application/pdf` to `application/vnd.openxmlformats-officedocument.wordprocessingml.document` If nothing specified, output files will be in the same format as the original file.
#[serde(rename = "formatConversions")]
pub format_conversions: Option<HashMap<String, String>>,
/// Optional. Glossaries to be applied. It's keyed by target language code.
pub glossaries: Option<HashMap<String, TranslateTextGlossaryConfig>>,
/// Required. Input configurations. The total number of files matched should be <= 100. The total content size to translate should be <= 100M Unicode codepoints. The files must use UTF-8 encoding.
#[serde(rename = "inputConfigs")]
pub input_configs: Option<Vec<BatchDocumentInputConfig>>,
/// Optional. The models to use for translation. Map's key is target language code. Map's value is the model name. Value can be a built-in general model, or an AutoML Translation model. The value format depends on model type: - AutoML Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, If the map is empty or a specific model is not requested for a language pair, then default google model (nmt) is used.
pub models: Option<HashMap<String, String>>,
/// Required. Output configuration. If 2 input configs match to the same file (that is, same input path), we don't generate output for duplicate inputs.
#[serde(rename = "outputConfig")]
pub output_config: Option<BatchDocumentOutputConfig>,
/// Required. The ISO-639 language code of the input document if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in [Language Support](https://cloud.google.com/translate/docs/languages).
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// Required. The ISO-639 language code to use for translation of the input document. Specify up to 10 language codes here.
#[serde(rename = "targetLanguageCodes")]
pub target_language_codes: Option<Vec<String>>,
}
impl common::RequestValue for BatchTranslateDocumentRequest {}
/// The batch translation 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*).
///
/// * [locations batch translate text projects](ProjectLocationBatchTranslateTextCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct BatchTranslateTextRequest {
/// Optional. Glossaries to be applied for translation. It's keyed by target language code.
pub glossaries: Option<HashMap<String, TranslateTextGlossaryConfig>>,
/// Required. Input configurations. The total number of files matched should be <= 100. The total content size should be <= 100M Unicode codepoints. The files must use UTF-8 encoding.
#[serde(rename = "inputConfigs")]
pub input_configs: Option<Vec<InputConfig>>,
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
pub labels: Option<HashMap<String, String>>,
/// Optional. The models to use for translation. Map's key is target language code. Map's value is model name. Value can be a built-in general model, or an AutoML Translation model. The value format depends on model type: - AutoML Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, If the map is empty or a specific model is not requested for a language pair, then default google model (nmt) is used.
pub models: Option<HashMap<String, String>>,
/// Required. Output configuration. If 2 input configs match to the same file (that is, same input path), we don't generate output for duplicate inputs.
#[serde(rename = "outputConfig")]
pub output_config: Option<OutputConfig>,
/// Required. Source language code.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// Required. Specify up to 10 language codes here.
#[serde(rename = "targetLanguageCodes")]
pub target_language_codes: Option<Vec<String>>,
}
impl common::RequestValue for BatchTranslateTextRequest {}
/// 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*).
///
/// * [locations operations cancel projects](ProjectLocationOperationCancelCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct CancelOperationRequest {
_never_set: Option<bool>,
}
impl common::RequestValue for CancelOperationRequest {}
/// A dataset that hosts the examples (sentence pairs) used for translation models.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 datasets create projects](ProjectLocationDatasetCreateCall) (request)
/// * [locations datasets get projects](ProjectLocationDatasetGetCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Dataset {
/// Output only. Timestamp when this dataset was created.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The name of the dataset to show in the interface. The name can be up to 32 characters long and can consist only of ASCII Latin letters A-Z and a-z, underscores (_), and ASCII digits 0-9.
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// Output only. The number of examples in the dataset.
#[serde(rename = "exampleCount")]
pub example_count: Option<i32>,
/// The resource name of the dataset, in form of `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}`
pub name: Option<String>,
/// The BCP-47 language code of the source language.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// The BCP-47 language code of the target language.
#[serde(rename = "targetLanguageCode")]
pub target_language_code: Option<String>,
/// Output only. Number of test examples (sentence pairs).
#[serde(rename = "testExampleCount")]
pub test_example_count: Option<i32>,
/// Output only. Number of training examples (sentence pairs).
#[serde(rename = "trainExampleCount")]
pub train_example_count: Option<i32>,
/// Output only. Timestamp when this dataset was last updated.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Output only. Number of validation examples (sentence pairs).
#[serde(rename = "validateExampleCount")]
pub validate_example_count: Option<i32>,
}
impl common::RequestValue for Dataset {}
impl common::ResponseResult for Dataset {}
/// Input configuration for datasets.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DatasetInputConfig {
/// Files containing the sentence pairs to be imported to the dataset.
#[serde(rename = "inputFiles")]
pub input_files: Option<Vec<InputFile>>,
}
impl common::Part for DatasetInputConfig {}
/// Output configuration for datasets.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DatasetOutputConfig {
/// Google Cloud Storage destination to write the output.
#[serde(rename = "gcsDestination")]
pub gcs_destination: Option<GcsOutputDestination>,
}
impl common::Part for DatasetOutputConfig {}
/// The request message for language detection.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 detect language projects](ProjectLocationDetectLanguageCall) (request)
/// * [detect language projects](ProjectDetectLanguageCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DetectLanguageRequest {
/// The content of the input stored as a string.
pub content: Option<String>,
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
pub labels: Option<HashMap<String, String>>,
/// Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type defaults to "text/html".
#[serde(rename = "mimeType")]
pub mime_type: Option<String>,
/// Optional. The language detection model to be used. Format: `projects/{project-number-or-id}/locations/{location-id}/models/language-detection/{model-id}` Only one language detection model is currently supported: `projects/{project-number-or-id}/locations/{location-id}/models/language-detection/default`. If not specified, the default model is used.
pub model: Option<String>,
}
impl common::RequestValue for DetectLanguageRequest {}
/// The response message for language detection.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 detect language projects](ProjectLocationDetectLanguageCall) (response)
/// * [detect language projects](ProjectDetectLanguageCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DetectLanguageResponse {
/// The most probable language detected by the Translation API. For each request, the Translation API will always return only one result.
pub languages: Option<Vec<DetectedLanguage>>,
}
impl common::ResponseResult for DetectLanguageResponse {}
/// The response message for language detection.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DetectedLanguage {
/// The confidence of the detection result for this language.
pub confidence: Option<f32>,
/// The ISO-639 language code of the source content in the request, detected automatically.
#[serde(rename = "languageCode")]
pub language_code: Option<String>,
}
impl common::Part for DetectedLanguage {}
/// A document translation request input config.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DocumentInputConfig {
/// Document's content represented as a stream of bytes.
#[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
pub content: Option<Vec<u8>>,
/// Google Cloud Storage location. This must be a single file. For example: gs://example_bucket/example_file.pdf
#[serde(rename = "gcsSource")]
pub gcs_source: Option<GcsSource>,
/// Specifies the input document's mime_type. If not specified it will be determined using the file extension for gcs_source provided files. For a file provided through bytes content the mime_type must be provided. Currently supported mime types are: - application/pdf - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
#[serde(rename = "mimeType")]
pub mime_type: Option<String>,
}
impl common::Part for DocumentInputConfig {}
/// A document translation request output config.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DocumentOutputConfig {
/// Optional. Google Cloud Storage destination for the translation output, e.g., `gs://my_bucket/my_directory/`. The destination directory provided does not have to be empty, but the bucket must exist. If a file with the same name as the output file already exists in the destination an error will be returned. For a DocumentInputConfig.contents provided document, the output file will have the name "output_[trg]_translations.[ext]", where - [trg] corresponds to the translated file's language code, - [ext] corresponds to the translated file's extension according to its mime type. For a DocumentInputConfig.gcs_uri provided document, the output file will have a name according to its URI. For example: an input file with URI: `gs://a/b/c.[extension]` stored in a gcs_destination bucket with name "my_bucket" will have an output URI: `gs://my_bucket/a_b_c_[trg]_translations.[ext]`, where - [trg] corresponds to the translated file's language code, - [ext] corresponds to the translated file's extension according to its mime type. If the document was directly provided through the request, then the output document will have the format: `gs://my_bucket/translated_document_[trg]_translations.[ext]`, where - [trg] corresponds to the translated file's language code, - [ext] corresponds to the translated file's extension according to its mime type. If a glossary was provided, then the output URI for the glossary translation will be equal to the default output URI but have `glossary_translations` instead of `translations`. For the previous example, its glossary URI would be: `gs://my_bucket/a_b_c_[trg]_glossary_translations.[ext]`. Thus the max number of output files will be 2 (Translated document, Glossary translated document). Callers should expect no partial outputs. If there is any error during document translation, no output will be stored in the Cloud Storage bucket.
#[serde(rename = "gcsDestination")]
pub gcs_destination: Option<GcsDestination>,
/// Optional. Specifies the translated document's mime_type. If not specified, the translated file's mime type will be the same as the input file's mime type. Currently only support the output mime type to be the same as input mime type. - application/pdf - application/vnd.openxmlformats-officedocument.wordprocessingml.document - application/vnd.openxmlformats-officedocument.presentationml.presentation - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
#[serde(rename = "mimeType")]
pub mime_type: Option<String>,
}
impl common::Part for DocumentOutputConfig {}
/// A translated document message.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DocumentTranslation {
/// The array of translated documents. It is expected to be size 1 for now. We may produce multiple translated documents in the future for other type of file formats.
#[serde(rename = "byteStreamOutputs")]
#[serde_as(as = "Option<Vec<common::serde::standard_base64::Wrapper>>")]
pub byte_stream_outputs: Option<Vec<Vec<u8>>>,
/// The detected language for the input document. If the user did not provide the source language for the input document, this field will have the language code automatically detected. If the source language was passed, auto-detection of the language does not occur and this field is empty.
#[serde(rename = "detectedLanguageCode")]
pub detected_language_code: Option<String>,
/// The translated document's mime type.
#[serde(rename = "mimeType")]
pub mime_type: Option<String>,
}
impl common::Part for DocumentTranslation {}
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 adaptive mt datasets adaptive mt files delete projects](ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall) (response)
/// * [locations adaptive mt datasets delete projects](ProjectLocationAdaptiveMtDatasetDeleteCall) (response)
/// * [locations glossaries glossary entries delete projects](ProjectLocationGlossaryGlossaryEntryDeleteCall) (response)
/// * [locations operations cancel projects](ProjectLocationOperationCancelCall) (response)
/// * [locations operations delete projects](ProjectLocationOperationDeleteCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Empty {
_never_set: Option<bool>,
}
impl common::ResponseResult for Empty {}
/// A sentence pair.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Example {
/// Output only. The resource name of the example, in form of `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}/examples/{example_id}'
pub name: Option<String>,
/// Sentence in source language.
#[serde(rename = "sourceText")]
pub source_text: Option<String>,
/// Sentence in target language.
#[serde(rename = "targetText")]
pub target_text: Option<String>,
/// Output only. Usage of the sentence pair. Options are TRAIN|VALIDATION|TEST.
pub usage: Option<String>,
}
impl common::Part for Example {}
/// Request message for ExportData.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 datasets export data projects](ProjectLocationDatasetExportDataCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ExportDataRequest {
/// Required. The config for the output content.
#[serde(rename = "outputConfig")]
pub output_config: Option<DatasetOutputConfig>,
}
impl common::RequestValue for ExportDataRequest {}
/// An inlined file.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct FileInputSource {
/// Required. The file's byte contents.
#[serde_as(as = "Option<common::serde::standard_base64::Wrapper>")]
pub content: Option<Vec<u8>>,
/// Required. The file's display name.
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// Required. The file's mime type.
#[serde(rename = "mimeType")]
pub mime_type: Option<String>,
}
impl common::Part for FileInputSource {}
/// The Google Cloud Storage location for the output content.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GcsDestination {
/// Required. The bucket used in 'output_uri_prefix' must exist and there must be no files under 'output_uri_prefix'. 'output_uri_prefix' must end with "/" and start with "gs://". One 'output_uri_prefix' can only be used by one batch translation job at a time. Otherwise an INVALID_ARGUMENT (400) error is returned.
#[serde(rename = "outputUriPrefix")]
pub output_uri_prefix: Option<String>,
}
impl common::Part for GcsDestination {}
/// The Google Cloud Storage location for the input content.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GcsInputSource {
/// Required. Source data URI. For example, `gs://my_bucket/my_object`.
#[serde(rename = "inputUri")]
pub input_uri: Option<String>,
}
impl common::Part for GcsInputSource {}
/// The Google Cloud Storage location for the output content.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GcsOutputDestination {
/// Required. Google Cloud Storage URI to output directory. For example, `gs://bucket/directory`. The requesting user must have write permission to the bucket. The directory will be created if it doesn't exist.
#[serde(rename = "outputUriPrefix")]
pub output_uri_prefix: Option<String>,
}
impl common::Part for GcsOutputDestination {}
/// The Google Cloud Storage location for the input content.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GcsSource {
/// Required. Source data URI. For example, `gs://my_bucket/my_object`.
#[serde(rename = "inputUri")]
pub input_uri: Option<String>,
}
impl common::Part for GcsSource {}
/// Represents a glossary built from user-provided data.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations glossaries create projects](ProjectLocationGlossaryCreateCall) (request)
/// * [locations glossaries get projects](ProjectLocationGlossaryGetCall) (response)
/// * [locations glossaries patch projects](ProjectLocationGlossaryPatchCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Glossary {
/// Optional. The display name of the glossary.
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// Output only. When the glossary creation was finished.
#[serde(rename = "endTime")]
pub end_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Output only. The number of entries defined in the glossary.
#[serde(rename = "entryCount")]
pub entry_count: Option<i32>,
/// Required. Provides examples to build the glossary from. Total glossary must not exceed 10M Unicode codepoints.
#[serde(rename = "inputConfig")]
pub input_config: Option<GlossaryInputConfig>,
/// Used with equivalent term set glossaries.
#[serde(rename = "languageCodesSet")]
pub language_codes_set: Option<LanguageCodesSet>,
/// Used with unidirectional glossaries.
#[serde(rename = "languagePair")]
pub language_pair: Option<LanguageCodePair>,
/// Required. The resource name of the glossary. Glossary names have the form `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`.
pub name: Option<String>,
/// Output only. When CreateGlossary was called.
#[serde(rename = "submitTime")]
pub submit_time: Option<chrono::DateTime<chrono::offset::Utc>>,
}
impl common::RequestValue for Glossary {}
impl common::ResponseResult for Glossary {}
/// Represents a single entry in a glossary.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 glossaries glossary entries create projects](ProjectLocationGlossaryGlossaryEntryCreateCall) (request|response)
/// * [locations glossaries glossary entries get projects](ProjectLocationGlossaryGlossaryEntryGetCall) (response)
/// * [locations glossaries glossary entries patch projects](ProjectLocationGlossaryGlossaryEntryPatchCall) (request|response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GlossaryEntry {
/// Describes the glossary entry.
pub description: Option<String>,
/// Required. The resource name of the entry. Format: "projects/*/locations/*/glossaries/*/glossaryEntries/*"
pub name: Option<String>,
/// Used for an unidirectional glossary.
#[serde(rename = "termsPair")]
pub terms_pair: Option<GlossaryTermsPair>,
/// Used for an equivalent term sets glossary.
#[serde(rename = "termsSet")]
pub terms_set: Option<GlossaryTermsSet>,
}
impl common::RequestValue for GlossaryEntry {}
impl common::ResponseResult for GlossaryEntry {}
/// Input configuration for glossaries.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GlossaryInputConfig {
/// Required. Google Cloud Storage location of glossary data. File format is determined based on the filename extension. API returns [google.rpc.Code.INVALID_ARGUMENT] for unsupported URI-s and file formats. Wildcards are not allowed. This must be a single file in one of the following formats: For unidirectional glossaries: - TSV/CSV (`.tsv`/`.csv`): Two column file, tab- or comma-separated. The first column is source text. The second column is target text. No headers in this file. The first row contains data and not column names. - TMX (`.tmx`): TMX file with parallel data defining source/target term pairs. For equivalent term sets glossaries: - CSV (`.csv`): Multi-column CSV file defining equivalent glossary terms in multiple languages. See documentation for more information - [glossaries](https://cloud.google.com/translate/docs/advanced/glossary).
#[serde(rename = "gcsSource")]
pub gcs_source: Option<GcsSource>,
}
impl common::Part for GlossaryInputConfig {}
/// Represents a single glossary term
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GlossaryTerm {
/// The language for this glossary term.
#[serde(rename = "languageCode")]
pub language_code: Option<String>,
/// The text for the glossary term.
pub text: Option<String>,
}
impl common::Part for GlossaryTerm {}
/// Represents a single entry for an unidirectional glossary.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GlossaryTermsPair {
/// The source term is the term that will get match in the text,
#[serde(rename = "sourceTerm")]
pub source_term: Option<GlossaryTerm>,
/// The term that will replace the match source term.
#[serde(rename = "targetTerm")]
pub target_term: Option<GlossaryTerm>,
}
impl common::Part for GlossaryTermsPair {}
/// Represents a single entry for an equivalent term set glossary. This is used for equivalent term sets where each term can be replaced by the other terms in the set.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct GlossaryTermsSet {
/// Each term in the set represents a term that can be replaced by the other terms.
pub terms: Option<Vec<GlossaryTerm>>,
}
impl common::Part for GlossaryTermsSet {}
/// The request for importing an AdaptiveMt file along with its sentences.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 adaptive mt datasets import adaptive mt file projects](ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ImportAdaptiveMtFileRequest {
/// Inline file source.
#[serde(rename = "fileInputSource")]
pub file_input_source: Option<FileInputSource>,
/// Google Cloud Storage file source.
#[serde(rename = "gcsInputSource")]
pub gcs_input_source: Option<GcsInputSource>,
}
impl common::RequestValue for ImportAdaptiveMtFileRequest {}
/// The response for importing an AdaptiveMtFile
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 adaptive mt datasets import adaptive mt file projects](ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ImportAdaptiveMtFileResponse {
/// Output only. The Adaptive MT file that was imported.
#[serde(rename = "adaptiveMtFile")]
pub adaptive_mt_file: Option<AdaptiveMtFile>,
}
impl common::ResponseResult for ImportAdaptiveMtFileResponse {}
/// Request message for ImportData.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 datasets import data projects](ProjectLocationDatasetImportDataCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ImportDataRequest {
/// Required. The config for the input content.
#[serde(rename = "inputConfig")]
pub input_config: Option<DatasetInputConfig>,
}
impl common::RequestValue for ImportDataRequest {}
/// Input configuration for BatchTranslateText request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct InputConfig {
/// Required. Google Cloud Storage location for the source input. This can be a single file (for example, `gs://translation-test/input.tsv`) or a wildcard (for example, `gs://translation-test/*`). If a file extension is `.tsv`, it can contain either one or two columns. The first column (optional) is the id of the text request. If the first column is missing, we use the row number (0-based) from the input file as the ID in the output file. The second column is the actual text to be translated. We recommend each row be <= 10K Unicode codepoints, otherwise an error might be returned. Note that the input tsv must be RFC 4180 compliant. You could use https://github.com/Clever/csvlint to check potential formatting errors in your tsv file. csvlint --delimiter='\t' your_input_file.tsv The other supported file extensions are `.txt` or `.html`, which is treated as a single large chunk of text.
#[serde(rename = "gcsSource")]
pub gcs_source: Option<GcsSource>,
/// Optional. Can be "text/plain" or "text/html". For `.tsv`, "text/html" is used if mime_type is missing. For `.html`, this field must be "text/html" or empty. For `.txt`, this field must be "text/plain" or empty.
#[serde(rename = "mimeType")]
pub mime_type: Option<String>,
}
impl common::Part for InputConfig {}
/// An input file.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct InputFile {
/// Google Cloud Storage file source.
#[serde(rename = "gcsSource")]
pub gcs_source: Option<GcsInputSource>,
/// Optional. Usage of the file contents. Options are TRAIN|VALIDATION|TEST, or UNASSIGNED (by default) for auto split.
pub usage: Option<String>,
}
impl common::Part for InputFile {}
/// Used with unidirectional glossaries.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct LanguageCodePair {
/// Required. The ISO-639 language code of the input text, for example, "en-US". Expected to be an exact match for GlossaryTerm.language_code.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// Required. The ISO-639 language code for translation output, for example, "zh-CN". Expected to be an exact match for GlossaryTerm.language_code.
#[serde(rename = "targetLanguageCode")]
pub target_language_code: Option<String>,
}
impl common::Part for LanguageCodePair {}
/// Used with equivalent term set glossaries.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct LanguageCodesSet {
/// The ISO-639 language code(s) for terms defined in the glossary. All entries are unique. The list contains at least two entries. Expected to be an exact match for GlossaryTerm.language_code.
#[serde(rename = "languageCodes")]
pub language_codes: Option<Vec<String>>,
}
impl common::Part for LanguageCodesSet {}
/// A list of AdaptiveMtDatasets.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 adaptive mt datasets list projects](ProjectLocationAdaptiveMtDatasetListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListAdaptiveMtDatasetsResponse {
/// Output only. A list of Adaptive MT datasets.
#[serde(rename = "adaptiveMtDatasets")]
pub adaptive_mt_datasets: Option<Vec<AdaptiveMtDataset>>,
/// Optional. A token to retrieve a page of results. Pass this value in the [ListAdaptiveMtDatasetsRequest.page_token] field in the subsequent call to `ListAdaptiveMtDatasets` method to retrieve the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListAdaptiveMtDatasetsResponse {}
/// The response for listing all AdaptiveMt files under a given dataset.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations adaptive mt datasets adaptive mt files list projects](ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListAdaptiveMtFilesResponse {
/// Output only. The Adaptive MT files.
#[serde(rename = "adaptiveMtFiles")]
pub adaptive_mt_files: Option<Vec<AdaptiveMtFile>>,
/// Optional. A token to retrieve a page of results. Pass this value in the ListAdaptiveMtFilesRequest.page_token field in the subsequent call to `ListAdaptiveMtFiles` method to retrieve the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListAdaptiveMtFilesResponse {}
/// List AdaptiveMt sentences response.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
///
/// * [locations adaptive mt datasets adaptive mt files adaptive mt sentences list projects](ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall) (response)
/// * [locations adaptive mt datasets adaptive mt sentences list projects](ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListAdaptiveMtSentencesResponse {
/// Output only. The list of AdaptiveMtSentences.
#[serde(rename = "adaptiveMtSentences")]
pub adaptive_mt_sentences: Option<Vec<AdaptiveMtSentence>>,
/// Optional.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListAdaptiveMtSentencesResponse {}
/// Response message for ListDatasets.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 datasets list projects](ProjectLocationDatasetListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListDatasetsResponse {
/// The datasets read.
pub datasets: Option<Vec<Dataset>>,
/// A token to retrieve next page of results. Pass this token to the page_token field in the ListDatasetsRequest to obtain the corresponding page.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListDatasetsResponse {}
/// Response message for ListExamples.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 datasets examples list projects](ProjectLocationDatasetExampleListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListExamplesResponse {
/// The sentence pairs.
pub examples: Option<Vec<Example>>,
/// A token to retrieve next page of results. Pass this token to the page_token field in the ListExamplesRequest to obtain the corresponding page.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListExamplesResponse {}
/// Response message for ListGlossaries.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 glossaries list projects](ProjectLocationGlossaryListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListGlossariesResponse {
/// The list of glossaries for a project.
pub glossaries: Option<Vec<Glossary>>,
/// A token to retrieve a page of results. Pass this value in the [ListGlossariesRequest.page_token] field in the subsequent call to `ListGlossaries` method to retrieve the next page of results.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListGlossariesResponse {}
/// Response message for ListGlossaryEntries
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 glossaries glossary entries list projects](ProjectLocationGlossaryGlossaryEntryListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListGlossaryEntriesResponse {
/// Optional. The Glossary Entries
#[serde(rename = "glossaryEntries")]
pub glossary_entries: Option<Vec<GlossaryEntry>>,
/// Optional. A token to retrieve a page of results. Pass this value in the [ListGLossaryEntriesRequest.page_token] field in the subsequent calls.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListGlossaryEntriesResponse {}
/// The response message for Locations.ListLocations.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 list projects](ProjectLocationListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListLocationsResponse {
/// A list of locations that matches the specified filter in the request.
pub locations: Option<Vec<Location>>,
/// The standard List next-page token.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListLocationsResponse {}
/// Response message for ListModels.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 models list projects](ProjectLocationModelListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ListModelsResponse {
/// The models read.
pub models: Option<Vec<Model>>,
/// A token to retrieve next page of results. Pass this token to the page_token field in the ListModelsRequest to obtain the corresponding page.
#[serde(rename = "nextPageToken")]
pub next_page_token: Option<String>,
}
impl common::ResponseResult for ListModelsResponse {}
/// 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*).
///
/// * [locations operations list projects](ProjectLocationOperationListCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::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 common::ResponseResult for ListOperationsResponse {}
/// A resource that represents a Google Cloud location.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 get projects](ProjectLocationGetCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Location {
/// The friendly name for this location, typically a nearby city name. For example, "Tokyo".
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// Cross-service attributes for the location. For example {"cloud.googleapis.com/region": "us-east1"}
pub labels: Option<HashMap<String, String>>,
/// The canonical id for this location. For example: `"us-east1"`.
#[serde(rename = "locationId")]
pub location_id: Option<String>,
/// Service-specific metadata. For example the available capacity at the given location.
pub metadata: Option<HashMap<String, serde_json::Value>>,
/// Resource name for the location, which may vary between implementations. For example: `"projects/example-project/locations/us-east1"`
pub name: Option<String>,
}
impl common::ResponseResult for Location {}
/// A trained translation model.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 models create projects](ProjectLocationModelCreateCall) (request)
/// * [locations models get projects](ProjectLocationModelGetCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Model {
/// Output only. Timestamp when the model resource was created, which is also when the training started.
#[serde(rename = "createTime")]
pub create_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// The dataset from which the model is trained, in form of `projects/{project-number-or-id}/locations/{location_id}/datasets/{dataset_id}`
pub dataset: Option<String>,
/// The name of the model to show in the interface. The name can be up to 32 characters long and can consist only of ASCII Latin letters A-Z and a-z, underscores (_), and ASCII digits 0-9.
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// The resource name of the model, in form of `projects/{project-number-or-id}/locations/{location_id}/models/{model_id}`
pub name: Option<String>,
/// Output only. The BCP-47 language code of the source language.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// Output only. The BCP-47 language code of the target language.
#[serde(rename = "targetLanguageCode")]
pub target_language_code: Option<String>,
/// Output only. Number of examples (sentence pairs) used to test the model.
#[serde(rename = "testExampleCount")]
pub test_example_count: Option<i32>,
/// Output only. Number of examples (sentence pairs) used to train the model.
#[serde(rename = "trainExampleCount")]
pub train_example_count: Option<i32>,
/// Output only. Timestamp when this model was last updated.
#[serde(rename = "updateTime")]
pub update_time: Option<chrono::DateTime<chrono::offset::Utc>>,
/// Output only. Number of examples (sentence pairs) used to validate the model.
#[serde(rename = "validateExampleCount")]
pub validate_example_count: Option<i32>,
}
impl common::RequestValue for Model {}
impl common::ResponseResult for Model {}
/// 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*).
///
/// * [locations datasets create projects](ProjectLocationDatasetCreateCall) (response)
/// * [locations datasets delete projects](ProjectLocationDatasetDeleteCall) (response)
/// * [locations datasets export data projects](ProjectLocationDatasetExportDataCall) (response)
/// * [locations datasets import data projects](ProjectLocationDatasetImportDataCall) (response)
/// * [locations glossaries create projects](ProjectLocationGlossaryCreateCall) (response)
/// * [locations glossaries delete projects](ProjectLocationGlossaryDeleteCall) (response)
/// * [locations glossaries patch projects](ProjectLocationGlossaryPatchCall) (response)
/// * [locations models create projects](ProjectLocationModelCreateCall) (response)
/// * [locations models delete projects](ProjectLocationModelDeleteCall) (response)
/// * [locations operations get projects](ProjectLocationOperationGetCall) (response)
/// * [locations operations wait projects](ProjectLocationOperationWaitCall) (response)
/// * [locations batch translate document projects](ProjectLocationBatchTranslateDocumentCall) (response)
/// * [locations batch translate text projects](ProjectLocationBatchTranslateTextCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Operation {
/// 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 error result of the operation in case of failure or cancellation.
pub error: Option<Status>,
/// 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, serde_json::Value>>,
/// 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>,
/// The normal, successful response of the operation. 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, serde_json::Value>>,
}
impl common::ResponseResult for Operation {}
/// Output configuration for BatchTranslateText request.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct OutputConfig {
/// Google Cloud Storage destination for output content. For every single input file (for example, gs://a/b/c.[extension]), we generate at most 2 * n output files. (n is the # of target_language_codes in the BatchTranslateTextRequest). Output files (tsv) generated are compliant with RFC 4180 except that record delimiters are '\n' instead of '\r\n'. We don't provide any way to change record delimiters. While the input files are being processed, we write/update an index file 'index.csv' under 'output_uri_prefix' (for example, gs://translation-test/index.csv) The index file is generated/updated as new files are being translated. The format is: input_file,target_language_code,translations_file,errors_file, glossary_translations_file,glossary_errors_file input_file is one file we matched using gcs_source.input_uri. target_language_code is provided in the request. translations_file contains the translations. (details provided below) errors_file contains the errors during processing of the file. (details below). Both translations_file and errors_file could be empty strings if we have no content to output. glossary_translations_file and glossary_errors_file are always empty strings if the input_file is tsv. They could also be empty if we have no content to output. Once a row is present in index.csv, the input/output matching never changes. Callers should also expect all the content in input_file are processed and ready to be consumed (that is, no partial output file is written). Since index.csv will be keeping updated during the process, please make sure there is no custom retention policy applied on the output bucket that may avoid file updating. (https://cloud.google.com/storage/docs/bucket-lock#retention-policy) The format of translations_file (for target language code 'trg') is: `gs://translation_test/a_b_c_'trg'_translations.[extension]` If the input file extension is tsv, the output has the following columns: Column 1: ID of the request provided in the input, if it's not provided in the input, then the input row number is used (0-based). Column 2: source sentence. Column 3: translation without applying a glossary. Empty string if there is an error. Column 4 (only present if a glossary is provided in the request): translation after applying the glossary. Empty string if there is an error applying the glossary. Could be same string as column 3 if there is no glossary applied. If input file extension is a txt or html, the translation is directly written to the output file. If glossary is requested, a separate glossary_translations_file has format of `gs://translation_test/a_b_c_'trg'_glossary_translations.[extension]` The format of errors file (for target language code 'trg') is: `gs://translation_test/a_b_c_'trg'_errors.[extension]` If the input file extension is tsv, errors_file contains the following: Column 1: ID of the request provided in the input, if it's not provided in the input, then the input row number is used (0-based). Column 2: source sentence. Column 3: Error detail for the translation. Could be empty. Column 4 (only present if a glossary is provided in the request): Error when applying the glossary. If the input file extension is txt or html, glossary_error_file will be generated that contains error details. glossary_error_file has format of `gs://translation_test/a_b_c_'trg'_glossary_errors.[extension]`
#[serde(rename = "gcsDestination")]
pub gcs_destination: Option<GcsDestination>,
}
impl common::Part for OutputConfig {}
/// A single romanization response.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Romanization {
/// The ISO-639 language code of source text in the initial request, detected automatically, if no source language was passed within the initial request. If the source language was passed, auto-detection of the language does not occur and this field is empty.
#[serde(rename = "detectedLanguageCode")]
pub detected_language_code: Option<String>,
/// Romanized text. If an error occurs during romanization, this field might be excluded from the response.
#[serde(rename = "romanizedText")]
pub romanized_text: Option<String>,
}
impl common::Part for Romanization {}
/// The request message for synchronous romanization.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 romanize text projects](ProjectLocationRomanizeTextCall) (request)
/// * [romanize text projects](ProjectRomanizeTextCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RomanizeTextRequest {
/// Required. The content of the input in string format.
pub contents: Option<Vec<String>>,
/// Optional. The ISO-639 language code of the input text if known, for example, "hi" or "zh". If the source language isn't specified, the API attempts to identify the source language automatically and returns the source language for each content in the response.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
}
impl common::RequestValue for RomanizeTextRequest {}
/// The response message for synchronous romanization.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 romanize text projects](ProjectLocationRomanizeTextCall) (response)
/// * [romanize text projects](ProjectRomanizeTextCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct RomanizeTextResponse {
/// Text romanization responses. This field has the same length as `contents`.
pub romanizations: Option<Vec<Romanization>>,
}
impl common::ResponseResult for RomanizeTextResponse {}
/// 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.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Status {
/// 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, serde_json::Value>>>,
/// 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>,
}
impl common::Part for Status {}
/// A single supported language response corresponds to information related to one supported language.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct SupportedLanguage {
/// Human-readable name of the language localized in the display language specified in the request.
#[serde(rename = "displayName")]
pub display_name: Option<String>,
/// Supported language code, generally consisting of its ISO 639-1 identifier, for example, 'en', 'ja'. In certain cases, ISO-639 codes including language and region identifiers are returned (for example, 'zh-TW' and 'zh-CN').
#[serde(rename = "languageCode")]
pub language_code: Option<String>,
/// Can be used as a source language.
#[serde(rename = "supportSource")]
pub support_source: Option<bool>,
/// Can be used as a target language.
#[serde(rename = "supportTarget")]
pub support_target: Option<bool>,
}
impl common::Part for SupportedLanguage {}
/// The response message for discovering supported languages.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 get supported languages projects](ProjectLocationGetSupportedLanguageCall) (response)
/// * [get supported languages projects](ProjectGetSupportedLanguageCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct SupportedLanguages {
/// A list of supported language responses. This list contains an entry for each language the Translation API supports.
pub languages: Option<Vec<SupportedLanguage>>,
}
impl common::ResponseResult for SupportedLanguages {}
/// A document translation 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*).
///
/// * [locations translate document projects](ProjectLocationTranslateDocumentCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TranslateDocumentRequest {
/// Optional. This flag is to support user customized attribution. If not provided, the default is `Machine Translated by Google`. Customized attribution should follow rules in https://cloud.google.com/translate/attribution#attribution_and_logos
#[serde(rename = "customizedAttribution")]
pub customized_attribution: Option<String>,
/// Required. Input configurations.
#[serde(rename = "documentInputConfig")]
pub document_input_config: Option<DocumentInputConfig>,
/// Optional. Output configurations. Defines if the output file should be stored within Cloud Storage as well as the desired output format. If not provided the translated file will only be returned through a byte-stream and its output mime type will be the same as the input file's mime type.
#[serde(rename = "documentOutputConfig")]
pub document_output_config: Option<DocumentOutputConfig>,
/// Optional. If true, enable auto rotation correction in DVS.
#[serde(rename = "enableRotationCorrection")]
pub enable_rotation_correction: Option<bool>,
/// Optional. If true, use the text removal server to remove the shadow text on background image for native pdf translation. Shadow removal feature can only be enabled when is_translate_native_pdf_only: false && pdf_native_only: false
#[serde(rename = "enableShadowRemovalNativePdf")]
pub enable_shadow_removal_native_pdf: Option<bool>,
/// Optional. Glossary to be applied. The glossary must be within the same region (have the same location-id) as the model, otherwise an INVALID_ARGUMENT (400) error is returned.
#[serde(rename = "glossaryConfig")]
pub glossary_config: Option<TranslateTextGlossaryConfig>,
/// Optional. is_translate_native_pdf_only field for external customers. If true, the page limit of online native pdf translation is 300 and only native pdf pages will be translated.
#[serde(rename = "isTranslateNativePdfOnly")]
pub is_translate_native_pdf_only: Option<bool>,
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
pub labels: Option<HashMap<String, String>>,
/// Optional. The `model` type requested for this translation. The format depends on model type: - AutoML Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, If not provided, the default Google model (NMT) will be used for translation.
pub model: Option<String>,
/// Optional. The ISO-639 language code of the input document if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the API attempts to identify the source language automatically and returns the source language within the response. Source language must be specified if the request contains a glossary or a custom model.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// Required. The ISO-639 language code to use for translation of the input document, set to one of the language codes listed in Language Support.
#[serde(rename = "targetLanguageCode")]
pub target_language_code: Option<String>,
}
impl common::RequestValue for TranslateDocumentRequest {}
/// A translated document response message.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 translate document projects](ProjectLocationTranslateDocumentCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TranslateDocumentResponse {
/// Translated document.
#[serde(rename = "documentTranslation")]
pub document_translation: Option<DocumentTranslation>,
/// The `glossary_config` used for this translation.
#[serde(rename = "glossaryConfig")]
pub glossary_config: Option<TranslateTextGlossaryConfig>,
/// The document's translation output if a glossary is provided in the request. This can be the same as [TranslateDocumentResponse.document_translation] if no glossary terms apply.
#[serde(rename = "glossaryDocumentTranslation")]
pub glossary_document_translation: Option<DocumentTranslation>,
/// Only present when 'model' is present in the request. 'model' is normalized to have a project number. For example: If the 'model' field in TranslateDocumentRequest is: `projects/{project-id}/locations/{location-id}/models/general/nmt` then `model` here would be normalized to `projects/{project-number}/locations/{location-id}/models/general/nmt`.
pub model: Option<String>,
}
impl common::ResponseResult for TranslateDocumentResponse {}
/// Configures which glossary is used for a specific target language and defines options for applying that glossary.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TranslateTextGlossaryConfig {
/// Required. The `glossary` to be applied for this translation. The format depends on the glossary: - User-provided custom glossary: `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`
pub glossary: Option<String>,
/// Optional. Indicates match is case insensitive. The default value is `false` if missing.
#[serde(rename = "ignoreCase")]
pub ignore_case: Option<bool>,
}
impl common::Part for TranslateTextGlossaryConfig {}
/// The request message for synchronous translation.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 translate text projects](ProjectLocationTranslateTextCall) (request)
/// * [translate text projects](ProjectTranslateTextCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TranslateTextRequest {
/// Required. The content of the input in string format. We recommend the total content be less than 30,000 codepoints. The max length of this field is 1024. Use BatchTranslateText for larger text.
pub contents: Option<Vec<String>>,
/// Optional. Glossary to be applied. The glossary must be within the same region (have the same location-id) as the model, otherwise an INVALID_ARGUMENT (400) error is returned.
#[serde(rename = "glossaryConfig")]
pub glossary_config: Option<TranslateTextGlossaryConfig>,
/// Optional. The labels with user-defined metadata for the request. Label keys and values can be no longer than 63 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. Label values are optional. Label keys must start with a letter. See https://cloud.google.com/translate/docs/advanced/labels for more information.
pub labels: Option<HashMap<String, String>>,
/// Optional. The format of the source text, for example, "text/html", "text/plain". If left blank, the MIME type defaults to "text/html".
#[serde(rename = "mimeType")]
pub mime_type: Option<String>,
/// Optional. The `model` type requested for this translation. The format depends on model type: - AutoML Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, For global (non-regionalized) requests, use `location-id` `global`. For example, `projects/{project-number-or-id}/locations/global/models/general/nmt`. If not provided, the default Google model (NMT) will be used
pub model: Option<String>,
/// Optional. The ISO-639 language code of the input text if known, for example, "en-US" or "sr-Latn". Supported language codes are listed in Language Support. If the source language isn't specified, the API attempts to identify the source language automatically and returns the source language within the response.
#[serde(rename = "sourceLanguageCode")]
pub source_language_code: Option<String>,
/// Required. The ISO-639 language code to use for translation of the input text, set to one of the language codes listed in Language Support.
#[serde(rename = "targetLanguageCode")]
pub target_language_code: Option<String>,
/// Optional. Transliteration to be applied.
#[serde(rename = "transliterationConfig")]
pub transliteration_config: Option<TransliterationConfig>,
}
impl common::RequestValue for TranslateTextRequest {}
/// There is no detailed description.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 translate text projects](ProjectLocationTranslateTextCall) (response)
/// * [translate text projects](ProjectTranslateTextCall) (response)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TranslateTextResponse {
/// Text translation responses if a glossary is provided in the request. This can be the same as `translations` if no terms apply. This field has the same length as `contents`.
#[serde(rename = "glossaryTranslations")]
pub glossary_translations: Option<Vec<Translation>>,
/// Text translation responses with no glossary applied. This field has the same length as `contents`.
pub translations: Option<Vec<Translation>>,
}
impl common::ResponseResult for TranslateTextResponse {}
/// A single translation response.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct Translation {
/// The ISO-639 language code of source text in the initial request, detected automatically, if no source language was passed within the initial request. If the source language was passed, auto-detection of the language does not occur and this field is empty.
#[serde(rename = "detectedLanguageCode")]
pub detected_language_code: Option<String>,
/// The `glossary_config` used for this translation.
#[serde(rename = "glossaryConfig")]
pub glossary_config: Option<TranslateTextGlossaryConfig>,
/// Only present when `model` is present in the request. `model` here is normalized to have project number. For example: If the `model` requested in TranslationTextRequest is `projects/{project-id}/locations/{location-id}/models/general/nmt` then `model` here would be normalized to `projects/{project-number}/locations/{location-id}/models/general/nmt`.
pub model: Option<String>,
/// Text translated into the target language. If an error occurs during translation, this field might be excluded from the response.
#[serde(rename = "translatedText")]
pub translated_text: Option<String>,
}
impl common::Part for Translation {}
/// Configures transliteration feature on top of translation.
///
/// This type is not used in any activity, and only used as *part* of another schema.
///
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct TransliterationConfig {
/// If true, source text in romanized form can be translated to the target language.
#[serde(rename = "enableTransliteration")]
pub enable_transliteration: Option<bool>,
}
impl common::Part for TransliterationConfig {}
/// The request message for Operations.WaitOperation.
///
/// # Activities
///
/// This type is used in activities, which are methods you may call on this type or where 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 operations wait projects](ProjectLocationOperationWaitCall) (request)
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[serde_with::serde_as]
#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct WaitOperationRequest {
/// The maximum duration to wait before timing out. If left blank, the wait will be at most the time permitted by the underlying HTTP/RPC protocol. If RPC context deadline is also specified, the shorter one will be used.
#[serde_as(as = "Option<common::serde::duration::Wrapper>")]
pub timeout: Option<chrono::Duration>,
}
impl common::RequestValue for WaitOperationRequest {}
// ###################
// MethodBuilders ###
// #################
/// A builder providing access to all methods supported on *project* resources.
/// It is not used directly, but through the [`Translate`] hub.
///
/// # Example
///
/// Instantiate a resource builder
///
/// ```test_harness,no_run
/// extern crate hyper;
/// extern crate hyper_rustls;
/// extern crate google_translate3 as translate3;
///
/// # async fn dox() {
/// use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// let secret: yup_oauth2::ApplicationSecret = Default::default();
/// let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// secret,
/// yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// ).build().await.unwrap();
///
/// let client = hyper_util::client::legacy::Client::builder(
/// hyper_util::rt::TokioExecutor::new()
/// )
/// .build(
/// hyper_rustls::HttpsConnectorBuilder::new()
/// .with_native_roots()
/// .unwrap()
/// .https_or_http()
/// .enable_http1()
/// .build()
/// );
/// let mut hub = Translate::new(client, auth);
/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
/// // like `detect_language(...)`, `get_supported_languages(...)`, `locations_adaptive_mt_datasets_adaptive_mt_files_adaptive_mt_sentences_list(...)`, `locations_adaptive_mt_datasets_adaptive_mt_files_delete(...)`, `locations_adaptive_mt_datasets_adaptive_mt_files_get(...)`, `locations_adaptive_mt_datasets_adaptive_mt_files_list(...)`, `locations_adaptive_mt_datasets_adaptive_mt_sentences_list(...)`, `locations_adaptive_mt_datasets_create(...)`, `locations_adaptive_mt_datasets_delete(...)`, `locations_adaptive_mt_datasets_get(...)`, `locations_adaptive_mt_datasets_import_adaptive_mt_file(...)`, `locations_adaptive_mt_datasets_list(...)`, `locations_adaptive_mt_translate(...)`, `locations_batch_translate_document(...)`, `locations_batch_translate_text(...)`, `locations_datasets_create(...)`, `locations_datasets_delete(...)`, `locations_datasets_examples_list(...)`, `locations_datasets_export_data(...)`, `locations_datasets_get(...)`, `locations_datasets_import_data(...)`, `locations_datasets_list(...)`, `locations_detect_language(...)`, `locations_get(...)`, `locations_get_supported_languages(...)`, `locations_glossaries_create(...)`, `locations_glossaries_delete(...)`, `locations_glossaries_get(...)`, `locations_glossaries_glossary_entries_create(...)`, `locations_glossaries_glossary_entries_delete(...)`, `locations_glossaries_glossary_entries_get(...)`, `locations_glossaries_glossary_entries_list(...)`, `locations_glossaries_glossary_entries_patch(...)`, `locations_glossaries_list(...)`, `locations_glossaries_patch(...)`, `locations_list(...)`, `locations_models_create(...)`, `locations_models_delete(...)`, `locations_models_get(...)`, `locations_models_list(...)`, `locations_operations_cancel(...)`, `locations_operations_delete(...)`, `locations_operations_get(...)`, `locations_operations_list(...)`, `locations_operations_wait(...)`, `locations_romanize_text(...)`, `locations_translate_document(...)`, `locations_translate_text(...)`, `romanize_text(...)` and `translate_text(...)`
/// // to build up your call.
/// let rb = hub.projects();
/// # }
/// ```
pub struct ProjectMethods<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
}
impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
impl<'a, C> ProjectMethods<'a, C> {
/// Create a builder to help you perform the following task:
///
/// Lists all AdaptiveMtSentences under a given file/dataset.
///
/// # Arguments
///
/// * `parent` - Required. The resource name of the project from which to list the Adaptive MT files. The following format lists all sentences under a file. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}` The following format lists all sentences within a dataset. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
pub fn locations_adaptive_mt_datasets_adaptive_mt_files_adaptive_mt_sentences_list(
&self,
parent: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C> {
ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes an AdaptiveMtFile along with its sentences.
///
/// # Arguments
///
/// * `name` - Required. The resource name of the file to delete, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
pub fn locations_adaptive_mt_datasets_adaptive_mt_files_delete(
&self,
name: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C> {
ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets and AdaptiveMtFile
///
/// # Arguments
///
/// * `name` - Required. The resource name of the file, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
pub fn locations_adaptive_mt_datasets_adaptive_mt_files_get(
&self,
name: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C> {
ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists all AdaptiveMtFiles associated to an AdaptiveMtDataset.
///
/// # Arguments
///
/// * `parent` - Required. The resource name of the project from which to list the Adaptive MT files. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
pub fn locations_adaptive_mt_datasets_adaptive_mt_files_list(
&self,
parent: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C> {
ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists all AdaptiveMtSentences under a given file/dataset.
///
/// # Arguments
///
/// * `parent` - Required. The resource name of the project from which to list the Adaptive MT files. The following format lists all sentences under a file. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}` The following format lists all sentences within a dataset. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
pub fn locations_adaptive_mt_datasets_adaptive_mt_sentences_list(
&self,
parent: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C> {
ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates an Adaptive MT dataset.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Name of the parent project. In form of `projects/{project-number-or-id}/locations/{location-id}`
pub fn locations_adaptive_mt_datasets_create(
&self,
request: AdaptiveMtDataset,
parent: &str,
) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C> {
ProjectLocationAdaptiveMtDatasetCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes an Adaptive MT dataset, including all its entries and associated metadata.
///
/// # Arguments
///
/// * `name` - Required. Name of the dataset. In the form of `projects/{project-number-or-id}/locations/{location-id}/adaptiveMtDatasets/{adaptive-mt-dataset-id}`
pub fn locations_adaptive_mt_datasets_delete(
&self,
name: &str,
) -> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C> {
ProjectLocationAdaptiveMtDatasetDeleteCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets the Adaptive MT dataset.
///
/// # Arguments
///
/// * `name` - Required. Name of the dataset. In the form of `projects/{project-number-or-id}/locations/{location-id}/adaptiveMtDatasets/{adaptive-mt-dataset-id}`
pub fn locations_adaptive_mt_datasets_get(
&self,
name: &str,
) -> ProjectLocationAdaptiveMtDatasetGetCall<'a, C> {
ProjectLocationAdaptiveMtDatasetGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Imports an AdaptiveMtFile and adds all of its sentences into the AdaptiveMtDataset.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The resource name of the file, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}`
pub fn locations_adaptive_mt_datasets_import_adaptive_mt_file(
&self,
request: ImportAdaptiveMtFileRequest,
parent: &str,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C> {
ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists all Adaptive MT datasets for which the caller has read permission.
///
/// # Arguments
///
/// * `parent` - Required. The resource name of the project from which to list the Adaptive MT datasets. `projects/{project-number-or-id}/locations/{location-id}`
pub fn locations_adaptive_mt_datasets_list(
&self,
parent: &str,
) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C> {
ProjectLocationAdaptiveMtDatasetListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists sentence pairs in the dataset.
///
/// # Arguments
///
/// * `parent` - Required. Name of the parent dataset. In form of `projects/{project-number-or-id}/locations/{location-id}/datasets/{dataset-id}`
pub fn locations_datasets_examples_list(
&self,
parent: &str,
) -> ProjectLocationDatasetExampleListCall<'a, C> {
ProjectLocationDatasetExampleListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a Dataset.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The project name.
pub fn locations_datasets_create(
&self,
request: Dataset,
parent: &str,
) -> ProjectLocationDatasetCreateCall<'a, C> {
ProjectLocationDatasetCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes a dataset and all of its contents.
///
/// # Arguments
///
/// * `name` - Required. The name of the dataset to delete.
pub fn locations_datasets_delete(&self, name: &str) -> ProjectLocationDatasetDeleteCall<'a, C> {
ProjectLocationDatasetDeleteCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Exports dataset's data to the provided output location.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `dataset` - Required. Name of the dataset. In form of `projects/{project-number-or-id}/locations/{location-id}/datasets/{dataset-id}`
pub fn locations_datasets_export_data(
&self,
request: ExportDataRequest,
dataset: &str,
) -> ProjectLocationDatasetExportDataCall<'a, C> {
ProjectLocationDatasetExportDataCall {
hub: self.hub,
_request: request,
_dataset: dataset.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets a Dataset.
///
/// # Arguments
///
/// * `name` - Required. The resource name of the dataset to retrieve.
pub fn locations_datasets_get(&self, name: &str) -> ProjectLocationDatasetGetCall<'a, C> {
ProjectLocationDatasetGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Import sentence pairs into translation Dataset.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `dataset` - Required. Name of the dataset. In form of `projects/{project-number-or-id}/locations/{location-id}/datasets/{dataset-id}`
pub fn locations_datasets_import_data(
&self,
request: ImportDataRequest,
dataset: &str,
) -> ProjectLocationDatasetImportDataCall<'a, C> {
ProjectLocationDatasetImportDataCall {
hub: self.hub,
_request: request,
_dataset: dataset.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists datasets.
///
/// # Arguments
///
/// * `parent` - Required. Name of the parent project. In form of `projects/{project-number-or-id}/locations/{location-id}`
pub fn locations_datasets_list(&self, parent: &str) -> ProjectLocationDatasetListCall<'a, C> {
ProjectLocationDatasetListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a glossary entry.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The resource name of the glossary to create the entry under.
pub fn locations_glossaries_glossary_entries_create(
&self,
request: GlossaryEntry,
parent: &str,
) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C> {
ProjectLocationGlossaryGlossaryEntryCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes a single entry from the glossary
///
/// # Arguments
///
/// * `name` - Required. The resource name of the glossary entry to delete
pub fn locations_glossaries_glossary_entries_delete(
&self,
name: &str,
) -> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C> {
ProjectLocationGlossaryGlossaryEntryDeleteCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets a single glossary entry by the given id.
///
/// # Arguments
///
/// * `name` - Required. The resource name of the glossary entry to get
pub fn locations_glossaries_glossary_entries_get(
&self,
name: &str,
) -> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C> {
ProjectLocationGlossaryGlossaryEntryGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// List the entries for the glossary.
///
/// # Arguments
///
/// * `parent` - Required. The parent glossary resource name for listing the glossary's entries.
pub fn locations_glossaries_glossary_entries_list(
&self,
parent: &str,
) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C> {
ProjectLocationGlossaryGlossaryEntryListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates a glossary entry.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. The resource name of the entry. Format: "projects/*/locations/*/glossaries/*/glossaryEntries/*"
pub fn locations_glossaries_glossary_entries_patch(
&self,
request: GlossaryEntry,
name: &str,
) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C> {
ProjectLocationGlossaryGlossaryEntryPatchCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a glossary and returns the long-running operation. Returns NOT_FOUND, if the project doesn't exist.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The project name.
pub fn locations_glossaries_create(
&self,
request: Glossary,
parent: &str,
) -> ProjectLocationGlossaryCreateCall<'a, C> {
ProjectLocationGlossaryCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT_FOUND, if the glossary doesn't exist.
///
/// # Arguments
///
/// * `name` - Required. The name of the glossary to delete.
pub fn locations_glossaries_delete(
&self,
name: &str,
) -> ProjectLocationGlossaryDeleteCall<'a, C> {
ProjectLocationGlossaryDeleteCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist.
///
/// # Arguments
///
/// * `name` - Required. The name of the glossary to retrieve.
pub fn locations_glossaries_get(&self, name: &str) -> ProjectLocationGlossaryGetCall<'a, C> {
ProjectLocationGlossaryGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't exist.
///
/// # Arguments
///
/// * `parent` - Required. The name of the project from which to list all of the glossaries.
pub fn locations_glossaries_list(
&self,
parent: &str,
) -> ProjectLocationGlossaryListCall<'a, C> {
ProjectLocationGlossaryListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Updates a glossary. A LRO is used since the update can be async if the glossary's entry file is updated.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - Required. The resource name of the glossary. Glossary names have the form `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-id}`.
pub fn locations_glossaries_patch(
&self,
request: Glossary,
name: &str,
) -> ProjectLocationGlossaryPatchCall<'a, C> {
ProjectLocationGlossaryPatchCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_update_mask: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Creates a Model.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. The project name, in form of `projects/{project}/locations/{location}`
pub fn locations_models_create(
&self,
request: Model,
parent: &str,
) -> ProjectLocationModelCreateCall<'a, C> {
ProjectLocationModelCreateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Deletes a model.
///
/// # Arguments
///
/// * `name` - Required. The name of the model to delete.
pub fn locations_models_delete(&self, name: &str) -> ProjectLocationModelDeleteCall<'a, C> {
ProjectLocationModelDeleteCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets a model.
///
/// # Arguments
///
/// * `name` - Required. The resource name of the model to retrieve.
pub fn locations_models_get(&self, name: &str) -> ProjectLocationModelGetCall<'a, C> {
ProjectLocationModelGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists models.
///
/// # Arguments
///
/// * `parent` - Required. Name of the parent project. In form of `projects/{project-number-or-id}/locations/{location-id}`
pub fn locations_models_list(&self, parent: &str) -> ProjectLocationModelListCall<'a, C> {
ProjectLocationModelListCall {
hub: self.hub,
_parent: parent.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: 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 locations_operations_cancel(
&self,
request: CancelOperationRequest,
name: &str,
) -> ProjectLocationOperationCancelCall<'a, C> {
ProjectLocationOperationCancelCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: 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 locations_operations_delete(
&self,
name: &str,
) -> ProjectLocationOperationDeleteCall<'a, C> {
ProjectLocationOperationDeleteCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: 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> {
ProjectLocationOperationGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`.
///
/// # Arguments
///
/// * `name` - The name of the operation's parent resource.
pub fn locations_operations_list(&self, name: &str) -> ProjectLocationOperationListCall<'a, C> {
ProjectLocationOperationListCall {
hub: self.hub,
_name: name.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Waits until the specified long-running operation is done or reaches at most a specified timeout, returning the latest state. If the operation is already done, the latest state is immediately returned. If the timeout specified is greater than the default HTTP/RPC timeout, the HTTP/RPC timeout is used. If the server does not support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Note that this method is on a best-effort basis. It may return the latest state before the specified timeout (including immediately), meaning even an immediate response is no guarantee that the operation is done.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `name` - The name of the operation resource to wait on.
pub fn locations_operations_wait(
&self,
request: WaitOperationRequest,
name: &str,
) -> ProjectLocationOperationWaitCall<'a, C> {
ProjectLocationOperationWaitCall {
hub: self.hub,
_request: request,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Translate text using Adaptive MT.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Location to make a regional call. Format: `projects/{project-number-or-id}/locations/{location-id}`.
pub fn locations_adaptive_mt_translate(
&self,
request: AdaptiveMtTranslateRequest,
parent: &str,
) -> ProjectLocationAdaptiveMtTranslateCall<'a, C> {
ProjectLocationAdaptiveMtTranslateCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Translates a large volume of document in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Location to make a regional call. Format: `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported for batch translation. Only AutoML Translation models or glossaries within the same region (have the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn locations_batch_translate_document(
&self,
request: BatchTranslateDocumentRequest,
parent: &str,
) -> ProjectLocationBatchTranslateDocumentCall<'a, C> {
ProjectLocationBatchTranslateDocumentCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Translates a large volume of text in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported for batch translation. Only AutoML Translation models or glossaries within the same region (have the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn locations_batch_translate_text(
&self,
request: BatchTranslateTextRequest,
parent: &str,
) -> ProjectLocationBatchTranslateTextCall<'a, C> {
ProjectLocationBatchTranslateTextCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Detects the language of text within a request.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Only models within the same region (has same location-id) can be used. Otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn locations_detect_language(
&self,
request: DetectLanguageRequest,
parent: &str,
) -> ProjectLocationDetectLanguageCall<'a, C> {
ProjectLocationDetectLanguageCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Gets information about a location.
///
/// # Arguments
///
/// * `name` - Resource name for the location.
pub fn locations_get(&self, name: &str) -> ProjectLocationGetCall<'a, C> {
ProjectLocationGetCall {
hub: self.hub,
_name: name.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns a list of supported languages for translation.
///
/// # Arguments
///
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for AutoML models. Only models within the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn locations_get_supported_languages(
&self,
parent: &str,
) -> ProjectLocationGetSupportedLanguageCall<'a, C> {
ProjectLocationGetSupportedLanguageCall {
hub: self.hub,
_parent: parent.to_string(),
_model: Default::default(),
_display_language_code: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Lists information about the supported locations for this service.
///
/// # Arguments
///
/// * `name` - The resource that owns the locations collection, if applicable.
pub fn locations_list(&self, name: &str) -> ProjectLocationListCall<'a, C> {
ProjectLocationListCall {
hub: self.hub,
_name: name.to_string(),
_page_token: Default::default(),
_page_size: Default::default(),
_filter: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Romanize input text written in non-Latin scripts to Latin text.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`.
pub fn locations_romanize_text(
&self,
request: RomanizeTextRequest,
parent: &str,
) -> ProjectLocationRomanizeTextCall<'a, C> {
ProjectLocationRomanizeTextCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Translates documents in synchronous mode.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Location to make a regional call. Format: `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or custom glossaries. Models and glossaries must be within the same region (have the same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn locations_translate_document(
&self,
request: TranslateDocumentRequest,
parent: &str,
) -> ProjectLocationTranslateDocumentCall<'a, C> {
ProjectLocationTranslateDocumentCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Translates input text and returns translated text.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or custom glossaries. Models and glossaries must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn locations_translate_text(
&self,
request: TranslateTextRequest,
parent: &str,
) -> ProjectLocationTranslateTextCall<'a, C> {
ProjectLocationTranslateTextCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Detects the language of text within a request.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Only models within the same region (has same location-id) can be used. Otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn detect_language(
&self,
request: DetectLanguageRequest,
parent: &str,
) -> ProjectDetectLanguageCall<'a, C> {
ProjectDetectLanguageCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Returns a list of supported languages for translation.
///
/// # Arguments
///
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for AutoML models. Only models within the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn get_supported_languages(&self, parent: &str) -> ProjectGetSupportedLanguageCall<'a, C> {
ProjectGetSupportedLanguageCall {
hub: self.hub,
_parent: parent.to_string(),
_model: Default::default(),
_display_language_code: Default::default(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Romanize input text written in non-Latin scripts to Latin text.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`.
pub fn romanize_text(
&self,
request: RomanizeTextRequest,
parent: &str,
) -> ProjectRomanizeTextCall<'a, C> {
ProjectRomanizeTextCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
/// Create a builder to help you perform the following task:
///
/// Translates input text and returns translated text.
///
/// # Arguments
///
/// * `request` - No description provided.
/// * `parent` - Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or custom glossaries. Models and glossaries must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
pub fn translate_text(
&self,
request: TranslateTextRequest,
parent: &str,
) -> ProjectTranslateTextCall<'a, C> {
ProjectTranslateTextCall {
hub: self.hub,
_request: request,
_parent: parent.to_string(),
_delegate: Default::default(),
_additional_params: Default::default(),
_scopes: Default::default(),
}
}
}
// ###################
// CallBuilders ###
// #################
/// Lists all AdaptiveMtSentences under a given file/dataset.
///
/// A builder for the *locations.adaptiveMtDatasets.adaptiveMtFiles.adaptiveMtSentences.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_adaptive_mt_files_adaptive_mt_sentences_list("parent")
/// .page_token("voluptua.")
/// .page_size(-27)
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder
for ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C>
{
}
impl<'a, C> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(
mut self,
) -> common::Result<(common::Response, ListAdaptiveMtSentencesResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo { id: "translate.projects.locations.adaptiveMtDatasets.adaptiveMtFiles.adaptiveMtSentences.list",
http_method: hyper::Method::GET });
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/adaptiveMtSentences";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the project from which to list the Adaptive MT files. The following format lists all sentences under a file. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}` The following format lists all sentences within a dataset. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
///
/// 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,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// A token identifying a page of results the server should return. Typically, this is the value of ListAdaptiveMtSentencesRequest.next_page_token returned from the previous call to `ListTranslationMemories` method. The first page is returned if `page_token` is empty or missing.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(
mut self,
new_value: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
///
/// Sets the *page size* query property to the given value.
pub fn page_size(
mut self,
new_value: i32,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(
mut self,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileAdaptiveMtSentenceListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes an AdaptiveMtFile along with its sentences.
///
/// A builder for the *locations.adaptiveMtDatasets.adaptiveMtFiles.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_adaptive_mt_files_delete("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder
for ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C>
{
}
impl<'a, C> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.adaptiveMtFiles.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the file to delete, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
///
/// 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,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(
mut self,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets and AdaptiveMtFile
///
/// A builder for the *locations.adaptiveMtDatasets.adaptiveMtFiles.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_adaptive_mt_files_get("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C> {}
impl<'a, C> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AdaptiveMtFile)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.adaptiveMtFiles.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the file, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}`
///
/// 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,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists all AdaptiveMtFiles associated to an AdaptiveMtDataset.
///
/// A builder for the *locations.adaptiveMtDatasets.adaptiveMtFiles.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_adaptive_mt_files_list("parent")
/// .page_token("takimata")
/// .page_size(-52)
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C> {}
impl<'a, C> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListAdaptiveMtFilesResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.adaptiveMtFiles.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/adaptiveMtFiles";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the project from which to list the Adaptive MT files. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
///
/// 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,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. A token identifying a page of results the server should return. Typically, this is the value of ListAdaptiveMtFilesResponse.next_page_token returned from the previous call to `ListAdaptiveMtFiles` method. The first page is returned if `page_token`is empty or missing.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(
mut self,
new_value: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(
mut self,
new_value: i32,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtFileListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists all AdaptiveMtSentences under a given file/dataset.
///
/// A builder for the *locations.adaptiveMtDatasets.adaptiveMtSentences.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_adaptive_mt_sentences_list("parent")
/// .page_token("ipsum")
/// .page_size(-62)
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder
for ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C>
{
}
impl<'a, C> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(
mut self,
) -> common::Result<(common::Response, ListAdaptiveMtSentencesResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.adaptiveMtSentences.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/adaptiveMtSentences";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the project from which to list the Adaptive MT files. The following format lists all sentences under a file. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}/adaptiveMtFiles/{file}` The following format lists all sentences within a dataset. `projects/{project}/locations/{location}/adaptiveMtDatasets/{dataset}`
///
/// 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,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// A token identifying a page of results the server should return. Typically, this is the value of ListAdaptiveMtSentencesRequest.next_page_token returned from the previous call to `ListTranslationMemories` method. The first page is returned if `page_token` is empty or missing.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(
mut self,
new_value: &str,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
///
/// Sets the *page size* query property to the given value.
pub fn page_size(
mut self,
new_value: i32,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(
mut self,
) -> ProjectLocationAdaptiveMtDatasetAdaptiveMtSentenceListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates an Adaptive MT dataset.
///
/// A builder for the *locations.adaptiveMtDatasets.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 google_translate3 as translate3;
/// use translate3::api::AdaptiveMtDataset;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = AdaptiveMtDataset::default();
///
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_create(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetCreateCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: AdaptiveMtDataset,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationAdaptiveMtDatasetCreateCall<'a, C> {}
impl<'a, C> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AdaptiveMtDataset)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.create",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/adaptiveMtDatasets";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: AdaptiveMtDataset,
) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C> {
self._request = new_value;
self
}
/// Required. Name of the parent project. In form of `projects/{project-number-or-id}/locations/{location-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) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationAdaptiveMtDatasetCreateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes an Adaptive MT dataset, including all its entries and associated metadata.
///
/// A builder for the *locations.adaptiveMtDatasets.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_delete("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C> {}
impl<'a, C> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. Name of the dataset. In the form of `projects/{project-number-or-id}/locations/{location-id}/adaptiveMtDatasets/{adaptive-mt-dataset-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) -> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationAdaptiveMtDatasetDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets the Adaptive MT dataset.
///
/// A builder for the *locations.adaptiveMtDatasets.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_get("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationAdaptiveMtDatasetGetCall<'a, C> {}
impl<'a, C> ProjectLocationAdaptiveMtDatasetGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AdaptiveMtDataset)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. Name of the dataset. In the form of `projects/{project-number-or-id}/locations/{location-id}/adaptiveMtDatasets/{adaptive-mt-dataset-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) -> ProjectLocationAdaptiveMtDatasetGetCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationAdaptiveMtDatasetGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationAdaptiveMtDatasetGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationAdaptiveMtDatasetGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationAdaptiveMtDatasetGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Imports an AdaptiveMtFile and adds all of its sentences into the AdaptiveMtDataset.
///
/// A builder for the *locations.adaptiveMtDatasets.importAdaptiveMtFile* 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 google_translate3 as translate3;
/// use translate3::api::ImportAdaptiveMtFileRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ImportAdaptiveMtFileRequest::default();
///
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_import_adaptive_mt_file(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: ImportAdaptiveMtFileRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder
for ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C>
{
}
impl<'a, C> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(
mut self,
) -> common::Result<(common::Response, ImportAdaptiveMtFileResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.importAdaptiveMtFile",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:importAdaptiveMtFile";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ImportAdaptiveMtFileRequest,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C> {
self._request = new_value;
self
}
/// Required. The resource name of the file, in form of `projects/{project-number-or-id}/locations/{location_id}/adaptiveMtDatasets/{dataset}`
///
/// 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,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(
mut self,
) -> ProjectLocationAdaptiveMtDatasetImportAdaptiveMtFileCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists all Adaptive MT datasets for which the caller has read permission.
///
/// A builder for the *locations.adaptiveMtDatasets.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_adaptive_mt_datasets_list("parent")
/// .page_token("ipsum")
/// .page_size(-88)
/// .filter("amet")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtDatasetListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationAdaptiveMtDatasetListCall<'a, C> {}
impl<'a, C> ProjectLocationAdaptiveMtDatasetListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(
mut self,
) -> common::Result<(common::Response, ListAdaptiveMtDatasetsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtDatasets.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/adaptiveMtDatasets";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the project from which to list the Adaptive MT datasets. `projects/{project-number-or-id}/locations/{location-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) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. A token identifying a page of results the server should return. Typically, this is the value of ListAdaptiveMtDatasetsResponse.next_page_token returned from the previous call to `ListAdaptiveMtDatasets` method. The first page is returned if `page_token`is empty or missing.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(
mut self,
new_value: &str,
) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. Requested page size. The server may return fewer results than requested. If unspecified, the server picks an appropriate default.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// Optional. An expression for filtering the results of the request. Filter is not supported yet.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationAdaptiveMtDatasetListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists sentence pairs in the dataset.
///
/// A builder for the *locations.datasets.examples.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_datasets_examples_list("parent")
/// .page_token("ipsum")
/// .page_size(-93)
/// .filter("ut")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDatasetExampleListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDatasetExampleListCall<'a, C> {}
impl<'a, C> ProjectLocationDatasetExampleListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListExamplesResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.datasets.examples.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/examples";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. Name of the parent dataset. In form of `projects/{project-number-or-id}/locations/{location-id}/datasets/{dataset-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) -> ProjectLocationDatasetExampleListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. A token identifying a page of results for the server to return. Typically obtained from next_page_token field in the response of a ListExamples call.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationDatasetExampleListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. Requested page size. The server can return fewer results than requested.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationDatasetExampleListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// Optional. An expression for filtering the examples that will be returned. Example filter: * `usage=TRAIN`
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ProjectLocationDatasetExampleListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDatasetExampleListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDatasetExampleListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDatasetExampleListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDatasetExampleListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDatasetExampleListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a Dataset.
///
/// A builder for the *locations.datasets.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 google_translate3 as translate3;
/// use translate3::api::Dataset;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Dataset::default();
///
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().locations_datasets_create(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDatasetCreateCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: Dataset,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDatasetCreateCall<'a, C> {}
impl<'a, C> ProjectLocationDatasetCreateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.datasets.create",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/datasets";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Dataset) -> ProjectLocationDatasetCreateCall<'a, C> {
self._request = new_value;
self
}
/// Required. The project name.
///
/// 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) -> ProjectLocationDatasetCreateCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDatasetCreateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDatasetCreateCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDatasetCreateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDatasetCreateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDatasetCreateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes a dataset and all of its contents.
///
/// A builder for the *locations.datasets.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_datasets_delete("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDatasetDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDatasetDeleteCall<'a, C> {}
impl<'a, C> ProjectLocationDatasetDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.datasets.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The name of the dataset to delete.
///
/// 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) -> ProjectLocationDatasetDeleteCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDatasetDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDatasetDeleteCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDatasetDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDatasetDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDatasetDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Exports dataset's data to the provided output location.
///
/// A builder for the *locations.datasets.exportData* 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 google_translate3 as translate3;
/// use translate3::api::ExportDataRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ExportDataRequest::default();
///
/// // You can configure optional parameters by calling 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_datasets_export_data(req, "dataset")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDatasetExportDataCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: ExportDataRequest,
_dataset: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDatasetExportDataCall<'a, C> {}
impl<'a, C> ProjectLocationDatasetExportDataCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.datasets.exportData",
http_method: hyper::Method::POST,
});
for &field in ["alt", "dataset"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("dataset", self._dataset);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+dataset}:exportData";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+dataset}", "dataset")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["dataset"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ExportDataRequest,
) -> ProjectLocationDatasetExportDataCall<'a, C> {
self._request = new_value;
self
}
/// Required. Name of the dataset. In form of `projects/{project-number-or-id}/locations/{location-id}/datasets/{dataset-id}`
///
/// Sets the *dataset* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn dataset(mut self, new_value: &str) -> ProjectLocationDatasetExportDataCall<'a, C> {
self._dataset = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDatasetExportDataCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDatasetExportDataCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDatasetExportDataCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDatasetExportDataCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDatasetExportDataCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets a Dataset.
///
/// A builder for the *locations.datasets.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_datasets_get("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDatasetGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDatasetGetCall<'a, C> {}
impl<'a, C> ProjectLocationDatasetGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Dataset)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.datasets.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the dataset to retrieve.
///
/// 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) -> ProjectLocationDatasetGetCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDatasetGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDatasetGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDatasetGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDatasetGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDatasetGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Import sentence pairs into translation Dataset.
///
/// A builder for the *locations.datasets.importData* 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 google_translate3 as translate3;
/// use translate3::api::ImportDataRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = ImportDataRequest::default();
///
/// // You can configure optional parameters by calling 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_datasets_import_data(req, "dataset")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDatasetImportDataCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: ImportDataRequest,
_dataset: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDatasetImportDataCall<'a, C> {}
impl<'a, C> ProjectLocationDatasetImportDataCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.datasets.importData",
http_method: hyper::Method::POST,
});
for &field in ["alt", "dataset"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("dataset", self._dataset);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+dataset}:importData";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+dataset}", "dataset")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["dataset"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: ImportDataRequest,
) -> ProjectLocationDatasetImportDataCall<'a, C> {
self._request = new_value;
self
}
/// Required. Name of the dataset. In form of `projects/{project-number-or-id}/locations/{location-id}/datasets/{dataset-id}`
///
/// Sets the *dataset* path property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn dataset(mut self, new_value: &str) -> ProjectLocationDatasetImportDataCall<'a, C> {
self._dataset = new_value.to_string();
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDatasetImportDataCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDatasetImportDataCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDatasetImportDataCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDatasetImportDataCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDatasetImportDataCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists datasets.
///
/// A builder for the *locations.datasets.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_datasets_list("parent")
/// .page_token("gubergren")
/// .page_size(-17)
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDatasetListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDatasetListCall<'a, C> {}
impl<'a, C> ProjectLocationDatasetListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListDatasetsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.datasets.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/datasets";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. Name of the parent project. In form of `projects/{project-number-or-id}/locations/{location-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) -> ProjectLocationDatasetListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. A token identifying a page of results for the server to return. Typically obtained from next_page_token field in the response of a ListDatasets call.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationDatasetListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. Requested page size. The server can return fewer results than requested.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationDatasetListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDatasetListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDatasetListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDatasetListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDatasetListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDatasetListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a glossary entry.
///
/// A builder for the *locations.glossaries.glossaryEntries.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 google_translate3 as translate3;
/// use translate3::api::GlossaryEntry;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GlossaryEntry::default();
///
/// // You can configure optional parameters by calling 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_glossaries_glossary_entries_create(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: GlossaryEntry,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GlossaryEntry)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.glossaryEntries.create",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/glossaryEntries";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: GlossaryEntry,
) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C> {
self._request = new_value;
self
}
/// Required. The resource name of the glossary to create the entry under.
///
/// 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,
) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryGlossaryEntryCreateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes a single entry from the glossary
///
/// A builder for the *locations.glossaries.glossaryEntries.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_glossaries_glossary_entries_delete("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.glossaryEntries.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the glossary entry to delete
///
/// 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,
) -> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryGlossaryEntryDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets a single glossary entry by the given id.
///
/// A builder for the *locations.glossaries.glossaryEntries.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_glossaries_glossary_entries_get("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryGlossaryEntryGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryGlossaryEntryGetCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GlossaryEntry)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.glossaryEntries.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the glossary entry to get
///
/// 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) -> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryGlossaryEntryGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// List the entries for the glossary.
///
/// A builder for the *locations.glossaries.glossaryEntries.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_glossaries_glossary_entries_list("parent")
/// .page_token("sed")
/// .page_size(-70)
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryGlossaryEntryListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryGlossaryEntryListCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryGlossaryEntryListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListGlossaryEntriesResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.glossaryEntries.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/glossaryEntries";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The parent glossary resource name for listing the glossary's entries.
///
/// 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,
) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. A token identifying a page of results the server should return. Typically, this is the value of [ListGlossaryEntriesResponse.next_page_token] returned from the previous call. The first page is returned if `page_token`is empty or missing.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(
mut self,
new_value: &str,
) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. Requested page size. The server may return fewer glossary entries than requested. If unspecified, the server picks an appropriate default.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(
mut self,
new_value: i32,
) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryGlossaryEntryListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates a glossary entry.
///
/// A builder for the *locations.glossaries.glossaryEntries.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 google_translate3 as translate3;
/// use translate3::api::GlossaryEntry;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = GlossaryEntry::default();
///
/// // You can configure optional parameters by calling 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_glossaries_glossary_entries_patch(req, "name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: GlossaryEntry,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, GlossaryEntry)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.glossaryEntries.patch",
http_method: hyper::Method::PATCH,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: GlossaryEntry,
) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C> {
self._request = new_value;
self
}
/// Required. The resource name of the entry. Format: "projects/*/locations/*/glossaries/*/glossaryEntries/*"
///
/// 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) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(
mut self,
name: T,
value: T,
) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(
mut self,
scope: St,
) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryGlossaryEntryPatchCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a glossary and returns the long-running operation. Returns NOT_FOUND, if the project doesn't exist.
///
/// A builder for the *locations.glossaries.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 google_translate3 as translate3;
/// use translate3::api::Glossary;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Glossary::default();
///
/// // You can configure optional parameters by calling 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_glossaries_create(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryCreateCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: Glossary,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryCreateCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryCreateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.create",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/glossaries";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Glossary) -> ProjectLocationGlossaryCreateCall<'a, C> {
self._request = new_value;
self
}
/// Required. The project name.
///
/// 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) -> ProjectLocationGlossaryCreateCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryCreateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationGlossaryCreateCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGlossaryCreateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationGlossaryCreateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryCreateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes a glossary, or cancels glossary construction if the glossary isn't created yet. Returns NOT_FOUND, if the glossary doesn't exist.
///
/// A builder for the *locations.glossaries.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_glossaries_delete("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryDeleteCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The name of the glossary to delete.
///
/// 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) -> ProjectLocationGlossaryDeleteCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationGlossaryDeleteCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGlossaryDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationGlossaryDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets a glossary. Returns NOT_FOUND, if the glossary doesn't exist.
///
/// A builder for the *locations.glossaries.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_glossaries_get("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryGetCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Glossary)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The name of the glossary to retrieve.
///
/// 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) -> ProjectLocationGlossaryGetCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationGlossaryGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGlossaryGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationGlossaryGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists glossaries in a project. Returns NOT_FOUND, if the project doesn't exist.
///
/// A builder for the *locations.glossaries.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_glossaries_list("parent")
/// .page_token("sed")
/// .page_size(-24)
/// .filter("et")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryListCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListGlossariesResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/glossaries";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The name of the project from which to list all of the glossaries.
///
/// 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) -> ProjectLocationGlossaryListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. A token identifying a page of results the server should return. Typically, this is the value of [ListGlossariesResponse.next_page_token] returned from the previous call to `ListGlossaries` method. The first page is returned if `page_token`is empty or missing.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationGlossaryListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. Requested page size. The server may return fewer glossaries than requested. If unspecified, the server picks an appropriate default.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationGlossaryListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// Optional. Filter specifying constraints of a list operation. Specify the constraint by the format of "key=value", where key must be "src" or "tgt", and the value must be a valid language code. For multiple restrictions, concatenate them by "AND" (uppercase only), such as: "src=en-US AND tgt=zh-CN". Notice that the exact match is used here, which means using 'en-US' and 'en' can lead to different results, which depends on the language code you used when you create the glossary. For the unidirectional glossaries, the "src" and "tgt" add restrictions on the source and target language code separately. For the equivalent term set glossaries, the "src" and/or "tgt" add restrictions on the term set. For example: "src=en-US AND tgt=zh-CN" will only pick the unidirectional glossaries which exactly match the source language code as "en-US" and the target language code "zh-CN", but all equivalent term set glossaries which contain "en-US" and "zh-CN" in their language set will be picked. If missing, no filtering is performed.
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ProjectLocationGlossaryListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationGlossaryListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGlossaryListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationGlossaryListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Updates a glossary. A LRO is used since the update can be async if the glossary's entry file is updated.
///
/// A builder for the *locations.glossaries.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 google_translate3 as translate3;
/// use translate3::api::Glossary;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Glossary::default();
///
/// // You can configure optional parameters by calling 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_glossaries_patch(req, "name")
/// .update_mask(FieldMask::new::<&str>(&[]))
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGlossaryPatchCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: Glossary,
_name: String,
_update_mask: Option<common::FieldMask>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGlossaryPatchCall<'a, C> {}
impl<'a, C> ProjectLocationGlossaryPatchCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.glossaries.patch",
http_method: hyper::Method::PATCH,
});
for &field in ["alt", "name", "updateMask"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("name", self._name);
if let Some(value) = self._update_mask.as_ref() {
params.push("updateMask", value.to_string());
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::PATCH)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Glossary) -> ProjectLocationGlossaryPatchCall<'a, C> {
self._request = new_value;
self
}
/// Required. The resource name of the glossary. Glossary names have the form `projects/{project-number-or-id}/locations/{location-id}/glossaries/{glossary-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) -> ProjectLocationGlossaryPatchCall<'a, C> {
self._name = new_value.to_string();
self
}
/// The list of fields to be updated. Currently only `display_name` and 'input_config'
///
/// Sets the *update mask* query property to the given value.
pub fn update_mask(
mut self,
new_value: common::FieldMask,
) -> ProjectLocationGlossaryPatchCall<'a, C> {
self._update_mask = 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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGlossaryPatchCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationGlossaryPatchCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGlossaryPatchCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationGlossaryPatchCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGlossaryPatchCall<'a, C> {
self._scopes.clear();
self
}
}
/// Creates a Model.
///
/// A builder for the *locations.models.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 google_translate3 as translate3;
/// use translate3::api::Model;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = Model::default();
///
/// // You can configure optional parameters by calling 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_models_create(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationModelCreateCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: Model,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationModelCreateCall<'a, C> {}
impl<'a, C> ProjectLocationModelCreateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.models.create",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/models";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: Model) -> ProjectLocationModelCreateCall<'a, C> {
self._request = new_value;
self
}
/// Required. The project name, in form of `projects/{project}/locations/{location}`
///
/// 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) -> ProjectLocationModelCreateCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationModelCreateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationModelCreateCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationModelCreateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationModelCreateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationModelCreateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Deletes a model.
///
/// A builder for the *locations.models.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_models_delete("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationModelDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationModelDeleteCall<'a, C> {}
impl<'a, C> ProjectLocationModelDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.models.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The name of the model to delete.
///
/// 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) -> ProjectLocationModelDeleteCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationModelDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationModelDeleteCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationModelDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationModelDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationModelDeleteCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets a model.
///
/// A builder for the *locations.models.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_models_get("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationModelGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationModelGetCall<'a, C> {}
impl<'a, C> ProjectLocationModelGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Model)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.models.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. The resource name of the model to retrieve.
///
/// 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) -> ProjectLocationModelGetCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationModelGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationModelGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationModelGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationModelGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationModelGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists models.
///
/// A builder for the *locations.models.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_models_list("parent")
/// .page_token("et")
/// .page_size(-28)
/// .filter("amet.")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationModelListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationModelListCall<'a, C> {}
impl<'a, C> ProjectLocationModelListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListModelsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.models.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/models";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. Name of the parent project. In form of `projects/{project-number-or-id}/locations/{location-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) -> ProjectLocationModelListCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. A token identifying a page of results for the server to return. Typically obtained from next_page_token field in the response of a ListModels call.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationModelListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// Optional. Requested page size. The server can return fewer results than requested.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationModelListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// Optional. An expression for filtering the models that will be returned. Supported filter: `dataset_id=${dataset_id}`
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ProjectLocationModelListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationModelListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationModelListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationModelListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationModelListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationModelListCall<'a, C> {
self._scopes.clear();
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 *locations.operations.cancel* 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 google_translate3 as translate3;
/// use translate3::api::CancelOperationRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the 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.projects().locations_operations_cancel(req, "name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationOperationCancelCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: CancelOperationRequest,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationOperationCancelCall<'a, C> {}
impl<'a, C> ProjectLocationOperationCancelCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.operations.cancel",
http_method: hyper::Method::POST,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}:cancel";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though 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,
) -> ProjectLocationOperationCancelCall<'a, C> {
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) -> ProjectLocationOperationCancelCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationOperationCancelCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationOperationCancelCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationOperationCancelCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationOperationCancelCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationOperationCancelCall<'a, C> {
self._scopes.clear();
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 *locations.operations.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_delete("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationOperationDeleteCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationOperationDeleteCall<'a, C> {}
impl<'a, C> ProjectLocationOperationDeleteCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Empty)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.operations.delete",
http_method: hyper::Method::DELETE,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::DELETE)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// 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) -> ProjectLocationOperationDeleteCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationOperationDeleteCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationOperationDeleteCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationOperationDeleteCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationOperationDeleteCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationOperationDeleteCall<'a, C> {
self._scopes.clear();
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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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().await;
/// # }
/// ```
pub struct ProjectLocationOperationGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationOperationGetCall<'a, C> {}
impl<'a, C> ProjectLocationOperationGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.operations.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// 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> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationOperationGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationOperationGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationOperationGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationOperationGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationOperationGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists operations that match the specified filter in the request. If the server doesn't support this method, it returns `UNIMPLEMENTED`.
///
/// A builder for the *locations.operations.list* method supported by a *project* resource.
/// It is not used directly, but through a [`ProjectMethods`] instance.
///
/// # Example
///
/// Instantiate a resource method builder
///
/// ```test_harness,no_run
/// # extern crate hyper;
/// # extern crate hyper_rustls;
/// # extern crate google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_list("name")
/// .page_token("et")
/// .page_size(-95)
/// .filter("Stet")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationOperationListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationOperationListCall<'a, C> {}
impl<'a, C> ProjectLocationOperationListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListOperationsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.operations.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("name", self._name);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}/operations";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// 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) -> ProjectLocationOperationListCall<'a, C> {
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) -> ProjectLocationOperationListCall<'a, C> {
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) -> ProjectLocationOperationListCall<'a, C> {
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) -> ProjectLocationOperationListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationOperationListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationOperationListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationOperationListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationOperationListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationOperationListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Waits until the specified long-running operation is done or reaches at most a specified timeout, returning the latest state. If the operation is already done, the latest state is immediately returned. If the timeout specified is greater than the default HTTP/RPC timeout, the HTTP/RPC timeout is used. If the server does not support this method, it returns `google.rpc.Code.UNIMPLEMENTED`. Note that this method is on a best-effort basis. It may return the latest state before the specified timeout (including immediately), meaning even an immediate response is no guarantee that the operation is done.
///
/// A builder for the *locations.operations.wait* 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 google_translate3 as translate3;
/// use translate3::api::WaitOperationRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = WaitOperationRequest::default();
///
/// // You can configure optional parameters by calling 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_wait(req, "name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationOperationWaitCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: WaitOperationRequest,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationOperationWaitCall<'a, C> {}
impl<'a, C> ProjectLocationOperationWaitCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.operations.wait",
http_method: hyper::Method::POST,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}:wait";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: WaitOperationRequest,
) -> ProjectLocationOperationWaitCall<'a, C> {
self._request = new_value;
self
}
/// The name of the operation resource to wait on.
///
/// 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) -> ProjectLocationOperationWaitCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationOperationWaitCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationOperationWaitCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationOperationWaitCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationOperationWaitCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationOperationWaitCall<'a, C> {
self._scopes.clear();
self
}
}
/// Translate text using Adaptive MT.
///
/// A builder for the *locations.adaptiveMtTranslate* 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 google_translate3 as translate3;
/// use translate3::api::AdaptiveMtTranslateRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = AdaptiveMtTranslateRequest::default();
///
/// // You can configure optional parameters by calling 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_adaptive_mt_translate(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationAdaptiveMtTranslateCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: AdaptiveMtTranslateRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationAdaptiveMtTranslateCall<'a, C> {}
impl<'a, C> ProjectLocationAdaptiveMtTranslateCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, AdaptiveMtTranslateResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.adaptiveMtTranslate",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:adaptiveMtTranslate";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: AdaptiveMtTranslateRequest,
) -> ProjectLocationAdaptiveMtTranslateCall<'a, C> {
self._request = new_value;
self
}
/// Required. Location to make a regional call. Format: `projects/{project-number-or-id}/locations/{location-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) -> ProjectLocationAdaptiveMtTranslateCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationAdaptiveMtTranslateCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationAdaptiveMtTranslateCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationAdaptiveMtTranslateCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationAdaptiveMtTranslateCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationAdaptiveMtTranslateCall<'a, C> {
self._scopes.clear();
self
}
}
/// Translates a large volume of document in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.
///
/// A builder for the *locations.batchTranslateDocument* 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 google_translate3 as translate3;
/// use translate3::api::BatchTranslateDocumentRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BatchTranslateDocumentRequest::default();
///
/// // You can configure optional parameters by calling 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_batch_translate_document(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationBatchTranslateDocumentCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: BatchTranslateDocumentRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationBatchTranslateDocumentCall<'a, C> {}
impl<'a, C> ProjectLocationBatchTranslateDocumentCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.batchTranslateDocument",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:batchTranslateDocument";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: BatchTranslateDocumentRequest,
) -> ProjectLocationBatchTranslateDocumentCall<'a, C> {
self._request = new_value;
self
}
/// Required. Location to make a regional call. Format: `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported for batch translation. Only AutoML Translation models or glossaries within the same region (have the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectLocationBatchTranslateDocumentCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationBatchTranslateDocumentCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationBatchTranslateDocumentCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationBatchTranslateDocumentCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(
mut self,
scopes: I,
) -> ProjectLocationBatchTranslateDocumentCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationBatchTranslateDocumentCall<'a, C> {
self._scopes.clear();
self
}
}
/// Translates a large volume of text in asynchronous batch mode. This function provides real-time output as the inputs are being processed. If caller cancels a request, the partial results (for an input file, it's all or nothing) may still be available on the specified output location. This call returns immediately and you can use google.longrunning.Operation.name to poll the status of the call.
///
/// A builder for the *locations.batchTranslateText* 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 google_translate3 as translate3;
/// use translate3::api::BatchTranslateTextRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = BatchTranslateTextRequest::default();
///
/// // You can configure optional parameters by calling 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_batch_translate_text(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationBatchTranslateTextCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: BatchTranslateTextRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationBatchTranslateTextCall<'a, C> {}
impl<'a, C> ProjectLocationBatchTranslateTextCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Operation)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.batchTranslateText",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:batchTranslateText";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: BatchTranslateTextRequest,
) -> ProjectLocationBatchTranslateTextCall<'a, C> {
self._request = new_value;
self
}
/// Required. Location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}`. The `global` location is not supported for batch translation. Only AutoML Translation models or glossaries within the same region (have the same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectLocationBatchTranslateTextCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationBatchTranslateTextCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationBatchTranslateTextCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationBatchTranslateTextCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationBatchTranslateTextCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationBatchTranslateTextCall<'a, C> {
self._scopes.clear();
self
}
}
/// Detects the language of text within a request.
///
/// A builder for the *locations.detectLanguage* 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 google_translate3 as translate3;
/// use translate3::api::DetectLanguageRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = DetectLanguageRequest::default();
///
/// // You can configure optional parameters by calling 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_detect_language(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationDetectLanguageCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: DetectLanguageRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationDetectLanguageCall<'a, C> {}
impl<'a, C> ProjectLocationDetectLanguageCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, DetectLanguageResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.detectLanguage",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:detectLanguage";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: DetectLanguageRequest,
) -> ProjectLocationDetectLanguageCall<'a, C> {
self._request = new_value;
self
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Only models within the same region (has same location-id) can be used. Otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectLocationDetectLanguageCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationDetectLanguageCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationDetectLanguageCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationDetectLanguageCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationDetectLanguageCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationDetectLanguageCall<'a, C> {
self._scopes.clear();
self
}
}
/// Gets information about a location.
///
/// A builder for the *locations.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_get("name")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGetCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGetCall<'a, C> {}
impl<'a, C> ProjectLocationGetCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, Location)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.get",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(3 + self._additional_params.len());
params.push("name", self._name);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Resource name for the location.
///
/// 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) -> ProjectLocationGetCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGetCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationGetCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGetCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationGetCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGetCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns a list of supported languages for translation.
///
/// A builder for the *locations.getSupportedLanguages* 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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_get_supported_languages("parent")
/// .model("elitr")
/// .display_language_code("Lorem")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationGetSupportedLanguageCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_model: Option<String>,
_display_language_code: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationGetSupportedLanguageCall<'a, C> {}
impl<'a, C> ProjectLocationGetSupportedLanguageCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, SupportedLanguages)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.getSupportedLanguages",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "model", "displayLanguageCode"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._model.as_ref() {
params.push("model", value);
}
if let Some(value) = self._display_language_code.as_ref() {
params.push("displayLanguageCode", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/supportedLanguages";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for AutoML models. Only models within the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectLocationGetSupportedLanguageCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. Get supported languages of this model. The format depends on model type: - AutoML Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, Returns languages supported by the specified model. If missing, we get supported languages of Google general NMT model.
///
/// Sets the *model* query property to the given value.
pub fn model(mut self, new_value: &str) -> ProjectLocationGetSupportedLanguageCall<'a, C> {
self._model = Some(new_value.to_string());
self
}
/// Optional. The language to use to return localized, human readable names of supported languages. If missing, then display names are not returned in a response.
///
/// Sets the *display language code* query property to the given value.
pub fn display_language_code(
mut self,
new_value: &str,
) -> ProjectLocationGetSupportedLanguageCall<'a, C> {
self._display_language_code = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationGetSupportedLanguageCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationGetSupportedLanguageCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationGetSupportedLanguageCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationGetSupportedLanguageCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationGetSupportedLanguageCall<'a, C> {
self._scopes.clear();
self
}
}
/// Lists information about the supported locations for this service.
///
/// A builder for the *locations.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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling 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_list("name")
/// .page_token("no")
/// .page_size(-100)
/// .filter("accusam")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationListCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_name: String,
_page_token: Option<String>,
_page_size: Option<i32>,
_filter: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationListCall<'a, C> {}
impl<'a, C> ProjectLocationListCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, ListLocationsResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.list",
http_method: hyper::Method::GET,
});
for &field in ["alt", "name", "pageToken", "pageSize", "filter"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(6 + self._additional_params.len());
params.push("name", self._name);
if let Some(value) = self._page_token.as_ref() {
params.push("pageToken", value);
}
if let Some(value) = self._page_size.as_ref() {
params.push("pageSize", value.to_string());
}
if let Some(value) = self._filter.as_ref() {
params.push("filter", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+name}/locations";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+name}", "name")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["name"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// The resource that owns the locations collection, if applicable.
///
/// 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) -> ProjectLocationListCall<'a, C> {
self._name = new_value.to_string();
self
}
/// A page token received from the `next_page_token` field in the response. Send that page token to receive the subsequent page.
///
/// Sets the *page token* query property to the given value.
pub fn page_token(mut self, new_value: &str) -> ProjectLocationListCall<'a, C> {
self._page_token = Some(new_value.to_string());
self
}
/// The maximum number of results to return. If not set, the service selects a default.
///
/// Sets the *page size* query property to the given value.
pub fn page_size(mut self, new_value: i32) -> ProjectLocationListCall<'a, C> {
self._page_size = Some(new_value);
self
}
/// A filter to narrow down results to a preferred subset. The filtering language accepts strings like `"displayName=tokyo"`, and is documented in more detail in [AIP-160](https://google.aip.dev/160).
///
/// Sets the *filter* query property to the given value.
pub fn filter(mut self, new_value: &str) -> ProjectLocationListCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationListCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationListCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationListCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationListCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationListCall<'a, C> {
self._scopes.clear();
self
}
}
/// Romanize input text written in non-Latin scripts to Latin text.
///
/// A builder for the *locations.romanizeText* 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 google_translate3 as translate3;
/// use translate3::api::RomanizeTextRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = RomanizeTextRequest::default();
///
/// // You can configure optional parameters by calling 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_romanize_text(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationRomanizeTextCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: RomanizeTextRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationRomanizeTextCall<'a, C> {}
impl<'a, C> ProjectLocationRomanizeTextCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, RomanizeTextResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.romanizeText",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:romanizeText";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: RomanizeTextRequest,
) -> ProjectLocationRomanizeTextCall<'a, C> {
self._request = new_value;
self
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-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) -> ProjectLocationRomanizeTextCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationRomanizeTextCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationRomanizeTextCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationRomanizeTextCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationRomanizeTextCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationRomanizeTextCall<'a, C> {
self._scopes.clear();
self
}
}
/// Translates documents in synchronous mode.
///
/// A builder for the *locations.translateDocument* 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 google_translate3 as translate3;
/// use translate3::api::TranslateDocumentRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TranslateDocumentRequest::default();
///
/// // You can configure optional parameters by calling 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_translate_document(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationTranslateDocumentCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: TranslateDocumentRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationTranslateDocumentCall<'a, C> {}
impl<'a, C> ProjectLocationTranslateDocumentCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, TranslateDocumentResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.translateDocument",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:translateDocument";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: TranslateDocumentRequest,
) -> ProjectLocationTranslateDocumentCall<'a, C> {
self._request = new_value;
self
}
/// Required. Location to make a regional call. Format: `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or custom glossaries. Models and glossaries must be within the same region (have the same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectLocationTranslateDocumentCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationTranslateDocumentCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationTranslateDocumentCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationTranslateDocumentCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationTranslateDocumentCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationTranslateDocumentCall<'a, C> {
self._scopes.clear();
self
}
}
/// Translates input text and returns translated text.
///
/// A builder for the *locations.translateText* 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 google_translate3 as translate3;
/// use translate3::api::TranslateTextRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TranslateTextRequest::default();
///
/// // You can configure optional parameters by calling 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_translate_text(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectLocationTranslateTextCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: TranslateTextRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectLocationTranslateTextCall<'a, C> {}
impl<'a, C> ProjectLocationTranslateTextCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, TranslateTextResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.locations.translateText",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:translateText";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(
mut self,
new_value: TranslateTextRequest,
) -> ProjectLocationTranslateTextCall<'a, C> {
self._request = new_value;
self
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or custom glossaries. Models and glossaries must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectLocationTranslateTextCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectLocationTranslateTextCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectLocationTranslateTextCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationTranslateTextCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectLocationTranslateTextCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectLocationTranslateTextCall<'a, C> {
self._scopes.clear();
self
}
}
/// Detects the language of text within a request.
///
/// A builder for the *detectLanguage* 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 google_translate3 as translate3;
/// use translate3::api::DetectLanguageRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = DetectLanguageRequest::default();
///
/// // You can configure optional parameters by calling 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().detect_language(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectDetectLanguageCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: DetectLanguageRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectDetectLanguageCall<'a, C> {}
impl<'a, C> ProjectDetectLanguageCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, DetectLanguageResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.detectLanguage",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:detectLanguage";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: DetectLanguageRequest) -> ProjectDetectLanguageCall<'a, C> {
self._request = new_value;
self
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Only models within the same region (has same location-id) can be used. Otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectDetectLanguageCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectDetectLanguageCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectDetectLanguageCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectDetectLanguageCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectDetectLanguageCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectDetectLanguageCall<'a, C> {
self._scopes.clear();
self
}
}
/// Returns a list of supported languages for translation.
///
/// A builder for the *getSupportedLanguages* 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 google_translate3 as translate3;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // You can configure optional parameters by calling the respective setters at will, and
/// // execute the final call using `doit()`.
/// // Values shown here are possibly random and not representative !
/// let result = hub.projects().get_supported_languages("parent")
/// .model("consetetur")
/// .display_language_code("amet.")
/// .doit().await;
/// # }
/// ```
pub struct ProjectGetSupportedLanguageCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_parent: String,
_model: Option<String>,
_display_language_code: Option<String>,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectGetSupportedLanguageCall<'a, C> {}
impl<'a, C> ProjectGetSupportedLanguageCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, SupportedLanguages)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.getSupportedLanguages",
http_method: hyper::Method::GET,
});
for &field in ["alt", "parent", "model", "displayLanguageCode"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(5 + self._additional_params.len());
params.push("parent", self._parent);
if let Some(value) = self._model.as_ref() {
params.push("model", value);
}
if let Some(value) = self._display_language_code.as_ref() {
params.push("displayLanguageCode", value);
}
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}/supportedLanguages";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::GET)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_LENGTH, 0_u64)
.body(common::to_body::<String>(None));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for AutoML models. Only models within the same region (have same location-id) can be used, otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectGetSupportedLanguageCall<'a, C> {
self._parent = new_value.to_string();
self
}
/// Optional. Get supported languages of this model. The format depends on model type: - AutoML Translation models: `projects/{project-number-or-id}/locations/{location-id}/models/{model-id}` - General (built-in) models: `projects/{project-number-or-id}/locations/{location-id}/models/general/nmt`, Returns languages supported by the specified model. If missing, we get supported languages of Google general NMT model.
///
/// Sets the *model* query property to the given value.
pub fn model(mut self, new_value: &str) -> ProjectGetSupportedLanguageCall<'a, C> {
self._model = Some(new_value.to_string());
self
}
/// Optional. The language to use to return localized, human readable names of supported languages. If missing, then display names are not returned in a response.
///
/// Sets the *display language code* query property to the given value.
pub fn display_language_code(
mut self,
new_value: &str,
) -> ProjectGetSupportedLanguageCall<'a, C> {
self._display_language_code = Some(new_value.to_string());
self
}
/// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
/// while executing the actual API request.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectGetSupportedLanguageCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectGetSupportedLanguageCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectGetSupportedLanguageCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectGetSupportedLanguageCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectGetSupportedLanguageCall<'a, C> {
self._scopes.clear();
self
}
}
/// Romanize input text written in non-Latin scripts to Latin text.
///
/// A builder for the *romanizeText* 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 google_translate3 as translate3;
/// use translate3::api::RomanizeTextRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = RomanizeTextRequest::default();
///
/// // You can configure optional parameters by calling 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().romanize_text(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectRomanizeTextCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: RomanizeTextRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectRomanizeTextCall<'a, C> {}
impl<'a, C> ProjectRomanizeTextCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, RomanizeTextResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.romanizeText",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:romanizeText";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: RomanizeTextRequest) -> ProjectRomanizeTextCall<'a, C> {
self._request = new_value;
self
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}/locations/{location-id}` or `projects/{project-number-or-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-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) -> ProjectRomanizeTextCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectRomanizeTextCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectRomanizeTextCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectRomanizeTextCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectRomanizeTextCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectRomanizeTextCall<'a, C> {
self._scopes.clear();
self
}
}
/// Translates input text and returns translated text.
///
/// A builder for the *translateText* 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 google_translate3 as translate3;
/// use translate3::api::TranslateTextRequest;
/// # async fn dox() {
/// # use translate3::{Translate, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
///
/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
/// # let auth = yup_oauth2::InstalledFlowAuthenticator::builder(
/// # secret,
/// # yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
/// # ).build().await.unwrap();
///
/// # let client = hyper_util::client::legacy::Client::builder(
/// # hyper_util::rt::TokioExecutor::new()
/// # )
/// # .build(
/// # hyper_rustls::HttpsConnectorBuilder::new()
/// # .with_native_roots()
/// # .unwrap()
/// # .https_or_http()
/// # .enable_http1()
/// # .build()
/// # );
/// # let mut hub = Translate::new(client, auth);
/// // As the method needs a request, you would usually fill it with the desired information
/// // into the respective structure. Some of the parts shown here might not be applicable !
/// // Values shown here are possibly random and not representative !
/// let mut req = TranslateTextRequest::default();
///
/// // You can configure optional parameters by calling 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().translate_text(req, "parent")
/// .doit().await;
/// # }
/// ```
pub struct ProjectTranslateTextCall<'a, C>
where
C: 'a,
{
hub: &'a Translate<C>,
_request: TranslateTextRequest,
_parent: String,
_delegate: Option<&'a mut dyn common::Delegate>,
_additional_params: HashMap<String, String>,
_scopes: BTreeSet<String>,
}
impl<'a, C> common::CallBuilder for ProjectTranslateTextCall<'a, C> {}
impl<'a, C> ProjectTranslateTextCall<'a, C>
where
C: common::Connector,
{
/// Perform the operation you have build so far.
pub async fn doit(mut self) -> common::Result<(common::Response, TranslateTextResponse)> {
use std::borrow::Cow;
use std::io::{Read, Seek};
use common::{url::Params, ToParts};
use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
let mut dd = common::DefaultDelegate;
let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
dlg.begin(common::MethodInfo {
id: "translate.projects.translateText",
http_method: hyper::Method::POST,
});
for &field in ["alt", "parent"].iter() {
if self._additional_params.contains_key(field) {
dlg.finished(false);
return Err(common::Error::FieldClash(field));
}
}
let mut params = Params::with_capacity(4 + self._additional_params.len());
params.push("parent", self._parent);
params.extend(self._additional_params.iter());
params.push("alt", "json");
let mut url = self.hub._base_url.clone() + "v3/{+parent}:translateText";
if self._scopes.is_empty() {
self._scopes
.insert(Scope::CloudPlatform.as_ref().to_string());
}
#[allow(clippy::single_element_loop)]
for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
url = params.uri_replacement(url, param_name, find_this, true);
}
{
let to_remove = ["parent"];
params.remove_params(&to_remove);
}
let url = params.parse_with_url(&url);
let mut json_mime_type = mime::APPLICATION_JSON;
let mut request_value_reader = {
let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
common::remove_json_null_values(&mut value);
let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
serde_json::to_writer(&mut dst, &value).unwrap();
dst
};
let request_size = request_value_reader
.seek(std::io::SeekFrom::End(0))
.unwrap();
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
loop {
let token = match self
.hub
.auth
.get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
.await
{
Ok(token) => token,
Err(e) => match dlg.token(e) {
Ok(token) => token,
Err(e) => {
dlg.finished(false);
return Err(common::Error::MissingToken(e));
}
},
};
request_value_reader
.seek(std::io::SeekFrom::Start(0))
.unwrap();
let mut req_result = {
let client = &self.hub.client;
dlg.pre_request();
let mut req_builder = hyper::Request::builder()
.method(hyper::Method::POST)
.uri(url.as_str())
.header(USER_AGENT, self.hub._user_agent.clone());
if let Some(token) = token.as_ref() {
req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
}
let request = req_builder
.header(CONTENT_TYPE, json_mime_type.to_string())
.header(CONTENT_LENGTH, request_size as u64)
.body(common::to_body(
request_value_reader.get_ref().clone().into(),
));
client.request(request.unwrap()).await
};
match req_result {
Err(err) => {
if let common::Retry::After(d) = dlg.http_error(&err) {
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(common::Error::HttpError(err));
}
Ok(res) => {
let (mut parts, body) = res.into_parts();
let mut body = common::Body::new(body);
if !parts.status.is_success() {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let error = serde_json::from_str(&common::to_string(&bytes));
let response = common::to_response(parts, bytes.into());
if let common::Retry::After(d) =
dlg.http_failure(&response, error.as_ref().ok())
{
sleep(d).await;
continue;
}
dlg.finished(false);
return Err(match error {
Ok(value) => common::Error::BadRequest(value),
_ => common::Error::Failure(response),
});
}
let response = {
let bytes = common::to_bytes(body).await.unwrap_or_default();
let encoded = common::to_string(&bytes);
match serde_json::from_str(&encoded) {
Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
Err(error) => {
dlg.response_json_decode_error(&encoded, &error);
return Err(common::Error::JsonDecodeError(
encoded.to_string(),
error,
));
}
}
};
dlg.finished(true);
return Ok(response);
}
}
}
}
///
/// Sets the *request* property to the given value.
///
/// Even though the property as already been set when instantiating this call,
/// we provide this method for API completeness.
pub fn request(mut self, new_value: TranslateTextRequest) -> ProjectTranslateTextCall<'a, C> {
self._request = new_value;
self
}
/// Required. Project or location to make a call. Must refer to a caller's project. Format: `projects/{project-number-or-id}` or `projects/{project-number-or-id}/locations/{location-id}`. For global calls, use `projects/{project-number-or-id}/locations/global` or `projects/{project-number-or-id}`. Non-global location is required for requests using AutoML models or custom glossaries. Models and glossaries must be within the same region (have same location-id), otherwise an INVALID_ARGUMENT (400) error is returned.
///
/// 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) -> ProjectTranslateTextCall<'a, C> {
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.
///
/// ````text
/// It should be used to handle progress information, and 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 common::Delegate,
) -> ProjectTranslateTextCall<'a, C> {
self._delegate = Some(new_value);
self
}
/// Set any additional parameter of the query string used in the request.
/// It should be used to set parameters 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
///
/// * *$.xgafv* (query-string) - V1 error format.
/// * *access_token* (query-string) - OAuth access token.
/// * *alt* (query-string) - Data format for response.
/// * *callback* (query-string) - JSONP
/// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
/// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
/// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
/// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
/// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
/// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
/// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
pub fn param<T>(mut self, name: T, value: T) -> ProjectTranslateTextCall<'a, C>
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 of the default [`Scope`] variant
/// [`Scope::CloudPlatform`].
///
/// The `scope` will be added to a set of scopes. This is important as one can maintain access
/// tokens for more than one scope.
///
/// Usually there is more than one suitable scope to authorize an operation, some of which may
/// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
/// sufficient, a read-write scope will do as well.
pub fn add_scope<St>(mut self, scope: St) -> ProjectTranslateTextCall<'a, C>
where
St: AsRef<str>,
{
self._scopes.insert(String::from(scope.as_ref()));
self
}
/// Identifies the authorization scope(s) for the method you are building.
///
/// See [`Self::add_scope()`] for details.
pub fn add_scopes<I, St>(mut self, scopes: I) -> ProjectTranslateTextCall<'a, C>
where
I: IntoIterator<Item = St>,
St: AsRef<str>,
{
self._scopes
.extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
self
}
/// Removes all scopes, and no default scope will be used either.
/// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
/// for details).
pub fn clear_scopes(mut self) -> ProjectTranslateTextCall<'a, C> {
self._scopes.clear();
self
}
}