google_policyanalyzer1/
api.rs

1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16    /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
17    CloudPlatform,
18}
19
20impl AsRef<str> for Scope {
21    fn as_ref(&self) -> &str {
22        match *self {
23            Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
24        }
25    }
26}
27
28#[allow(clippy::derivable_impls)]
29impl Default for Scope {
30    fn default() -> Scope {
31        Scope::CloudPlatform
32    }
33}
34
35// ########
36// HUB ###
37// ######
38
39/// Central instance to access all PolicyAnalyzer related resource activities
40///
41/// # Examples
42///
43/// Instantiate a new hub
44///
45/// ```test_harness,no_run
46/// extern crate hyper;
47/// extern crate hyper_rustls;
48/// extern crate google_policyanalyzer1 as policyanalyzer1;
49/// use policyanalyzer1::{Result, Error};
50/// # async fn dox() {
51/// use policyanalyzer1::{PolicyAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
52///
53/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
54/// // `client_secret`, among other things.
55/// let secret: yup_oauth2::ApplicationSecret = Default::default();
56/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
57/// // unless you replace  `None` with the desired Flow.
58/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
59/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
60/// // retrieve them from storage.
61/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
62///     .with_native_roots()
63///     .unwrap()
64///     .https_only()
65///     .enable_http2()
66///     .build();
67///
68/// let executor = hyper_util::rt::TokioExecutor::new();
69/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
70///     secret,
71///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
72///     yup_oauth2::client::CustomHyperClientBuilder::from(
73///         hyper_util::client::legacy::Client::builder(executor).build(connector),
74///     ),
75/// ).build().await.unwrap();
76///
77/// let client = hyper_util::client::legacy::Client::builder(
78///     hyper_util::rt::TokioExecutor::new()
79/// )
80/// .build(
81///     hyper_rustls::HttpsConnectorBuilder::new()
82///         .with_native_roots()
83///         .unwrap()
84///         .https_or_http()
85///         .enable_http2()
86///         .build()
87/// );
88/// let mut hub = PolicyAnalyzer::new(client, auth);
89/// // You can configure optional parameters by calling the respective setters at will, and
90/// // execute the final call using `doit()`.
91/// // Values shown here are possibly random and not representative !
92/// let result = hub.folders().locations_activity_types_activities_query("parent")
93///              .page_token("takimata")
94///              .page_size(-52)
95///              .filter("duo")
96///              .doit().await;
97///
98/// match result {
99///     Err(e) => match e {
100///         // The Error enum provides details about what exactly happened.
101///         // You can also just use its `Debug`, `Display` or `Error` traits
102///          Error::HttpError(_)
103///         |Error::Io(_)
104///         |Error::MissingAPIKey
105///         |Error::MissingToken(_)
106///         |Error::Cancelled
107///         |Error::UploadSizeLimitExceeded(_, _)
108///         |Error::Failure(_)
109///         |Error::BadRequest(_)
110///         |Error::FieldClash(_)
111///         |Error::JsonDecodeError(_, _) => println!("{}", e),
112///     },
113///     Ok(res) => println!("Success: {:?}", res),
114/// }
115/// # }
116/// ```
117#[derive(Clone)]
118pub struct PolicyAnalyzer<C> {
119    pub client: common::Client<C>,
120    pub auth: Box<dyn common::GetToken>,
121    _user_agent: String,
122    _base_url: String,
123    _root_url: String,
124}
125
126impl<C> common::Hub for PolicyAnalyzer<C> {}
127
128impl<'a, C> PolicyAnalyzer<C> {
129    pub fn new<A: 'static + common::GetToken>(
130        client: common::Client<C>,
131        auth: A,
132    ) -> PolicyAnalyzer<C> {
133        PolicyAnalyzer {
134            client,
135            auth: Box::new(auth),
136            _user_agent: "google-api-rust-client/7.0.0".to_string(),
137            _base_url: "https://policyanalyzer.googleapis.com/".to_string(),
138            _root_url: "https://policyanalyzer.googleapis.com/".to_string(),
139        }
140    }
141
142    pub fn folders(&'a self) -> FolderMethods<'a, C> {
143        FolderMethods { hub: self }
144    }
145    pub fn organizations(&'a self) -> OrganizationMethods<'a, C> {
146        OrganizationMethods { hub: self }
147    }
148    pub fn projects(&'a self) -> ProjectMethods<'a, C> {
149        ProjectMethods { hub: self }
150    }
151
152    /// Set the user-agent header field to use in all requests to the server.
153    /// It defaults to `google-api-rust-client/7.0.0`.
154    ///
155    /// Returns the previously set user-agent.
156    pub fn user_agent(&mut self, agent_name: String) -> String {
157        std::mem::replace(&mut self._user_agent, agent_name)
158    }
159
160    /// Set the base url to use in all requests to the server.
161    /// It defaults to `https://policyanalyzer.googleapis.com/`.
162    ///
163    /// Returns the previously set base url.
164    pub fn base_url(&mut self, new_base_url: String) -> String {
165        std::mem::replace(&mut self._base_url, new_base_url)
166    }
167
168    /// Set the root url to use in all requests to the server.
169    /// It defaults to `https://policyanalyzer.googleapis.com/`.
170    ///
171    /// Returns the previously set root url.
172    pub fn root_url(&mut self, new_root_url: String) -> String {
173        std::mem::replace(&mut self._root_url, new_root_url)
174    }
175}
176
177// ############
178// SCHEMAS ###
179// ##########
180/// Represents Activity on a GCP resource over specific observation period.
181///
182/// This type is not used in any activity, and only used as *part* of another schema.
183///
184#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
185#[serde_with::serde_as]
186#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
187pub struct GoogleCloudPolicyanalyzerV1Activity {
188    /// A struct of custom fields to explain the activity.
189    pub activity: Option<HashMap<String, serde_json::Value>>,
190    /// The type of the activity.
191    #[serde(rename = "activityType")]
192    pub activity_type: Option<String>,
193    /// The full resource name that identifies the resource. For examples of full resource names for Google Cloud services, see https://cloud.google.com/iam/help/troubleshooter/full-resource-names.
194    #[serde(rename = "fullResourceName")]
195    pub full_resource_name: Option<String>,
196    /// The data observation period to build the activity.
197    #[serde(rename = "observationPeriod")]
198    pub observation_period: Option<GoogleCloudPolicyanalyzerV1ObservationPeriod>,
199}
200
201impl common::Part for GoogleCloudPolicyanalyzerV1Activity {}
202
203/// Represents data observation period.
204///
205/// This type is not used in any activity, and only used as *part* of another schema.
206///
207#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
208#[serde_with::serde_as]
209#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
210pub struct GoogleCloudPolicyanalyzerV1ObservationPeriod {
211    /// The observation end time. The time in this timestamp is always `07:00:00Z`.
212    #[serde(rename = "endTime")]
213    pub end_time: Option<chrono::DateTime<chrono::offset::Utc>>,
214    /// The observation start time. The time in this timestamp is always `07:00:00Z`.
215    #[serde(rename = "startTime")]
216    pub start_time: Option<chrono::DateTime<chrono::offset::Utc>>,
217}
218
219impl common::Part for GoogleCloudPolicyanalyzerV1ObservationPeriod {}
220
221/// Response to the `QueryActivity` method.
222///
223/// # Activities
224///
225/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
226/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
227///
228/// * [locations activity types activities query folders](FolderLocationActivityTypeActivityQueryCall) (response)
229/// * [locations activity types activities query organizations](OrganizationLocationActivityTypeActivityQueryCall) (response)
230/// * [locations activity types activities query projects](ProjectLocationActivityTypeActivityQueryCall) (response)
231#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
232#[serde_with::serde_as]
233#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
234pub struct GoogleCloudPolicyanalyzerV1QueryActivityResponse {
235    /// The set of activities that match the filter included in the request.
236    pub activities: Option<Vec<GoogleCloudPolicyanalyzerV1Activity>>,
237    /// If there might be more results than those appearing in this response, then `nextPageToken` is included. To get the next set of results, call this method again using the value of `nextPageToken` as `pageToken`.
238    #[serde(rename = "nextPageToken")]
239    pub next_page_token: Option<String>,
240}
241
242impl common::ResponseResult for GoogleCloudPolicyanalyzerV1QueryActivityResponse {}
243
244// ###################
245// MethodBuilders ###
246// #################
247
248/// A builder providing access to all methods supported on *folder* resources.
249/// It is not used directly, but through the [`PolicyAnalyzer`] hub.
250///
251/// # Example
252///
253/// Instantiate a resource builder
254///
255/// ```test_harness,no_run
256/// extern crate hyper;
257/// extern crate hyper_rustls;
258/// extern crate google_policyanalyzer1 as policyanalyzer1;
259///
260/// # async fn dox() {
261/// use policyanalyzer1::{PolicyAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
262///
263/// let secret: yup_oauth2::ApplicationSecret = Default::default();
264/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
265///     .with_native_roots()
266///     .unwrap()
267///     .https_only()
268///     .enable_http2()
269///     .build();
270///
271/// let executor = hyper_util::rt::TokioExecutor::new();
272/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
273///     secret,
274///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
275///     yup_oauth2::client::CustomHyperClientBuilder::from(
276///         hyper_util::client::legacy::Client::builder(executor).build(connector),
277///     ),
278/// ).build().await.unwrap();
279///
280/// let client = hyper_util::client::legacy::Client::builder(
281///     hyper_util::rt::TokioExecutor::new()
282/// )
283/// .build(
284///     hyper_rustls::HttpsConnectorBuilder::new()
285///         .with_native_roots()
286///         .unwrap()
287///         .https_or_http()
288///         .enable_http2()
289///         .build()
290/// );
291/// let mut hub = PolicyAnalyzer::new(client, auth);
292/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
293/// // like `locations_activity_types_activities_query(...)`
294/// // to build up your call.
295/// let rb = hub.folders();
296/// # }
297/// ```
298pub struct FolderMethods<'a, C>
299where
300    C: 'a,
301{
302    hub: &'a PolicyAnalyzer<C>,
303}
304
305impl<'a, C> common::MethodsBuilder for FolderMethods<'a, C> {}
306
307impl<'a, C> FolderMethods<'a, C> {
308    /// Create a builder to help you perform the following task:
309    ///
310    /// Queries policy activities on Google Cloud resources.
311    ///
312    /// # Arguments
313    ///
314    /// * `parent` - Required. The container resource on which to execute the request. Acceptable formats: `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/
315    pub fn locations_activity_types_activities_query(
316        &self,
317        parent: &str,
318    ) -> FolderLocationActivityTypeActivityQueryCall<'a, C> {
319        FolderLocationActivityTypeActivityQueryCall {
320            hub: self.hub,
321            _parent: parent.to_string(),
322            _page_token: Default::default(),
323            _page_size: Default::default(),
324            _filter: Default::default(),
325            _delegate: Default::default(),
326            _additional_params: Default::default(),
327            _scopes: Default::default(),
328        }
329    }
330}
331
332/// A builder providing access to all methods supported on *organization* resources.
333/// It is not used directly, but through the [`PolicyAnalyzer`] hub.
334///
335/// # Example
336///
337/// Instantiate a resource builder
338///
339/// ```test_harness,no_run
340/// extern crate hyper;
341/// extern crate hyper_rustls;
342/// extern crate google_policyanalyzer1 as policyanalyzer1;
343///
344/// # async fn dox() {
345/// use policyanalyzer1::{PolicyAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
346///
347/// let secret: yup_oauth2::ApplicationSecret = Default::default();
348/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
349///     .with_native_roots()
350///     .unwrap()
351///     .https_only()
352///     .enable_http2()
353///     .build();
354///
355/// let executor = hyper_util::rt::TokioExecutor::new();
356/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
357///     secret,
358///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
359///     yup_oauth2::client::CustomHyperClientBuilder::from(
360///         hyper_util::client::legacy::Client::builder(executor).build(connector),
361///     ),
362/// ).build().await.unwrap();
363///
364/// let client = hyper_util::client::legacy::Client::builder(
365///     hyper_util::rt::TokioExecutor::new()
366/// )
367/// .build(
368///     hyper_rustls::HttpsConnectorBuilder::new()
369///         .with_native_roots()
370///         .unwrap()
371///         .https_or_http()
372///         .enable_http2()
373///         .build()
374/// );
375/// let mut hub = PolicyAnalyzer::new(client, auth);
376/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
377/// // like `locations_activity_types_activities_query(...)`
378/// // to build up your call.
379/// let rb = hub.organizations();
380/// # }
381/// ```
382pub struct OrganizationMethods<'a, C>
383where
384    C: 'a,
385{
386    hub: &'a PolicyAnalyzer<C>,
387}
388
389impl<'a, C> common::MethodsBuilder for OrganizationMethods<'a, C> {}
390
391impl<'a, C> OrganizationMethods<'a, C> {
392    /// Create a builder to help you perform the following task:
393    ///
394    /// Queries policy activities on Google Cloud resources.
395    ///
396    /// # Arguments
397    ///
398    /// * `parent` - Required. The container resource on which to execute the request. Acceptable formats: `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/
399    pub fn locations_activity_types_activities_query(
400        &self,
401        parent: &str,
402    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C> {
403        OrganizationLocationActivityTypeActivityQueryCall {
404            hub: self.hub,
405            _parent: parent.to_string(),
406            _page_token: Default::default(),
407            _page_size: Default::default(),
408            _filter: Default::default(),
409            _delegate: Default::default(),
410            _additional_params: Default::default(),
411            _scopes: Default::default(),
412        }
413    }
414}
415
416/// A builder providing access to all methods supported on *project* resources.
417/// It is not used directly, but through the [`PolicyAnalyzer`] hub.
418///
419/// # Example
420///
421/// Instantiate a resource builder
422///
423/// ```test_harness,no_run
424/// extern crate hyper;
425/// extern crate hyper_rustls;
426/// extern crate google_policyanalyzer1 as policyanalyzer1;
427///
428/// # async fn dox() {
429/// use policyanalyzer1::{PolicyAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
430///
431/// let secret: yup_oauth2::ApplicationSecret = Default::default();
432/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
433///     .with_native_roots()
434///     .unwrap()
435///     .https_only()
436///     .enable_http2()
437///     .build();
438///
439/// let executor = hyper_util::rt::TokioExecutor::new();
440/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
441///     secret,
442///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
443///     yup_oauth2::client::CustomHyperClientBuilder::from(
444///         hyper_util::client::legacy::Client::builder(executor).build(connector),
445///     ),
446/// ).build().await.unwrap();
447///
448/// let client = hyper_util::client::legacy::Client::builder(
449///     hyper_util::rt::TokioExecutor::new()
450/// )
451/// .build(
452///     hyper_rustls::HttpsConnectorBuilder::new()
453///         .with_native_roots()
454///         .unwrap()
455///         .https_or_http()
456///         .enable_http2()
457///         .build()
458/// );
459/// let mut hub = PolicyAnalyzer::new(client, auth);
460/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
461/// // like `locations_activity_types_activities_query(...)`
462/// // to build up your call.
463/// let rb = hub.projects();
464/// # }
465/// ```
466pub struct ProjectMethods<'a, C>
467where
468    C: 'a,
469{
470    hub: &'a PolicyAnalyzer<C>,
471}
472
473impl<'a, C> common::MethodsBuilder for ProjectMethods<'a, C> {}
474
475impl<'a, C> ProjectMethods<'a, C> {
476    /// Create a builder to help you perform the following task:
477    ///
478    /// Queries policy activities on Google Cloud resources.
479    ///
480    /// # Arguments
481    ///
482    /// * `parent` - Required. The container resource on which to execute the request. Acceptable formats: `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/
483    pub fn locations_activity_types_activities_query(
484        &self,
485        parent: &str,
486    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C> {
487        ProjectLocationActivityTypeActivityQueryCall {
488            hub: self.hub,
489            _parent: parent.to_string(),
490            _page_token: Default::default(),
491            _page_size: Default::default(),
492            _filter: Default::default(),
493            _delegate: Default::default(),
494            _additional_params: Default::default(),
495            _scopes: Default::default(),
496        }
497    }
498}
499
500// ###################
501// CallBuilders   ###
502// #################
503
504/// Queries policy activities on Google Cloud resources.
505///
506/// A builder for the *locations.activityTypes.activities.query* method supported by a *folder* resource.
507/// It is not used directly, but through a [`FolderMethods`] instance.
508///
509/// # Example
510///
511/// Instantiate a resource method builder
512///
513/// ```test_harness,no_run
514/// # extern crate hyper;
515/// # extern crate hyper_rustls;
516/// # extern crate google_policyanalyzer1 as policyanalyzer1;
517/// # async fn dox() {
518/// # use policyanalyzer1::{PolicyAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
519///
520/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
521/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
522/// #     .with_native_roots()
523/// #     .unwrap()
524/// #     .https_only()
525/// #     .enable_http2()
526/// #     .build();
527///
528/// # let executor = hyper_util::rt::TokioExecutor::new();
529/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
530/// #     secret,
531/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
532/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
533/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
534/// #     ),
535/// # ).build().await.unwrap();
536///
537/// # let client = hyper_util::client::legacy::Client::builder(
538/// #     hyper_util::rt::TokioExecutor::new()
539/// # )
540/// # .build(
541/// #     hyper_rustls::HttpsConnectorBuilder::new()
542/// #         .with_native_roots()
543/// #         .unwrap()
544/// #         .https_or_http()
545/// #         .enable_http2()
546/// #         .build()
547/// # );
548/// # let mut hub = PolicyAnalyzer::new(client, auth);
549/// // You can configure optional parameters by calling the respective setters at will, and
550/// // execute the final call using `doit()`.
551/// // Values shown here are possibly random and not representative !
552/// let result = hub.folders().locations_activity_types_activities_query("parent")
553///              .page_token("gubergren")
554///              .page_size(-51)
555///              .filter("gubergren")
556///              .doit().await;
557/// # }
558/// ```
559pub struct FolderLocationActivityTypeActivityQueryCall<'a, C>
560where
561    C: 'a,
562{
563    hub: &'a PolicyAnalyzer<C>,
564    _parent: String,
565    _page_token: Option<String>,
566    _page_size: Option<i32>,
567    _filter: Option<String>,
568    _delegate: Option<&'a mut dyn common::Delegate>,
569    _additional_params: HashMap<String, String>,
570    _scopes: BTreeSet<String>,
571}
572
573impl<'a, C> common::CallBuilder for FolderLocationActivityTypeActivityQueryCall<'a, C> {}
574
575impl<'a, C> FolderLocationActivityTypeActivityQueryCall<'a, C>
576where
577    C: common::Connector,
578{
579    /// Perform the operation you have build so far.
580    pub async fn doit(
581        mut self,
582    ) -> common::Result<(
583        common::Response,
584        GoogleCloudPolicyanalyzerV1QueryActivityResponse,
585    )> {
586        use std::borrow::Cow;
587        use std::io::{Read, Seek};
588
589        use common::{url::Params, ToParts};
590        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
591
592        let mut dd = common::DefaultDelegate;
593        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
594        dlg.begin(common::MethodInfo {
595            id: "policyanalyzer.folders.locations.activityTypes.activities.query",
596            http_method: hyper::Method::GET,
597        });
598
599        for &field in ["alt", "parent", "pageToken", "pageSize", "filter"].iter() {
600            if self._additional_params.contains_key(field) {
601                dlg.finished(false);
602                return Err(common::Error::FieldClash(field));
603            }
604        }
605
606        let mut params = Params::with_capacity(6 + self._additional_params.len());
607        params.push("parent", self._parent);
608        if let Some(value) = self._page_token.as_ref() {
609            params.push("pageToken", value);
610        }
611        if let Some(value) = self._page_size.as_ref() {
612            params.push("pageSize", value.to_string());
613        }
614        if let Some(value) = self._filter.as_ref() {
615            params.push("filter", value);
616        }
617
618        params.extend(self._additional_params.iter());
619
620        params.push("alt", "json");
621        let mut url = self.hub._base_url.clone() + "v1/{+parent}/activities:query";
622        if self._scopes.is_empty() {
623            self._scopes
624                .insert(Scope::CloudPlatform.as_ref().to_string());
625        }
626
627        #[allow(clippy::single_element_loop)]
628        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
629            url = params.uri_replacement(url, param_name, find_this, true);
630        }
631        {
632            let to_remove = ["parent"];
633            params.remove_params(&to_remove);
634        }
635
636        let url = params.parse_with_url(&url);
637
638        loop {
639            let token = match self
640                .hub
641                .auth
642                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
643                .await
644            {
645                Ok(token) => token,
646                Err(e) => match dlg.token(e) {
647                    Ok(token) => token,
648                    Err(e) => {
649                        dlg.finished(false);
650                        return Err(common::Error::MissingToken(e));
651                    }
652                },
653            };
654            let mut req_result = {
655                let client = &self.hub.client;
656                dlg.pre_request();
657                let mut req_builder = hyper::Request::builder()
658                    .method(hyper::Method::GET)
659                    .uri(url.as_str())
660                    .header(USER_AGENT, self.hub._user_agent.clone());
661
662                if let Some(token) = token.as_ref() {
663                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
664                }
665
666                let request = req_builder
667                    .header(CONTENT_LENGTH, 0_u64)
668                    .body(common::to_body::<String>(None));
669
670                client.request(request.unwrap()).await
671            };
672
673            match req_result {
674                Err(err) => {
675                    if let common::Retry::After(d) = dlg.http_error(&err) {
676                        sleep(d).await;
677                        continue;
678                    }
679                    dlg.finished(false);
680                    return Err(common::Error::HttpError(err));
681                }
682                Ok(res) => {
683                    let (mut parts, body) = res.into_parts();
684                    let mut body = common::Body::new(body);
685                    if !parts.status.is_success() {
686                        let bytes = common::to_bytes(body).await.unwrap_or_default();
687                        let error = serde_json::from_str(&common::to_string(&bytes));
688                        let response = common::to_response(parts, bytes.into());
689
690                        if let common::Retry::After(d) =
691                            dlg.http_failure(&response, error.as_ref().ok())
692                        {
693                            sleep(d).await;
694                            continue;
695                        }
696
697                        dlg.finished(false);
698
699                        return Err(match error {
700                            Ok(value) => common::Error::BadRequest(value),
701                            _ => common::Error::Failure(response),
702                        });
703                    }
704                    let response = {
705                        let bytes = common::to_bytes(body).await.unwrap_or_default();
706                        let encoded = common::to_string(&bytes);
707                        match serde_json::from_str(&encoded) {
708                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
709                            Err(error) => {
710                                dlg.response_json_decode_error(&encoded, &error);
711                                return Err(common::Error::JsonDecodeError(
712                                    encoded.to_string(),
713                                    error,
714                                ));
715                            }
716                        }
717                    };
718
719                    dlg.finished(true);
720                    return Ok(response);
721                }
722            }
723        }
724    }
725
726    /// Required. The container resource on which to execute the request. Acceptable formats: `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/
727    ///
728    /// Sets the *parent* path property to the given value.
729    ///
730    /// Even though the property as already been set when instantiating this call,
731    /// we provide this method for API completeness.
732    pub fn parent(mut self, new_value: &str) -> FolderLocationActivityTypeActivityQueryCall<'a, C> {
733        self._parent = new_value.to_string();
734        self
735    }
736    /// Optional. If present, then retrieve the next batch of results from the preceding call to this method. `pageToken` must be the value of `nextPageToken` from the previous response. The values of other method parameters should be identical to those in the previous call.
737    ///
738    /// Sets the *page token* query property to the given value.
739    pub fn page_token(
740        mut self,
741        new_value: &str,
742    ) -> FolderLocationActivityTypeActivityQueryCall<'a, C> {
743        self._page_token = Some(new_value.to_string());
744        self
745    }
746    /// Optional. The maximum number of results to return from this request. Max limit is 1000. Non-positive values are ignored. The presence of `nextPageToken` in the response indicates that more results might be available.
747    ///
748    /// Sets the *page size* query property to the given value.
749    pub fn page_size(
750        mut self,
751        new_value: i32,
752    ) -> FolderLocationActivityTypeActivityQueryCall<'a, C> {
753        self._page_size = Some(new_value);
754        self
755    }
756    /// Optional. Filter expression to restrict the activities returned. For serviceAccountLastAuthentication activities, supported filters are: - `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` where `[STRING]` is the full resource name of the service account. For serviceAccountKeyLastAuthentication activities, supported filters are: - `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` where `[STRING]` is the full resource name of the service account key.
757    ///
758    /// Sets the *filter* query property to the given value.
759    pub fn filter(mut self, new_value: &str) -> FolderLocationActivityTypeActivityQueryCall<'a, C> {
760        self._filter = Some(new_value.to_string());
761        self
762    }
763    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
764    /// while executing the actual API request.
765    ///
766    /// ````text
767    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
768    /// ````
769    ///
770    /// Sets the *delegate* property to the given value.
771    pub fn delegate(
772        mut self,
773        new_value: &'a mut dyn common::Delegate,
774    ) -> FolderLocationActivityTypeActivityQueryCall<'a, C> {
775        self._delegate = Some(new_value);
776        self
777    }
778
779    /// Set any additional parameter of the query string used in the request.
780    /// It should be used to set parameters which are not yet available through their own
781    /// setters.
782    ///
783    /// Please note that this method must not be used to set any of the known parameters
784    /// which have their own setter method. If done anyway, the request will fail.
785    ///
786    /// # Additional Parameters
787    ///
788    /// * *$.xgafv* (query-string) - V1 error format.
789    /// * *access_token* (query-string) - OAuth access token.
790    /// * *alt* (query-string) - Data format for response.
791    /// * *callback* (query-string) - JSONP
792    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
793    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
794    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
795    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
796    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
797    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
798    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
799    pub fn param<T>(
800        mut self,
801        name: T,
802        value: T,
803    ) -> FolderLocationActivityTypeActivityQueryCall<'a, C>
804    where
805        T: AsRef<str>,
806    {
807        self._additional_params
808            .insert(name.as_ref().to_string(), value.as_ref().to_string());
809        self
810    }
811
812    /// Identifies the authorization scope for the method you are building.
813    ///
814    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
815    /// [`Scope::CloudPlatform`].
816    ///
817    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
818    /// tokens for more than one scope.
819    ///
820    /// Usually there is more than one suitable scope to authorize an operation, some of which may
821    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
822    /// sufficient, a read-write scope will do as well.
823    pub fn add_scope<St>(mut self, scope: St) -> FolderLocationActivityTypeActivityQueryCall<'a, C>
824    where
825        St: AsRef<str>,
826    {
827        self._scopes.insert(String::from(scope.as_ref()));
828        self
829    }
830    /// Identifies the authorization scope(s) for the method you are building.
831    ///
832    /// See [`Self::add_scope()`] for details.
833    pub fn add_scopes<I, St>(
834        mut self,
835        scopes: I,
836    ) -> FolderLocationActivityTypeActivityQueryCall<'a, C>
837    where
838        I: IntoIterator<Item = St>,
839        St: AsRef<str>,
840    {
841        self._scopes
842            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
843        self
844    }
845
846    /// Removes all scopes, and no default scope will be used either.
847    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
848    /// for details).
849    pub fn clear_scopes(mut self) -> FolderLocationActivityTypeActivityQueryCall<'a, C> {
850        self._scopes.clear();
851        self
852    }
853}
854
855/// Queries policy activities on Google Cloud resources.
856///
857/// A builder for the *locations.activityTypes.activities.query* method supported by a *organization* resource.
858/// It is not used directly, but through a [`OrganizationMethods`] instance.
859///
860/// # Example
861///
862/// Instantiate a resource method builder
863///
864/// ```test_harness,no_run
865/// # extern crate hyper;
866/// # extern crate hyper_rustls;
867/// # extern crate google_policyanalyzer1 as policyanalyzer1;
868/// # async fn dox() {
869/// # use policyanalyzer1::{PolicyAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
870///
871/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
872/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
873/// #     .with_native_roots()
874/// #     .unwrap()
875/// #     .https_only()
876/// #     .enable_http2()
877/// #     .build();
878///
879/// # let executor = hyper_util::rt::TokioExecutor::new();
880/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
881/// #     secret,
882/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
883/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
884/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
885/// #     ),
886/// # ).build().await.unwrap();
887///
888/// # let client = hyper_util::client::legacy::Client::builder(
889/// #     hyper_util::rt::TokioExecutor::new()
890/// # )
891/// # .build(
892/// #     hyper_rustls::HttpsConnectorBuilder::new()
893/// #         .with_native_roots()
894/// #         .unwrap()
895/// #         .https_or_http()
896/// #         .enable_http2()
897/// #         .build()
898/// # );
899/// # let mut hub = PolicyAnalyzer::new(client, auth);
900/// // You can configure optional parameters by calling the respective setters at will, and
901/// // execute the final call using `doit()`.
902/// // Values shown here are possibly random and not representative !
903/// let result = hub.organizations().locations_activity_types_activities_query("parent")
904///              .page_token("dolor")
905///              .page_size(-17)
906///              .filter("ipsum")
907///              .doit().await;
908/// # }
909/// ```
910pub struct OrganizationLocationActivityTypeActivityQueryCall<'a, C>
911where
912    C: 'a,
913{
914    hub: &'a PolicyAnalyzer<C>,
915    _parent: String,
916    _page_token: Option<String>,
917    _page_size: Option<i32>,
918    _filter: Option<String>,
919    _delegate: Option<&'a mut dyn common::Delegate>,
920    _additional_params: HashMap<String, String>,
921    _scopes: BTreeSet<String>,
922}
923
924impl<'a, C> common::CallBuilder for OrganizationLocationActivityTypeActivityQueryCall<'a, C> {}
925
926impl<'a, C> OrganizationLocationActivityTypeActivityQueryCall<'a, C>
927where
928    C: common::Connector,
929{
930    /// Perform the operation you have build so far.
931    pub async fn doit(
932        mut self,
933    ) -> common::Result<(
934        common::Response,
935        GoogleCloudPolicyanalyzerV1QueryActivityResponse,
936    )> {
937        use std::borrow::Cow;
938        use std::io::{Read, Seek};
939
940        use common::{url::Params, ToParts};
941        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
942
943        let mut dd = common::DefaultDelegate;
944        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
945        dlg.begin(common::MethodInfo {
946            id: "policyanalyzer.organizations.locations.activityTypes.activities.query",
947            http_method: hyper::Method::GET,
948        });
949
950        for &field in ["alt", "parent", "pageToken", "pageSize", "filter"].iter() {
951            if self._additional_params.contains_key(field) {
952                dlg.finished(false);
953                return Err(common::Error::FieldClash(field));
954            }
955        }
956
957        let mut params = Params::with_capacity(6 + self._additional_params.len());
958        params.push("parent", self._parent);
959        if let Some(value) = self._page_token.as_ref() {
960            params.push("pageToken", value);
961        }
962        if let Some(value) = self._page_size.as_ref() {
963            params.push("pageSize", value.to_string());
964        }
965        if let Some(value) = self._filter.as_ref() {
966            params.push("filter", value);
967        }
968
969        params.extend(self._additional_params.iter());
970
971        params.push("alt", "json");
972        let mut url = self.hub._base_url.clone() + "v1/{+parent}/activities:query";
973        if self._scopes.is_empty() {
974            self._scopes
975                .insert(Scope::CloudPlatform.as_ref().to_string());
976        }
977
978        #[allow(clippy::single_element_loop)]
979        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
980            url = params.uri_replacement(url, param_name, find_this, true);
981        }
982        {
983            let to_remove = ["parent"];
984            params.remove_params(&to_remove);
985        }
986
987        let url = params.parse_with_url(&url);
988
989        loop {
990            let token = match self
991                .hub
992                .auth
993                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
994                .await
995            {
996                Ok(token) => token,
997                Err(e) => match dlg.token(e) {
998                    Ok(token) => token,
999                    Err(e) => {
1000                        dlg.finished(false);
1001                        return Err(common::Error::MissingToken(e));
1002                    }
1003                },
1004            };
1005            let mut req_result = {
1006                let client = &self.hub.client;
1007                dlg.pre_request();
1008                let mut req_builder = hyper::Request::builder()
1009                    .method(hyper::Method::GET)
1010                    .uri(url.as_str())
1011                    .header(USER_AGENT, self.hub._user_agent.clone());
1012
1013                if let Some(token) = token.as_ref() {
1014                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1015                }
1016
1017                let request = req_builder
1018                    .header(CONTENT_LENGTH, 0_u64)
1019                    .body(common::to_body::<String>(None));
1020
1021                client.request(request.unwrap()).await
1022            };
1023
1024            match req_result {
1025                Err(err) => {
1026                    if let common::Retry::After(d) = dlg.http_error(&err) {
1027                        sleep(d).await;
1028                        continue;
1029                    }
1030                    dlg.finished(false);
1031                    return Err(common::Error::HttpError(err));
1032                }
1033                Ok(res) => {
1034                    let (mut parts, body) = res.into_parts();
1035                    let mut body = common::Body::new(body);
1036                    if !parts.status.is_success() {
1037                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1038                        let error = serde_json::from_str(&common::to_string(&bytes));
1039                        let response = common::to_response(parts, bytes.into());
1040
1041                        if let common::Retry::After(d) =
1042                            dlg.http_failure(&response, error.as_ref().ok())
1043                        {
1044                            sleep(d).await;
1045                            continue;
1046                        }
1047
1048                        dlg.finished(false);
1049
1050                        return Err(match error {
1051                            Ok(value) => common::Error::BadRequest(value),
1052                            _ => common::Error::Failure(response),
1053                        });
1054                    }
1055                    let response = {
1056                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1057                        let encoded = common::to_string(&bytes);
1058                        match serde_json::from_str(&encoded) {
1059                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1060                            Err(error) => {
1061                                dlg.response_json_decode_error(&encoded, &error);
1062                                return Err(common::Error::JsonDecodeError(
1063                                    encoded.to_string(),
1064                                    error,
1065                                ));
1066                            }
1067                        }
1068                    };
1069
1070                    dlg.finished(true);
1071                    return Ok(response);
1072                }
1073            }
1074        }
1075    }
1076
1077    /// Required. The container resource on which to execute the request. Acceptable formats: `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/
1078    ///
1079    /// Sets the *parent* path property to the given value.
1080    ///
1081    /// Even though the property as already been set when instantiating this call,
1082    /// we provide this method for API completeness.
1083    pub fn parent(
1084        mut self,
1085        new_value: &str,
1086    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C> {
1087        self._parent = new_value.to_string();
1088        self
1089    }
1090    /// Optional. If present, then retrieve the next batch of results from the preceding call to this method. `pageToken` must be the value of `nextPageToken` from the previous response. The values of other method parameters should be identical to those in the previous call.
1091    ///
1092    /// Sets the *page token* query property to the given value.
1093    pub fn page_token(
1094        mut self,
1095        new_value: &str,
1096    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C> {
1097        self._page_token = Some(new_value.to_string());
1098        self
1099    }
1100    /// Optional. The maximum number of results to return from this request. Max limit is 1000. Non-positive values are ignored. The presence of `nextPageToken` in the response indicates that more results might be available.
1101    ///
1102    /// Sets the *page size* query property to the given value.
1103    pub fn page_size(
1104        mut self,
1105        new_value: i32,
1106    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C> {
1107        self._page_size = Some(new_value);
1108        self
1109    }
1110    /// Optional. Filter expression to restrict the activities returned. For serviceAccountLastAuthentication activities, supported filters are: - `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` where `[STRING]` is the full resource name of the service account. For serviceAccountKeyLastAuthentication activities, supported filters are: - `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` where `[STRING]` is the full resource name of the service account key.
1111    ///
1112    /// Sets the *filter* query property to the given value.
1113    pub fn filter(
1114        mut self,
1115        new_value: &str,
1116    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C> {
1117        self._filter = Some(new_value.to_string());
1118        self
1119    }
1120    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1121    /// while executing the actual API request.
1122    ///
1123    /// ````text
1124    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1125    /// ````
1126    ///
1127    /// Sets the *delegate* property to the given value.
1128    pub fn delegate(
1129        mut self,
1130        new_value: &'a mut dyn common::Delegate,
1131    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C> {
1132        self._delegate = Some(new_value);
1133        self
1134    }
1135
1136    /// Set any additional parameter of the query string used in the request.
1137    /// It should be used to set parameters which are not yet available through their own
1138    /// setters.
1139    ///
1140    /// Please note that this method must not be used to set any of the known parameters
1141    /// which have their own setter method. If done anyway, the request will fail.
1142    ///
1143    /// # Additional Parameters
1144    ///
1145    /// * *$.xgafv* (query-string) - V1 error format.
1146    /// * *access_token* (query-string) - OAuth access token.
1147    /// * *alt* (query-string) - Data format for response.
1148    /// * *callback* (query-string) - JSONP
1149    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1150    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1151    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1152    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1153    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1154    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1155    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1156    pub fn param<T>(
1157        mut self,
1158        name: T,
1159        value: T,
1160    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C>
1161    where
1162        T: AsRef<str>,
1163    {
1164        self._additional_params
1165            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1166        self
1167    }
1168
1169    /// Identifies the authorization scope for the method you are building.
1170    ///
1171    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1172    /// [`Scope::CloudPlatform`].
1173    ///
1174    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1175    /// tokens for more than one scope.
1176    ///
1177    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1178    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1179    /// sufficient, a read-write scope will do as well.
1180    pub fn add_scope<St>(
1181        mut self,
1182        scope: St,
1183    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C>
1184    where
1185        St: AsRef<str>,
1186    {
1187        self._scopes.insert(String::from(scope.as_ref()));
1188        self
1189    }
1190    /// Identifies the authorization scope(s) for the method you are building.
1191    ///
1192    /// See [`Self::add_scope()`] for details.
1193    pub fn add_scopes<I, St>(
1194        mut self,
1195        scopes: I,
1196    ) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C>
1197    where
1198        I: IntoIterator<Item = St>,
1199        St: AsRef<str>,
1200    {
1201        self._scopes
1202            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1203        self
1204    }
1205
1206    /// Removes all scopes, and no default scope will be used either.
1207    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1208    /// for details).
1209    pub fn clear_scopes(mut self) -> OrganizationLocationActivityTypeActivityQueryCall<'a, C> {
1210        self._scopes.clear();
1211        self
1212    }
1213}
1214
1215/// Queries policy activities on Google Cloud resources.
1216///
1217/// A builder for the *locations.activityTypes.activities.query* method supported by a *project* resource.
1218/// It is not used directly, but through a [`ProjectMethods`] instance.
1219///
1220/// # Example
1221///
1222/// Instantiate a resource method builder
1223///
1224/// ```test_harness,no_run
1225/// # extern crate hyper;
1226/// # extern crate hyper_rustls;
1227/// # extern crate google_policyanalyzer1 as policyanalyzer1;
1228/// # async fn dox() {
1229/// # use policyanalyzer1::{PolicyAnalyzer, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1230///
1231/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1232/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1233/// #     .with_native_roots()
1234/// #     .unwrap()
1235/// #     .https_only()
1236/// #     .enable_http2()
1237/// #     .build();
1238///
1239/// # let executor = hyper_util::rt::TokioExecutor::new();
1240/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1241/// #     secret,
1242/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1243/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1244/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1245/// #     ),
1246/// # ).build().await.unwrap();
1247///
1248/// # let client = hyper_util::client::legacy::Client::builder(
1249/// #     hyper_util::rt::TokioExecutor::new()
1250/// # )
1251/// # .build(
1252/// #     hyper_rustls::HttpsConnectorBuilder::new()
1253/// #         .with_native_roots()
1254/// #         .unwrap()
1255/// #         .https_or_http()
1256/// #         .enable_http2()
1257/// #         .build()
1258/// # );
1259/// # let mut hub = PolicyAnalyzer::new(client, auth);
1260/// // You can configure optional parameters by calling the respective setters at will, and
1261/// // execute the final call using `doit()`.
1262/// // Values shown here are possibly random and not representative !
1263/// let result = hub.projects().locations_activity_types_activities_query("parent")
1264///              .page_token("amet")
1265///              .page_size(-20)
1266///              .filter("ipsum")
1267///              .doit().await;
1268/// # }
1269/// ```
1270pub struct ProjectLocationActivityTypeActivityQueryCall<'a, C>
1271where
1272    C: 'a,
1273{
1274    hub: &'a PolicyAnalyzer<C>,
1275    _parent: String,
1276    _page_token: Option<String>,
1277    _page_size: Option<i32>,
1278    _filter: Option<String>,
1279    _delegate: Option<&'a mut dyn common::Delegate>,
1280    _additional_params: HashMap<String, String>,
1281    _scopes: BTreeSet<String>,
1282}
1283
1284impl<'a, C> common::CallBuilder for ProjectLocationActivityTypeActivityQueryCall<'a, C> {}
1285
1286impl<'a, C> ProjectLocationActivityTypeActivityQueryCall<'a, C>
1287where
1288    C: common::Connector,
1289{
1290    /// Perform the operation you have build so far.
1291    pub async fn doit(
1292        mut self,
1293    ) -> common::Result<(
1294        common::Response,
1295        GoogleCloudPolicyanalyzerV1QueryActivityResponse,
1296    )> {
1297        use std::borrow::Cow;
1298        use std::io::{Read, Seek};
1299
1300        use common::{url::Params, ToParts};
1301        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1302
1303        let mut dd = common::DefaultDelegate;
1304        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1305        dlg.begin(common::MethodInfo {
1306            id: "policyanalyzer.projects.locations.activityTypes.activities.query",
1307            http_method: hyper::Method::GET,
1308        });
1309
1310        for &field in ["alt", "parent", "pageToken", "pageSize", "filter"].iter() {
1311            if self._additional_params.contains_key(field) {
1312                dlg.finished(false);
1313                return Err(common::Error::FieldClash(field));
1314            }
1315        }
1316
1317        let mut params = Params::with_capacity(6 + self._additional_params.len());
1318        params.push("parent", self._parent);
1319        if let Some(value) = self._page_token.as_ref() {
1320            params.push("pageToken", value);
1321        }
1322        if let Some(value) = self._page_size.as_ref() {
1323            params.push("pageSize", value.to_string());
1324        }
1325        if let Some(value) = self._filter.as_ref() {
1326            params.push("filter", value);
1327        }
1328
1329        params.extend(self._additional_params.iter());
1330
1331        params.push("alt", "json");
1332        let mut url = self.hub._base_url.clone() + "v1/{+parent}/activities:query";
1333        if self._scopes.is_empty() {
1334            self._scopes
1335                .insert(Scope::CloudPlatform.as_ref().to_string());
1336        }
1337
1338        #[allow(clippy::single_element_loop)]
1339        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
1340            url = params.uri_replacement(url, param_name, find_this, true);
1341        }
1342        {
1343            let to_remove = ["parent"];
1344            params.remove_params(&to_remove);
1345        }
1346
1347        let url = params.parse_with_url(&url);
1348
1349        loop {
1350            let token = match self
1351                .hub
1352                .auth
1353                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1354                .await
1355            {
1356                Ok(token) => token,
1357                Err(e) => match dlg.token(e) {
1358                    Ok(token) => token,
1359                    Err(e) => {
1360                        dlg.finished(false);
1361                        return Err(common::Error::MissingToken(e));
1362                    }
1363                },
1364            };
1365            let mut req_result = {
1366                let client = &self.hub.client;
1367                dlg.pre_request();
1368                let mut req_builder = hyper::Request::builder()
1369                    .method(hyper::Method::GET)
1370                    .uri(url.as_str())
1371                    .header(USER_AGENT, self.hub._user_agent.clone());
1372
1373                if let Some(token) = token.as_ref() {
1374                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1375                }
1376
1377                let request = req_builder
1378                    .header(CONTENT_LENGTH, 0_u64)
1379                    .body(common::to_body::<String>(None));
1380
1381                client.request(request.unwrap()).await
1382            };
1383
1384            match req_result {
1385                Err(err) => {
1386                    if let common::Retry::After(d) = dlg.http_error(&err) {
1387                        sleep(d).await;
1388                        continue;
1389                    }
1390                    dlg.finished(false);
1391                    return Err(common::Error::HttpError(err));
1392                }
1393                Ok(res) => {
1394                    let (mut parts, body) = res.into_parts();
1395                    let mut body = common::Body::new(body);
1396                    if !parts.status.is_success() {
1397                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1398                        let error = serde_json::from_str(&common::to_string(&bytes));
1399                        let response = common::to_response(parts, bytes.into());
1400
1401                        if let common::Retry::After(d) =
1402                            dlg.http_failure(&response, error.as_ref().ok())
1403                        {
1404                            sleep(d).await;
1405                            continue;
1406                        }
1407
1408                        dlg.finished(false);
1409
1410                        return Err(match error {
1411                            Ok(value) => common::Error::BadRequest(value),
1412                            _ => common::Error::Failure(response),
1413                        });
1414                    }
1415                    let response = {
1416                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1417                        let encoded = common::to_string(&bytes);
1418                        match serde_json::from_str(&encoded) {
1419                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1420                            Err(error) => {
1421                                dlg.response_json_decode_error(&encoded, &error);
1422                                return Err(common::Error::JsonDecodeError(
1423                                    encoded.to_string(),
1424                                    error,
1425                                ));
1426                            }
1427                        }
1428                    };
1429
1430                    dlg.finished(true);
1431                    return Ok(response);
1432                }
1433            }
1434        }
1435    }
1436
1437    /// Required. The container resource on which to execute the request. Acceptable formats: `projects/[PROJECT_ID|PROJECT_NUMBER]/locations/[LOCATION]/activityTypes/[ACTIVITY_TYPE]` LOCATION here refers to Google Cloud Locations: https://cloud.google.com/about/locations/
1438    ///
1439    /// Sets the *parent* path property to the given value.
1440    ///
1441    /// Even though the property as already been set when instantiating this call,
1442    /// we provide this method for API completeness.
1443    pub fn parent(
1444        mut self,
1445        new_value: &str,
1446    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C> {
1447        self._parent = new_value.to_string();
1448        self
1449    }
1450    /// Optional. If present, then retrieve the next batch of results from the preceding call to this method. `pageToken` must be the value of `nextPageToken` from the previous response. The values of other method parameters should be identical to those in the previous call.
1451    ///
1452    /// Sets the *page token* query property to the given value.
1453    pub fn page_token(
1454        mut self,
1455        new_value: &str,
1456    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C> {
1457        self._page_token = Some(new_value.to_string());
1458        self
1459    }
1460    /// Optional. The maximum number of results to return from this request. Max limit is 1000. Non-positive values are ignored. The presence of `nextPageToken` in the response indicates that more results might be available.
1461    ///
1462    /// Sets the *page size* query property to the given value.
1463    pub fn page_size(
1464        mut self,
1465        new_value: i32,
1466    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C> {
1467        self._page_size = Some(new_value);
1468        self
1469    }
1470    /// Optional. Filter expression to restrict the activities returned. For serviceAccountLastAuthentication activities, supported filters are: - `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` where `[STRING]` is the full resource name of the service account. For serviceAccountKeyLastAuthentication activities, supported filters are: - `activities.full_resource_name {=} [STRING]` - `activities.fullResourceName {=} [STRING]` where `[STRING]` is the full resource name of the service account key.
1471    ///
1472    /// Sets the *filter* query property to the given value.
1473    pub fn filter(
1474        mut self,
1475        new_value: &str,
1476    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C> {
1477        self._filter = Some(new_value.to_string());
1478        self
1479    }
1480    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1481    /// while executing the actual API request.
1482    ///
1483    /// ````text
1484    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1485    /// ````
1486    ///
1487    /// Sets the *delegate* property to the given value.
1488    pub fn delegate(
1489        mut self,
1490        new_value: &'a mut dyn common::Delegate,
1491    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C> {
1492        self._delegate = Some(new_value);
1493        self
1494    }
1495
1496    /// Set any additional parameter of the query string used in the request.
1497    /// It should be used to set parameters which are not yet available through their own
1498    /// setters.
1499    ///
1500    /// Please note that this method must not be used to set any of the known parameters
1501    /// which have their own setter method. If done anyway, the request will fail.
1502    ///
1503    /// # Additional Parameters
1504    ///
1505    /// * *$.xgafv* (query-string) - V1 error format.
1506    /// * *access_token* (query-string) - OAuth access token.
1507    /// * *alt* (query-string) - Data format for response.
1508    /// * *callback* (query-string) - JSONP
1509    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1510    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1511    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1512    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1513    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1514    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1515    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1516    pub fn param<T>(
1517        mut self,
1518        name: T,
1519        value: T,
1520    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C>
1521    where
1522        T: AsRef<str>,
1523    {
1524        self._additional_params
1525            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1526        self
1527    }
1528
1529    /// Identifies the authorization scope for the method you are building.
1530    ///
1531    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1532    /// [`Scope::CloudPlatform`].
1533    ///
1534    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1535    /// tokens for more than one scope.
1536    ///
1537    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1538    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1539    /// sufficient, a read-write scope will do as well.
1540    pub fn add_scope<St>(mut self, scope: St) -> ProjectLocationActivityTypeActivityQueryCall<'a, C>
1541    where
1542        St: AsRef<str>,
1543    {
1544        self._scopes.insert(String::from(scope.as_ref()));
1545        self
1546    }
1547    /// Identifies the authorization scope(s) for the method you are building.
1548    ///
1549    /// See [`Self::add_scope()`] for details.
1550    pub fn add_scopes<I, St>(
1551        mut self,
1552        scopes: I,
1553    ) -> ProjectLocationActivityTypeActivityQueryCall<'a, C>
1554    where
1555        I: IntoIterator<Item = St>,
1556        St: AsRef<str>,
1557    {
1558        self._scopes
1559            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1560        self
1561    }
1562
1563    /// Removes all scopes, and no default scope will be used either.
1564    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1565    /// for details).
1566    pub fn clear_scopes(mut self) -> ProjectLocationActivityTypeActivityQueryCall<'a, C> {
1567        self._scopes.clear();
1568        self
1569    }
1570}