text:
use std::error::Error;
use std::fmt;

use async_trait::async_trait;
use rusoto_core::credential::ProvideAwsCredentials;
use rusoto_core::region;
use rusoto_core::request::{BufferedHttpResponse, DispatchSignedRequest};
use rusoto_core::{Client, RusotoError};

use rusoto_core::param::{Params, ServiceParams};
use rusoto_core::proto;
use rusoto_core::signature::SignedRequest;
#[allow(unused_imports)]
use serde::{Deserialize, Serialize};
use serde_json;
///
Specifies an action for an event-based policy.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct Action {
    ///
The rule for copying shared snapshots across Regions.

    #[serde(rename = "CrossRegionCopy")]
    pub cross_region_copy: Vec<CrossRegionCopyAction>,
    ///
A descriptive name for the action.

    #[serde(rename = "Name")]
    pub name: String,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct CreateLifecyclePolicyRequest {
    ///
A description of the lifecycle policy. The characters ^[0-9A-Za-z _-]+$ are supported.

    #[serde(rename = "Description")]
    pub description: String,
    ///
The Amazon Resource Name (ARN) of the IAM role used to run the operations specified by the lifecycle policy.

    #[serde(rename = "ExecutionRoleArn")]
    pub execution_role_arn: String,
    ///
The configuration details of the lifecycle policy.

    #[serde(rename = "PolicyDetails")]
    pub policy_details: PolicyDetails,
    ///
The desired activation state of the lifecycle policy after creation.

    #[serde(rename = "State")]
    pub state: String,
    ///
The tags to apply to the lifecycle policy during creation.

    #[serde(rename = "Tags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<::std::collections::HashMap<String, String>>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct CreateLifecyclePolicyResponse {
    ///
The identifier of the lifecycle policy.

    #[serde(rename = "PolicyId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
}

///
Specifies when to create snapshots of EBS volumes.

You must specify either a Cron expression or an interval, interval unit, and start time. You cannot specify both.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct CreateRule {
    ///
The schedule, as a Cron expression. The schedule interval must be between 1 hour and 1 year. For more information, see Cron expressions in the Amazon CloudWatch User Guide.

    #[serde(rename = "CronExpression")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cron_expression: Option<String>,
    ///
The interval between snapshots. The supported values are 1, 2, 3, 4, 6, 8, 12, and 24.

    #[serde(rename = "Interval")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<i64>,
    ///
The interval unit.

    #[serde(rename = "IntervalUnit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_unit: Option<String>,
    ///
Specifies the destination for snapshots created by the policy. To create snapshots in the same Region as the source resource, specify CLOUD. To create snapshots on the same Outpost as the source resource, specify OUTPOST_LOCAL. If you omit this parameter, CLOUD is used by default.

If the policy targets resources in an AWS Region, then you must create snapshots in the same Region as the source resource.

If the policy targets resources on an Outpost, then you can create snapshots on the same Outpost as the source resource, or in the Region of that Outpost.

    #[serde(rename = "Location")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    ///
The time, in UTC, to start the operation. The supported format is hh:mm.

The operation occurs within a one-hour window following the specified time. If you do not specify a time, Amazon DLM selects a time within the next 24 hours.

    #[serde(rename = "Times")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub times: Option<Vec<String>>,
}

///
Specifies a rule for copying shared snapshots across Regions.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct CrossRegionCopyAction {
    ///
The encryption settings for the copied snapshot.

    #[serde(rename = "EncryptionConfiguration")]
    pub encryption_configuration: EncryptionConfiguration,
    #[serde(rename = "RetainRule")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retain_rule: Option<CrossRegionCopyRetainRule>,
    ///
The target Region.

    #[serde(rename = "Target")]
    pub target: String,
}

///
Specifies the retention rule for cross-Region snapshot copies.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct CrossRegionCopyRetainRule {
    ///
The amount of time to retain each snapshot. The maximum is 100 years. This is equivalent to 1200 months, 5200 weeks, or 36500 days.

    #[serde(rename = "Interval")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<i64>,
    ///
The unit of time for time-based retention.

    #[serde(rename = "IntervalUnit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_unit: Option<String>,
}

///
Specifies a rule for cross-Region snapshot copies.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct CrossRegionCopyRule {
    ///
The Amazon Resource Name (ARN) of the AWS KMS customer master key (CMK) to use for EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used.

    #[serde(rename = "CmkArn")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cmk_arn: Option<String>,
    ///
Copy all user-defined tags from the source snapshot to the copied snapshot.

    #[serde(rename = "CopyTags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub copy_tags: Option<bool>,
    ///
To encrypt a copy of an unencrypted snapshot if encryption by default is not enabled, enable encryption using this parameter. Copies of encrypted snapshots are encrypted, even if this parameter is false or if encryption by default is not enabled.

    #[serde(rename = "Encrypted")]
    pub encrypted: bool,
    ///
The retention rule.

    #[serde(rename = "RetainRule")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retain_rule: Option<CrossRegionCopyRetainRule>,
    ///
The Amazon Resource Name (ARN) of the target AWS Outpost for the snapshot copies.

If you specify an ARN, you must omit TargetRegion. You cannot specify a target Region and a target Outpost in the same rule.

    #[serde(rename = "Target")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    ///
The target Region for the snapshot copies.

If you specify a target Region, you must omit Target. You cannot specify a target Region and a target Outpost in the same rule.

    #[serde(rename = "TargetRegion")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_region: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct DeleteLifecyclePolicyRequest {
    ///
The identifier of the lifecycle policy.

    #[serde(rename = "PolicyId")]
    pub policy_id: String,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct DeleteLifecyclePolicyResponse {}

///
Specifies the encryption settings for shared snapshots that are copied across Regions.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct EncryptionConfiguration {
    ///
The Amazon Resource Name (ARN) of the AWS KMS customer master key (CMK) to use for EBS encryption. If this parameter is not specified, your AWS managed CMK for EBS is used.

    #[serde(rename = "CmkArn")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cmk_arn: Option<String>,
    ///
To encrypt a copy of an unencrypted snapshot when encryption by default is not enabled, enable encryption using this parameter. Copies of encrypted snapshots are encrypted, even if this parameter is false or when encryption by default is not enabled.

    #[serde(rename = "Encrypted")]
    pub encrypted: bool,
}

///
Specifies an event that triggers an event-based policy.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct EventParameters {
    ///
The snapshot description that can trigger the policy. The description pattern is specified using a regular expression. The policy runs only if a snapshot with a description that matches the specified pattern is shared with your account.

For example, specifying ^.*Created for policy: policy-1234567890abcdef0.*$ configures the policy to run only if snapshots created by policy policy-1234567890abcdef0 are shared with your account.

    #[serde(rename = "DescriptionRegex")]
    pub description_regex: String,
    ///
The type of event. Currently, only snapshot sharing events are supported.

    #[serde(rename = "EventType")]
    pub event_type: String,
    ///
The IDs of the AWS accounts that can trigger policy by sharing snapshots with your account. The policy only runs if one of the specified AWS accounts shares a snapshot with your account.

    #[serde(rename = "SnapshotOwner")]
    pub snapshot_owner: Vec<String>,
}

///
Specifies an event that triggers an event-based policy.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct EventSource {
    ///
Information about the event.

    #[serde(rename = "Parameters")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<EventParameters>,
    ///
The source of the event. Currently only managed AWS CloudWatch Events rules are supported.

    #[serde(rename = "Type")]
    pub type_: String,
}

///
Specifies a rule for enabling fast snapshot restore. You can enable fast snapshot restore based on either a count or a time interval.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct FastRestoreRule {
    ///
The Availability Zones in which to enable fast snapshot restore.

    #[serde(rename = "AvailabilityZones")]
    pub availability_zones: Vec<String>,
    ///
The number of snapshots to be enabled with fast snapshot restore.

    #[serde(rename = "Count")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<i64>,
    ///
The amount of time to enable fast snapshot restore. The maximum is 100 years. This is equivalent to 1200 months, 5200 weeks, or 36500 days.

    #[serde(rename = "Interval")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<i64>,
    ///
The unit of time for enabling fast snapshot restore.

    #[serde(rename = "IntervalUnit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_unit: Option<String>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct GetLifecyclePoliciesRequest {
    ///
The identifiers of the data lifecycle policies.

    #[serde(rename = "PolicyIds")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_ids: Option<Vec<String>>,
    ///
The resource type.

    #[serde(rename = "ResourceTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_types: Option<Vec<String>>,
    ///
The activation state.

    #[serde(rename = "State")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    ///
The tags to add to objects created by the policy.

Tags are strings in the format key=value.

These user-defined tags are added in addition to the AWS-added lifecycle tags.

    #[serde(rename = "TagsToAdd")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags_to_add: Option<Vec<String>>,
    ///
The target tag for a policy.

Tags are strings in the format key=value.

    #[serde(rename = "TargetTags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_tags: Option<Vec<String>>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct GetLifecyclePoliciesResponse {
    ///
Summary information about the lifecycle policies.

    #[serde(rename = "Policies")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policies: Option<Vec<LifecyclePolicySummary>>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct GetLifecyclePolicyRequest {
    ///
The identifier of the lifecycle policy.

    #[serde(rename = "PolicyId")]
    pub policy_id: String,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct GetLifecyclePolicyResponse {
    ///
Detailed information about the lifecycle policy.

    #[serde(rename = "Policy")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<LifecyclePolicy>,
}

///
Detailed information about a lifecycle policy.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct LifecyclePolicy {
    ///
The local date and time when the lifecycle policy was created.

    #[serde(rename = "DateCreated")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date_created: Option<f64>,
    ///
The local date and time when the lifecycle policy was last modified.

    #[serde(rename = "DateModified")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date_modified: Option<f64>,
    ///
The description of the lifecycle policy.

    #[serde(rename = "Description")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    ///
The Amazon Resource Name (ARN) of the IAM role used to run the operations specified by the lifecycle policy.

    #[serde(rename = "ExecutionRoleArn")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_role_arn: Option<String>,
    ///
The Amazon Resource Name (ARN) of the policy.

    #[serde(rename = "PolicyArn")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_arn: Option<String>,
    ///
The configuration of the lifecycle policy

    #[serde(rename = "PolicyDetails")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_details: Option<PolicyDetails>,
    ///
The identifier of the lifecycle policy.

    #[serde(rename = "PolicyId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
    ///
The activation state of the lifecycle policy.

    #[serde(rename = "State")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    ///
The description of the status.

    #[serde(rename = "StatusMessage")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_message: Option<String>,
    ///
The tags.

    #[serde(rename = "Tags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<::std::collections::HashMap<String, String>>,
}

///
Summary information about a lifecycle policy.

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct LifecyclePolicySummary {
    ///
The description of the lifecycle policy.

    #[serde(rename = "Description")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    ///
The identifier of the lifecycle policy.

    #[serde(rename = "PolicyId")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_id: Option<String>,
    ///
The type of policy. EBS_SNAPSHOT_MANAGEMENT indicates that the policy manages the lifecycle of Amazon EBS snapshots. IMAGE_MANAGEMENT indicates that the policy manages the lifecycle of EBS-backed AMIs.

    #[serde(rename = "PolicyType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_type: Option<String>,
    ///
The activation state of the lifecycle policy.

    #[serde(rename = "State")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
    ///
The tags.

    #[serde(rename = "Tags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<::std::collections::HashMap<String, String>>,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct ListTagsForResourceRequest {
    ///
The Amazon Resource Name (ARN) of the resource.

    #[serde(rename = "ResourceArn")]
    pub resource_arn: String,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct ListTagsForResourceResponse {
    ///
Information about the tags.

    #[serde(rename = "Tags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<::std::collections::HashMap<String, String>>,
}

///
Specifies optional parameters to add to a policy. The set of valid parameters depends on the combination of policy type and resource type.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct Parameters {
    ///
[EBS Snapshot Management – Instance policies only] Indicates whether to exclude the root volume from snapshots created using CreateSnapshots. The default is false.

    #[serde(rename = "ExcludeBootVolume")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exclude_boot_volume: Option<bool>,
    ///
Applies to AMI lifecycle policies only. Indicates whether targeted instances are rebooted when the lifecycle policy runs. true indicates that targeted instances are not rebooted when the policy runs. false indicates that target instances are rebooted when the policy runs. The default is true (instances are not rebooted).

    #[serde(rename = "NoReboot")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub no_reboot: Option<bool>,
}

///
Specifies the configuration of a lifecycle policy.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct PolicyDetails {
    ///
The actions to be performed when the event-based policy is triggered. You can specify only one action per policy.

This parameter is required for event-based policies only. If you are creating a snapshot or AMI policy, omit this parameter.

    #[serde(rename = "Actions")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actions: Option<Vec<Action>>,
    ///
The event that triggers the event-based policy.

This parameter is required for event-based policies only. If you are creating a snapshot or AMI policy, omit this parameter.

    #[serde(rename = "EventSource")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub event_source: Option<EventSource>,
    ///
A set of optional parameters for snapshot and AMI lifecycle policies.

This parameter is required for snapshot and AMI policies only. If you are creating an event-based policy, omit this parameter.

    #[serde(rename = "Parameters")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub parameters: Option<Parameters>,
    ///
The valid target resource types and actions a policy can manage. Specify EBS_SNAPSHOT_MANAGEMENT to create a lifecycle policy that manages the lifecycle of Amazon EBS snapshots. Specify IMAGE_MANAGEMENT to create a lifecycle policy that manages the lifecycle of EBS-backed AMIs. Specify EVENT_BASED_POLICY  to create an event-based policy that performs specific actions when a defined event occurs in your AWS account.

The default is EBS_SNAPSHOT_MANAGEMENT.

    #[serde(rename = "PolicyType")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_type: Option<String>,
    ///
The location of the resources to backup. If the source resources are located in an AWS Region, specify CLOUD. If the source resources are located on an AWS Outpost in your account, specify OUTPOST.

If you specify OUTPOST, Amazon Data Lifecycle Manager backs up all resources of the specified type with matching target tags across all of the Outposts in your account.

    #[serde(rename = "ResourceLocations")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_locations: Option<Vec<String>>,
    ///
The target resource type for snapshot and AMI lifecycle policies. Use VOLUME to create snapshots of individual volumes or use INSTANCE to create multi-volume snapshots from the volumes for an instance.

This parameter is required for snapshot and AMI policies only. If you are creating an event-based policy, omit this parameter.

    #[serde(rename = "ResourceTypes")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resource_types: Option<Vec<String>>,
    ///
The schedules of policy-defined actions for snapshot and AMI lifecycle policies. A policy can have up to four schedules—one mandatory schedule and up to three optional schedules.

This parameter is required for snapshot and AMI policies only. If you are creating an event-based policy, omit this parameter.

    #[serde(rename = "Schedules")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schedules: Option<Vec<Schedule>>,
    ///
The single tag that identifies targeted resources for this policy.

This parameter is required for snapshot and AMI policies only. If you are creating an event-based policy, omit this parameter.

    #[serde(rename = "TargetTags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target_tags: Option<Vec<Tag>>,
}

///
Specifies the retention rule for a lifecycle policy. You can retain snapshots based on either a count or a time interval.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct RetainRule {
    ///
The number of snapshots to retain for each volume, up to a maximum of 1000.

    #[serde(rename = "Count")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub count: Option<i64>,
    ///
The amount of time to retain each snapshot. The maximum is 100 years. This is equivalent to 1200 months, 5200 weeks, or 36500 days.

    #[serde(rename = "Interval")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval: Option<i64>,
    ///
The unit of time for time-based retention.

    #[serde(rename = "IntervalUnit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interval_unit: Option<String>,
}

///
Specifies a backup schedule for a snapshot or AMI lifecycle policy.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct Schedule {
    ///
Copy all user-defined tags on a source volume to snapshots of the volume created by this policy.

    #[serde(rename = "CopyTags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub copy_tags: Option<bool>,
    ///
The creation rule.

    #[serde(rename = "CreateRule")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create_rule: Option<CreateRule>,
    ///
The rule for cross-Region snapshot copies.

You can only specify cross-Region copy rules for policies that create snapshots in a Region. If the policy creates snapshots on an Outpost, then you cannot copy the snapshots to a Region or to an Outpost. If the policy creates snapshots in a Region, then snapshots can be copied to up to three Regions or Outposts.

    #[serde(rename = "CrossRegionCopyRules")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cross_region_copy_rules: Option<Vec<CrossRegionCopyRule>>,
    ///
The rule for enabling fast snapshot restore.

    #[serde(rename = "FastRestoreRule")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub fast_restore_rule: Option<FastRestoreRule>,
    ///
The name of the schedule.

    #[serde(rename = "Name")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    ///
The retention rule.

    #[serde(rename = "RetainRule")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub retain_rule: Option<RetainRule>,
    ///
The rule for sharing snapshots with other AWS accounts.

    #[serde(rename = "ShareRules")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub share_rules: Option<Vec<ShareRule>>,
    ///
The tags to apply to policy-created resources. These user-defined tags are in addition to the AWS-added lifecycle tags.

    #[serde(rename = "TagsToAdd")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags_to_add: Option<Vec<Tag>>,
    ///
A collection of key/value pairs with values determined dynamically when the policy is executed. Keys may be any valid Amazon EC2 tag key. Values must be in one of the two following formats: $(instance-id) or $(timestamp). Variable tags are only valid for EBS Snapshot Management – Instance policies.

    #[serde(rename = "VariableTags")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variable_tags: Option<Vec<Tag>>,
}

///
Specifies a rule for sharing snapshots across AWS accounts.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct ShareRule {
    ///
The IDs of the AWS accounts with which to share the snapshots.

    #[serde(rename = "TargetAccounts")]
    pub target_accounts: Vec<String>,
    ///
The period after which snapshots that are shared with other AWS accounts are automatically unshared.

    #[serde(rename = "UnshareInterval")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unshare_interval: Option<i64>,
    ///
The unit of time for the automatic unsharing interval.

    #[serde(rename = "UnshareIntervalUnit")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unshare_interval_unit: Option<String>,
}

///
Specifies a tag for a resource.

#[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)]
pub struct Tag {
    ///
The tag key.

    #[serde(rename = "Key")]
    pub key: String,
    ///
The tag value.

    #[serde(rename = "Value")]
    pub value: String,
}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct TagResourceRequest {
    ///
The Amazon Resource Name (ARN) of the resource.

    #[serde(rename = "ResourceArn")]
    pub resource_arn: String,
    ///
One or more tags.

    #[serde(rename = "Tags")]
    pub tags: ::std::collections::HashMap<String, String>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct TagResourceResponse {}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct UntagResourceRequest {
    ///
The Amazon Resource Name (ARN) of the resource.

    #[serde(rename = "ResourceArn")]
    pub resource_arn: String,
    ///
The tag keys.

    #[serde(rename = "TagKeys")]
    pub tag_keys: Vec<String>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct UntagResourceResponse {}

#[derive(Clone, Debug, Default, PartialEq, Serialize)]
#[cfg_attr(feature = "deserialize_structs", derive(Deserialize))]
pub struct UpdateLifecyclePolicyRequest {
    ///
A description of the lifecycle policy.

    #[serde(rename = "Description")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    ///
The Amazon Resource Name (ARN) of the IAM role used to run the operations specified by the lifecycle policy.

    #[serde(rename = "ExecutionRoleArn")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution_role_arn: Option<String>,
    ///
The configuration of the lifecycle policy. You cannot update the policy type or the resource type.

    #[serde(rename = "PolicyDetails")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy_details: Option<PolicyDetails>,
    ///
The identifier of the lifecycle policy.

    #[serde(rename = "PolicyId")]
    pub policy_id: String,
    ///
The desired activation state of the lifecycle policy after creation.

    #[serde(rename = "State")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub state: Option<String>,
}

#[derive(Clone, Debug, Default, Deserialize, PartialEq)]
#[cfg_attr(any(test, feature = "serialize_structs"), derive(Serialize))]
pub struct UpdateLifecyclePolicyResponse {}

/// Errors returned by CreateLifecyclePolicy
#[derive(Debug, PartialEq)]
pub enum CreateLifecyclePolicyError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
Bad request. The request is missing required parameters or has invalid parameters.

    InvalidRequest(String),
    ///
The request failed because a limit was exceeded.

    LimitExceeded(String),
}

impl CreateLifecyclePolicyError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<CreateLifecyclePolicyError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(CreateLifecyclePolicyError::InternalServer(
                        err.msg,
                    ))
                }
                "InvalidRequestException" => {
                    return RusotoError::Service(CreateLifecyclePolicyError::InvalidRequest(
                        err.msg,
                    ))
                }
                "LimitExceededException" => {
                    return RusotoError::Service(CreateLifecyclePolicyError::LimitExceeded(err.msg))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for CreateLifecyclePolicyError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            CreateLifecyclePolicyError::InternalServer(ref cause) => write!(f, "{}", cause),
            CreateLifecyclePolicyError::InvalidRequest(ref cause) => write!(f, "{}", cause),
            CreateLifecyclePolicyError::LimitExceeded(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for CreateLifecyclePolicyError {}
/// Errors returned by DeleteLifecyclePolicy
#[derive(Debug, PartialEq)]
pub enum DeleteLifecyclePolicyError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
The request failed because a limit was exceeded.

    LimitExceeded(String),
    ///
A requested resource was not found.

    ResourceNotFound(String),
}

impl DeleteLifecyclePolicyError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<DeleteLifecyclePolicyError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(DeleteLifecyclePolicyError::InternalServer(
                        err.msg,
                    ))
                }
                "LimitExceededException" => {
                    return RusotoError::Service(DeleteLifecyclePolicyError::LimitExceeded(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(DeleteLifecyclePolicyError::ResourceNotFound(
                        err.msg,
                    ))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for DeleteLifecyclePolicyError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            DeleteLifecyclePolicyError::InternalServer(ref cause) => write!(f, "{}", cause),
            DeleteLifecyclePolicyError::LimitExceeded(ref cause) => write!(f, "{}", cause),
            DeleteLifecyclePolicyError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for DeleteLifecyclePolicyError {}
/// Errors returned by GetLifecyclePolicies
#[derive(Debug, PartialEq)]
pub enum GetLifecyclePoliciesError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
Bad request. The request is missing required parameters or has invalid parameters.

    InvalidRequest(String),
    ///
The request failed because a limit was exceeded.

    LimitExceeded(String),
    ///
A requested resource was not found.

    ResourceNotFound(String),
}

impl GetLifecyclePoliciesError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetLifecyclePoliciesError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(GetLifecyclePoliciesError::InternalServer(err.msg))
                }
                "InvalidRequestException" => {
                    return RusotoError::Service(GetLifecyclePoliciesError::InvalidRequest(err.msg))
                }
                "LimitExceededException" => {
                    return RusotoError::Service(GetLifecyclePoliciesError::LimitExceeded(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(GetLifecyclePoliciesError::ResourceNotFound(
                        err.msg,
                    ))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for GetLifecyclePoliciesError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GetLifecyclePoliciesError::InternalServer(ref cause) => write!(f, "{}", cause),
            GetLifecyclePoliciesError::InvalidRequest(ref cause) => write!(f, "{}", cause),
            GetLifecyclePoliciesError::LimitExceeded(ref cause) => write!(f, "{}", cause),
            GetLifecyclePoliciesError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for GetLifecyclePoliciesError {}
/// Errors returned by GetLifecyclePolicy
#[derive(Debug, PartialEq)]
pub enum GetLifecyclePolicyError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
The request failed because a limit was exceeded.

    LimitExceeded(String),
    ///
A requested resource was not found.

    ResourceNotFound(String),
}

impl GetLifecyclePolicyError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<GetLifecyclePolicyError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(GetLifecyclePolicyError::InternalServer(err.msg))
                }
                "LimitExceededException" => {
                    return RusotoError::Service(GetLifecyclePolicyError::LimitExceeded(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(GetLifecyclePolicyError::ResourceNotFound(err.msg))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for GetLifecyclePolicyError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            GetLifecyclePolicyError::InternalServer(ref cause) => write!(f, "{}", cause),
            GetLifecyclePolicyError::LimitExceeded(ref cause) => write!(f, "{}", cause),
            GetLifecyclePolicyError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for GetLifecyclePolicyError {}
/// Errors returned by ListTagsForResource
#[derive(Debug, PartialEq)]
pub enum ListTagsForResourceError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
Bad request. The request is missing required parameters or has invalid parameters.

    InvalidRequest(String),
    ///
A requested resource was not found.

    ResourceNotFound(String),
}

impl ListTagsForResourceError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<ListTagsForResourceError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(ListTagsForResourceError::InternalServer(err.msg))
                }
                "InvalidRequestException" => {
                    return RusotoError::Service(ListTagsForResourceError::InvalidRequest(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(ListTagsForResourceError::ResourceNotFound(
                        err.msg,
                    ))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for ListTagsForResourceError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            ListTagsForResourceError::InternalServer(ref cause) => write!(f, "{}", cause),
            ListTagsForResourceError::InvalidRequest(ref cause) => write!(f, "{}", cause),
            ListTagsForResourceError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for ListTagsForResourceError {}
/// Errors returned by TagResource
#[derive(Debug, PartialEq)]
pub enum TagResourceError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
Bad request. The request is missing required parameters or has invalid parameters.

    InvalidRequest(String),
    ///
A requested resource was not found.

    ResourceNotFound(String),
}

impl TagResourceError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<TagResourceError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(TagResourceError::InternalServer(err.msg))
                }
                "InvalidRequestException" => {
                    return RusotoError::Service(TagResourceError::InvalidRequest(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(TagResourceError::ResourceNotFound(err.msg))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for TagResourceError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            TagResourceError::InternalServer(ref cause) => write!(f, "{}", cause),
            TagResourceError::InvalidRequest(ref cause) => write!(f, "{}", cause),
            TagResourceError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for TagResourceError {}
/// Errors returned by UntagResource
#[derive(Debug, PartialEq)]
pub enum UntagResourceError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
Bad request. The request is missing required parameters or has invalid parameters.

    InvalidRequest(String),
    ///
A requested resource was not found.

    ResourceNotFound(String),
}

impl UntagResourceError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UntagResourceError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(UntagResourceError::InternalServer(err.msg))
                }
                "InvalidRequestException" => {
                    return RusotoError::Service(UntagResourceError::InvalidRequest(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(UntagResourceError::ResourceNotFound(err.msg))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for UntagResourceError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            UntagResourceError::InternalServer(ref cause) => write!(f, "{}", cause),
            UntagResourceError::InvalidRequest(ref cause) => write!(f, "{}", cause),
            UntagResourceError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for UntagResourceError {}
/// Errors returned by UpdateLifecyclePolicy
#[derive(Debug, PartialEq)]
pub enum UpdateLifecyclePolicyError {
    ///
The service failed in an unexpected way.

    InternalServer(String),
    ///
Bad request. The request is missing required parameters or has invalid parameters.

    InvalidRequest(String),
    ///
The request failed because a limit was exceeded.

    LimitExceeded(String),
    ///
A requested resource was not found.

    ResourceNotFound(String),
}

impl UpdateLifecyclePolicyError {
    pub fn from_response(res: BufferedHttpResponse) -> RusotoError<UpdateLifecyclePolicyError> {
        if let Some(err) = proto::json::Error::parse_rest(&res) {
            match err.typ.as_str() {
                "InternalServerException" => {
                    return RusotoError::Service(UpdateLifecyclePolicyError::InternalServer(
                        err.msg,
                    ))
                }
                "InvalidRequestException" => {
                    return RusotoError::Service(UpdateLifecyclePolicyError::InvalidRequest(
                        err.msg,
                    ))
                }
                "LimitExceededException" => {
                    return RusotoError::Service(UpdateLifecyclePolicyError::LimitExceeded(err.msg))
                }
                "ResourceNotFoundException" => {
                    return RusotoError::Service(UpdateLifecyclePolicyError::ResourceNotFound(
                        err.msg,
                    ))
                }
                "ValidationException" => return RusotoError::Validation(err.msg),
                _ => {}
            }
        }
        RusotoError::Unknown(res)
    }
}
impl fmt::Display for UpdateLifecyclePolicyError {
    #[allow(unused_variables)]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            UpdateLifecyclePolicyError::InternalServer(ref cause) => write!(f, "{}", cause),
            UpdateLifecyclePolicyError::InvalidRequest(ref cause) => write!(f, "{}", cause),
            UpdateLifecyclePolicyError::LimitExceeded(ref cause) => write!(f, "{}", cause),
            UpdateLifecyclePolicyError::ResourceNotFound(ref cause) => write!(f, "{}", cause),
        }
    }
}
impl Error for UpdateLifecyclePolicyError {}
/// Trait representing the capabilities of the Amazon DLM API. Amazon DLM clients implement this trait.
#[async_trait]
pub trait Dlm {
    ///
Creates a policy to manage the lifecycle of the specified AWS resources. You can create up to 100 lifecycle policies.

    async fn create_lifecycle_policy(
        &self,
        input: CreateLifecyclePolicyRequest,
    ) -> Result<CreateLifecyclePolicyResponse, RusotoError<CreateLifecyclePolicyError>>;

    ///
Deletes the specified lifecycle policy and halts the automated operations that the policy specified.

    async fn delete_lifecycle_policy(
        &self,
        input: DeleteLifecyclePolicyRequest,
    ) -> Result<DeleteLifecyclePolicyResponse, RusotoError<DeleteLifecyclePolicyError>>;

    ///
Gets summary information about all or the specified data lifecycle policies.

To get complete information about a policy, use GetLifecyclePolicy.

    async fn get_lifecycle_policies(
        &self,
        input: GetLifecyclePoliciesRequest,
    ) -> Result<GetLifecyclePoliciesResponse, RusotoError<GetLifecyclePoliciesError>>;

    ///
Gets detailed information about the specified lifecycle policy.

    async fn get_lifecycle_policy(
        &self,
        input: GetLifecyclePolicyRequest,
    ) -> Result<GetLifecyclePolicyResponse, RusotoError<GetLifecyclePolicyError>>;

    ///
Lists the tags for the specified resource.

    async fn list_tags_for_resource(
        &self,
        input: ListTagsForResourceRequest,
    ) -> Result<ListTagsForResourceResponse, RusotoError<ListTagsForResourceError>>;

    ///
Adds the specified tags to the specified resource.

    async fn tag_resource(
        &self,
        input: TagResourceRequest,
    ) -> Result<TagResourceResponse, RusotoError<TagResourceError>>;

    ///
Removes the specified tags from the specified resource.

    async fn untag_resource(
        &self,
        input: UntagResourceRequest,
    ) -> Result<UntagResourceResponse, RusotoError<UntagResourceError>>;

    ///
Updates the specified lifecycle policy.

    async fn update_lifecycle_policy(
        &self,
        input: UpdateLifecyclePolicyRequest,
    ) -> Result<UpdateLifecyclePolicyResponse, RusotoError<UpdateLifecyclePolicyError>>;
}
/// A client for the Amazon DLM API.
#[derive(Clone)]
pub struct DlmClient {
    client: Client,
    region: region::Region,
}

impl DlmClient {
    /// Creates a client backed by the default tokio event loop.
    ///
    /// The client will use the default credentials provider and tls client.
    pub fn new(region: region::Region) -> DlmClient {
        DlmClient {
            client: Client::shared(),
            region,
        }
    }

    pub fn new_with
(
        request_dispatcher: D,
        credentials_provider: P,
        region: region::Region,
    ) -> DlmClient
    where
        P: ProvideAwsCredentials + Send + Sync + 'static,
        D: DispatchSignedRequest + Send + Sync + 'static,
    {
        DlmClient {
            client: Client::new_with(credentials_provider, request_dispatcher),
            region,
        }
    }

    pub fn new_with_client(client: Client, region: region::Region) -> DlmClient {
        DlmClient { client, region }
    }
}

#[async_trait]
impl Dlm for DlmClient {
    ///
Creates a policy to manage the lifecycle of the specified AWS resources. You can create up to 100 lifecycle policies.

    #[allow(unused_mut)]
    async fn create_lifecycle_policy(
        &self,
        input: CreateLifecyclePolicyRequest,
    ) -> Result<CreateLifecyclePolicyResponse, RusotoError<CreateLifecyclePolicyError>> {
        let request_uri = "/policies";

        let mut request = SignedRequest::new("POST", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<CreateLifecyclePolicyResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(CreateLifecyclePolicyError::from_response(response))
        }
    }

    ///
Deletes the specified lifecycle policy and halts the automated operations that the policy specified.

    #[allow(unused_mut)]
    async fn delete_lifecycle_policy(
        &self,
        input: DeleteLifecyclePolicyRequest,
    ) -> Result<DeleteLifecyclePolicyResponse, RusotoError<DeleteLifecyclePolicyError>> {
        let request_uri = format!("/policies/{policy_id}/", policy_id = input.policy_id);

        let mut request = SignedRequest::new("DELETE", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<DeleteLifecyclePolicyResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(DeleteLifecyclePolicyError::from_response(response))
        }
    }

    ///
Gets summary information about all or the specified data lifecycle policies.

To get complete information about a policy, use GetLifecyclePolicy.

    #[allow(unused_mut)]
    async fn get_lifecycle_policies(
        &self,
        input: GetLifecyclePoliciesRequest,
    ) -> Result<GetLifecyclePoliciesResponse, RusotoError<GetLifecyclePoliciesError>> {
        let request_uri = "/policies";

        let mut request = SignedRequest::new("GET", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let mut params = Params::new();
        if let Some(ref x) = input.policy_ids {
            for item in x.iter() {
                params.put("policyIds", item);
            }
        }
        if let Some(ref x) = input.resource_types {
            for item in x.iter() {
                params.put("resourceTypes", item);
            }
        }
        if let Some(ref x) = input.state {
            params.put("state", x);
        }
        if let Some(ref x) = input.tags_to_add {
            for item in x.iter() {
                params.put("tagsToAdd", item);
            }
        }
        if let Some(ref x) = input.target_tags {
            for item in x.iter() {
                params.put("targetTags", item);
            }
        }
        request.set_params(params);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<GetLifecyclePoliciesResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(GetLifecyclePoliciesError::from_response(response))
        }
    }

    ///
Gets detailed information about the specified lifecycle policy.

    #[allow(unused_mut)]
    async fn get_lifecycle_policy(
        &self,
        input: GetLifecyclePolicyRequest,
    ) -> Result<GetLifecyclePolicyResponse, RusotoError<GetLifecyclePolicyError>> {
        let request_uri = format!("/policies/{policy_id}/", policy_id = input.policy_id);

        let mut request = SignedRequest::new("GET", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<GetLifecyclePolicyResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(GetLifecyclePolicyError::from_response(response))
        }
    }

    ///
Lists the tags for the specified resource.

    #[allow(unused_mut)]
    async fn list_tags_for_resource(
        &self,
        input: ListTagsForResourceRequest,
    ) -> Result<ListTagsForResourceResponse, RusotoError<ListTagsForResourceError>> {
        let request_uri = format!("/tags/{resource_arn}", resource_arn = input.resource_arn);

        let mut request = SignedRequest::new("GET", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<ListTagsForResourceResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(ListTagsForResourceError::from_response(response))
        }
    }

    ///
Adds the specified tags to the specified resource.

    #[allow(unused_mut)]
    async fn tag_resource(
        &self,
        input: TagResourceRequest,
    ) -> Result<TagResourceResponse, RusotoError<TagResourceError>> {
        let request_uri = format!("/tags/{resource_arn}", resource_arn = input.resource_arn);

        let mut request = SignedRequest::new("POST", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<TagResourceResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(TagResourceError::from_response(response))
        }
    }

    ///
Removes the specified tags from the specified resource.

    #[allow(unused_mut)]
    async fn untag_resource(
        &self,
        input: UntagResourceRequest,
    ) -> Result<UntagResourceResponse, RusotoError<UntagResourceError>> {
        let request_uri = format!("/tags/{resource_arn}", resource_arn = input.resource_arn);

        let mut request = SignedRequest::new("DELETE", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let mut params = Params::new();
        for item in input.tag_keys.iter() {
            params.put("tagKeys", item);
        }
        request.set_params(params);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<UntagResourceResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(UntagResourceError::from_response(response))
        }
    }

    ///
Updates the specified lifecycle policy.

    #[allow(unused_mut)]
    async fn update_lifecycle_policy(
        &self,
        input: UpdateLifecyclePolicyRequest,
    ) -> Result<UpdateLifecyclePolicyResponse, RusotoError<UpdateLifecyclePolicyError>> {
        let request_uri = format!("/policies/{policy_id}", policy_id = input.policy_id);

        let mut request = SignedRequest::new("PATCH", "dlm", &self.region, &request_uri);
        request.set_content_type("application/x-amz-json-1.1".to_owned());

        let encoded = Some(serde_json::to_vec(&input).unwrap());
        request.set_payload(encoded);

        let mut response = self
            .client
            .sign_and_dispatch(request)
            .await
            .map_err(RusotoError::from)?;
        if response.status.is_success() {
            let mut response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            let result = proto::json::ResponsePayload::new(&response)
                .deserialize::<UpdateLifecyclePolicyResponse, _>()?;

            Ok(result)
        } else {
            let response = response.buffer().await.map_err(RusotoError::HttpDispatch)?;
            Err(UpdateLifecyclePolicyError::from_response(response))
        }
    }
}


text:
#include "gl_replay.h"
#include "serialise/rdcfile.h"
#include "gl_driver.h"
#include "gl_resources.h"

PFNWGLCREATECONTEXTATTRIBSARBPROC createContextAttribs = NULL;
PFNWGLGETPIXELFORMATATTRIBIVARBPROC getPixelFormatAttrib = NULL;

typedef PROC(WINAPI *WGLGETPROCADDRESSPROC)(const char *);
typedef HGLRC(WINAPI *WGLCREATECONTEXTPROC)(HDC);
typedef BOOL(WINAPI *WGLMAKECURRENTPROC)(HDC, HGLRC);
typedef BOOL(WINAPI *WGLDELETECONTEXTPROC)(HGLRC);

WGLGETPROCADDRESSPROC wglGetProc = NULL;
WGLCREATECONTEXTPROC wglCreateRC = NULL;
WGLMAKECURRENTPROC wglMakeCurrentProc = NULL;
WGLDELETECONTEXTPROC wglDeleteRC = NULL;

ReplayStatus GL_CreateReplayDevice(RDCFile *rdc, IReplayDriver **driver)
{
  RDCDEBUG("Creating an OpenGL replay device");

  HMODULE lib = NULL;
  lib = LoadLibraryA("opengl32.dll");
  if(lib == NULL)
  {
    RDCERR("Failed to load opengl32.dll");
    return ReplayStatus::APIInitFailed;
  }

  GLInitParams initParams;
  uint64_t ver = GLInitParams::CurrentVersion;

  // if we have an RDCFile, open the frame capture section and serialise the init params.
  // if not, we're creating a proxy-capable device so use default-initialised init params.
  if(rdc)
  {
    int sectionIdx = rdc->SectionIndex(SectionType::FrameCapture);

    if(sectionIdx < 0)
      return ReplayStatus::InternalError;

    ver = rdc->GetSectionProperties(sectionIdx).version;

    if(!GLInitParams::IsSupportedVersion(ver))
    {
      RDCERR("Incompatible OpenGL serialise version %llu", ver);
      return ReplayStatus::APIIncompatibleVersion;
    }

    StreamReader *reader = rdc->ReadSection(sectionIdx);

    ReadSerialiser ser(reader, Ownership::Stream);

    SystemChunk chunk = ser.ReadChunk<SystemChunk>();

    if(chunk != SystemChunk::DriverInit)
    {
      RDCERR("Expected to get a DriverInit chunk, instead got %u", chunk);
      return ReplayStatus::FileCorrupted;
    }

    SERIALISE_ELEMENT(initParams);

    if(ser.IsErrored())
    {
      RDCERR("Failed reading driver init params.");
      return ReplayStatus::FileIOFailed;
    }
  }

  PIXELFORMATDESCRIPTOR pfd = {0};

  if(wglGetProc == NULL)
  {
    wglGetProc = (WGLGETPROCADDRESSPROC)GetProcAddress(lib, "wglGetProcAddress");
    wglCreateRC = (WGLCREATECONTEXTPROC)GetProcAddress(lib, "wglCreateContext");
    wglMakeCurrentProc = (WGLMAKECURRENTPROC)GetProcAddress(lib, "wglMakeCurrent");
    wglDeleteRC = (WGLDELETECONTEXTPROC)GetProcAddress(lib, "wglDeleteContext");

    if(wglGetProc == NULL || wglCreateRC == NULL || wglMakeCurrentProc == NULL || wglDeleteRC == NULL)
    {
      RDCERR("Couldn't get wgl function addresses");
      return ReplayStatus::APIInitFailed;
    }

    WNDCLASSEX wc;
    RDCEraseEl(wc);
    wc.style = CS_OWNDC;
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.lpfnWndProc = DefWindowProc;
    wc.hInstance = GetModuleHandle(NULL);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.lpszClassName = L"renderdocGLclass";

    if(!RegisterClassEx(&wc))
    {
      RDCERR("Couldn't register GL window class");
      return ReplayStatus::APIInitFailed;
    }

    RDCEraseEl(pfd);
    pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
    pfd.nVersion = 1;
    pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
    pfd.iLayerType = PFD_MAIN_PLANE;
    pfd.iPixelType = PFD_TYPE_RGBA;
    pfd.cColorBits = 32;
    pfd.cDepthBits = 24;
    pfd.cStencilBits = 0;
  }

  HWND w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"", WS_OVERLAPPEDWINDOW,
                          CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
                          GetModuleHandle(NULL), NULL);

  HDC dc = GetDC(w);

  int pf = ChoosePixelFormat(dc, &pfd);
  if(pf == 0)
  {
    RDCERR("Couldn't choose pixel format");
    return ReplayStatus::APIInitFailed;
  }

  BOOL res = SetPixelFormat(dc, pf, &pfd);
  if(res == FALSE)
  {
    RDCERR("Couldn't set pixel format");
    return ReplayStatus::APIInitFailed;
  }

  HGLRC rc = wglCreateRC(dc);
  if(rc == NULL)
  {
    RDCERR("Couldn't create simple RC");
    return ReplayStatus::APIInitFailed;
  }

  res = wglMakeCurrentProc(dc, rc);
  if(res == FALSE)
  {
    RDCERR("Couldn't make simple RC current");
    return ReplayStatus::APIInitFailed;
  }

  createContextAttribs =
      (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProc("wglCreateContextAttribsARB");
  getPixelFormatAttrib =
      (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProc("wglGetPixelFormatAttribivARB");

  if(createContextAttribs == NULL || getPixelFormatAttrib == NULL)
  {
    RDCERR("RenderDoc requires WGL_ARB_create_context and WGL_ARB_pixel_format");
    return ReplayStatus::APIHardwareUnsupported;
  }

  wglMakeCurrentProc(NULL, NULL);
  wglDeleteRC(rc);
  ReleaseDC(w, dc);
  DestroyWindow(w);

  GLReplay::PreContextInitCounters();

  // we don't use the default framebuffer (backbuffer) for anything, so we make it
  // tiny and with no depth/stencil bits
  pfd.iPixelType = PFD_TYPE_RGBA;
  pfd.cColorBits = 24;
  pfd.cDepthBits = 0;
  pfd.cStencilBits = 0;

  w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"RenderDoc replay window",
                     WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 32, 32, NULL, NULL,
                     GetModuleHandle(NULL), NULL);

  dc = GetDC(w);

  pf = ChoosePixelFormat(dc, &pfd);
  if(pf == 0)
  {
    RDCERR("Couldn't choose pixel format");
    ReleaseDC(w, dc);
    GLReplay::PostContextShutdownCounters();
    return ReplayStatus::APIInitFailed;
  }

  res = SetPixelFormat(dc, pf, &pfd);
  if(res == FALSE)
  {
    RDCERR("Couldn't set pixel format");
    ReleaseDC(w, dc);
    GLReplay::PostContextShutdownCounters();
    return ReplayStatus::APIInitFailed;
  }

  int attribs[64] = {0};
  int i = 0;

  attribs[i++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
  int &major = attribs[i];
  attribs[i++] = 0;
  attribs[i++] = WGL_CONTEXT_MINOR_VERSION_ARB;
  int &minor = attribs[i];
  attribs[i++] = 0;
  attribs[i++] = WGL_CONTEXT_FLAGS_ARB;
#if ENABLED(RDOC_DEVEL)
  attribs[i++] = WGL_CONTEXT_DEBUG_BIT_ARB;
#else
  attribs[i++] = 0;
#endif
  attribs[i++] = WGL_CONTEXT_PROFILE_MASK_ARB;
  attribs[i++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;

  // try to create all versions from 4.5 down to 3.2 in order to get the
  // highest versioned context we can
  struct
  {
    int major;
    int minor;
  } versions[] = {
      {4, 5}, {4, 4}, {4, 3}, {4, 2}, {4, 1}, {4, 0}, {3, 3}, {3, 2},
  };

  rc = NULL;

  for(size_t v = 0; v < ARRAY_COUNT(versions); v++)
  {
    major = versions[v].major;
    minor = versions[v].minor;
    rc = createContextAttribs(dc, NULL, attribs);

    if(rc)
      break;
  }
  if(rc == NULL)
  {
    RDCERR("Couldn't create 3.2 RC - RenderDoc requires OpenGL 3.2 availability");
    ReleaseDC(w, dc);
    GLReplay::PostContextShutdownCounters();
    return ReplayStatus::APIHardwareUnsupported;
  }

  GLCoreVersion = major * 10 + minor;

  res = wglMakeCurrentProc(dc, rc);
  if(res == FALSE)
  {
    RDCERR("Couldn't make 3.2 RC current");
    wglMakeCurrentProc(NULL, NULL);
    wglDeleteRC(rc);
    ReleaseDC(w, dc);
    GLReplay::PostContextShutdownCounters();
    return ReplayStatus::APIInitFailed;
  }

  PFNGLGETINTEGERVPROC getInt = (PFNGLGETINTEGERVPROC)GetProcAddress(lib, "glGetIntegerv");
  PFNGLGETSTRINGPROC getStr = (PFNGLGETSTRINGPROC)GetProcAddress(lib, "glGetString");
  PFNGLGETSTRINGIPROC getStri = (PFNGLGETSTRINGIPROC)wglGetProc("glGetStringi");

  if(getInt == NULL || getStr == NULL || getStri == NULL)
  {
    RDCERR("Couldn't get glGetIntegerv (%p), glGetString (%p) or glGetStringi (%p) entry points",
           getInt, getStr, getStri);
    wglMakeCurrentProc(NULL, NULL);
    wglDeleteRC(rc);
    ReleaseDC(w, dc);
    GLReplay::PostContextShutdownCounters();
    return ReplayStatus::APIInitFailed;
  }

  bool missingExt = CheckReplayContext(getStr, getInt, getStri);

  if(missingExt)
  {
    wglMakeCurrentProc(NULL, NULL);
    wglDeleteRC(rc);
    ReleaseDC(w, dc);
    GLReplay::PostContextShutdownCounters();
    return ReplayStatus::APIInitFailed;
  }

  const GLHookSet &real = GetRealGLFunctions();

  bool extensionsValidated = ValidateFunctionPointers(real);

  if(!extensionsValidated)
  {
    wglMakeCurrentProc(NULL, NULL);
    wglDeleteRC(rc);
    ReleaseDC(w, dc);
    GLReplay::PostContextShutdownCounters();
    return ReplayStatus::APIInitFailed;
  }

  WrappedOpenGL *gl = new WrappedOpenGL(real, GetGLPlatform());
  gl->Initialise(initParams, ver);

  RDCLOG("Created device.");
  GLReplay *replay = gl->GetReplay();
  replay->SetProxy(rdc == NULL);
  GLWindowingData data;
  data.DC = dc;
  data.ctx = rc;
  data.wnd = w;
  replay->SetReplayData(data);

  *driver = (IReplayDriver *)replay;
  return ReplayStatus::Succeeded;
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

<title>PaymentWithPayPalServlet</title>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport"
	content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">
<meta name="groc-relative-root" content="">
<meta name="groc-document-path" content="PaymentWithPayPalServlet">
<meta name="groc-project-path" content="PaymentWithPayPalServlet.java">
<link rel="stylesheet" type="text/css" media="all"
	href="assets/style.css">

Back

					¶

Create Payment
						Using PayPal Sample

This sample code demonstrates how you can process a PayPal
						Account based Payment. API used: /v1/payments/payment

					package com.paypal.api.payments.servlet;

					import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.paypal.api.payments.Amount; import com.paypal.api.payments.Details; import com.paypal.api.payments.Links; import com.paypal.api.payments.Payer; import com.paypal.api.payments.Payment; import com.paypal.api.payments.PaymentExecution; import com.paypal.api.payments.RedirectUrls; import com.paypal.api.payments.Transaction; import com.paypal.api.payments.util.GenerateAccessToken; import com.paypal.core.rest.APIContext; import com.paypal.core.rest.PayPalRESTException; import com.paypal.core.rest.PayPalResource; /**
						* @author lvairamani  *
						*/ public class PaymentWithPayPalServlet extends
					HttpServlet { private static final long serialVersionUID = 1L; private
					static final Logger LOGGER = Logger .getLogger(PaymentWithPayPalServlet.class);
					Map<String, String> map =
					new HashMap<String,
					String>(); public void init(ServletConfig
					servletConfig) throws ServletException {

					¶

Load Configuration

Load SDK configuration for the resource. This intialization
						code can be done as Init Servlet.

					InputStream is = PaymentWithPayPalServlet.class .getResourceAsStream("/sdk_config.properties");
					try { PayPalResource.initConfig(is);
					} catch (PayPalRESTException e) {
					LOGGER.fatal(e.getMessage()); } }

					@Override protected
					void doGet(HttpServletRequest req, HttpServletResponse
					resp) throws ServletException, IOException { doPost(req, resp); }

					¶

Create

Sample showing to create a Payment using PayPal

					@Override protected
					void doPost(HttpServletRequest req, HttpServletResponse
					resp) throws ServletException, IOException {

					¶

AccessToken

Retrieve the access token from OAuthTokenCredential by
						passing in ClientID and ClientSecret

					APIContext apiContext
					= null; String accessToken
					= null; try {
					accessToken = GenerateAccessToken.getAccessToken();

					¶

Api Context

						Pass in a
						ApiContext
						object to authenticate the call and to send a unique request id
						(that ensures idempotency). The SDK generates a request id if you
						do not pass one explicitly.

					apiContext = new APIContext(accessToken);

					¶

Use this variant if you want to pass in a request id that is
						meaningful in your application, ideally a order id.

					/*  * String
						requestId = Long.toString(System.nanoTime(); APIContext  * apiContext = new APIContext(accessToken,
						requestId ));  */ }
					catch (PayPalRESTException e) { req.setAttribute("error", e.getMessage()); } if (req.getParameter("PayerID") != null) { Payment
					payment = new Payment();
					if (req.getParameter("guid") != null) { payment.setId(map.get(req.getParameter("guid"))); } PaymentExecution paymentExecution = new PaymentExecution(); paymentExecution.setPayerId(req.getParameter("PayerID")); try { payment.execute(apiContext, paymentExecution); req.setAttribute("response", Payment.getLastResponse()); } catch (PayPalRESTException e) { req.setAttribute("error", e.getMessage()); } } else
					{

					¶

Details

Let's you specify details of a payment amount.

					Details details = new Details(); details.setShipping("1"); details.setSubtotal("5"); details.setTax("1");

					¶

Amount

Let's you specify a payment amount.

					Amount amount = new Amount(); amount.setCurrency("USD");

					¶

Total must be equal to sum of shipping, tax and subtotal.

					amount.setTotal("7"); amount.setDetails(details);

					¶

Transaction

						A transaction defines the contract of a payment - what is the
						payment for and who is fulfilling it. Transaction is created with
						a
						Payee
						and
						Amount
						types

					Transaction transaction
					= new Transaction(); transaction.setAmount(amount); transaction
					.setDescription("This is the payment
						transaction description.");

					¶

						The Payment creation API requires a list of Transaction; add the
						created
						Transaction
						to a List

					List<Transaction> transactions = new ArrayList<Transaction>(); transactions.add(transaction);

					¶

Payer

A resource representing a Payer that funds a payment Payment
						Method as 'paypal'

					Payer payer = new Payer(); payer.setPaymentMethod("paypal");

					¶

Payment

A Payment Resource; create one using the above types and
						intent as 'sale'

					Payment payment = new Payment(); payment.setIntent("sale"); payment.setPayer(payer); payment.setTransactions(transactions);

					¶

Redirect URLs

					RedirectUrls redirectUrls
					= new RedirectUrls(); String guid
					= UUID.randomUUID().toString().replaceAll("-", ""); redirectUrls.setCancelUrl(req.getScheme() + "://"
					+ req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/paymentwithpaypal?guid="
					+ guid);
					redirectUrls.setReturnUrl(req.getScheme() + "://"
					+ req.getServerName() + ":" + req.getServerPort() + req.getContextPath() + "/paymentwithpaypal?guid="
					+ guid);
					payment.setRedirectUrls(redirectUrls);

					¶

Create a payment by posting to the APIService using a valid
						AccessToken The return object contains the status;

					try { Payment
					createdPayment = payment.create(apiContext);
					LOGGER.info("Created
						payment with id = " + createdPayment.getId()
					+ " and status =
						" + createdPayment.getState());

					¶

Payment Approval Url

					Iterator<Links> links
					= createdPayment.getLinks().iterator(); while (links.hasNext())
					{ Links link = links.next();
					if (link.getRel().equalsIgnoreCase("approval_url"))
					{ req.setAttribute("redirectURL", link.getHref()); } }
					req.setAttribute("response", Payment.getLastResponse()); map.put(guid,
					createdPayment.getId()); }
					catch (PayPalRESTException e) { req.setAttribute("error", e.getMessage()); } } req.setAttribute("request", Payment.getLastRequest()); req.getRequestDispatcher("response.jsp").forward(req, resp); } }

				Back


text:
<?php

namespace Google\Service\CloudIdentity;

class ListUserInvitationsResponse extends \Google\Collection
{
  protected $collection_key = 'userInvitations';
  /**
   * @var string
   */
  public $nextPageToken;
  protected $userInvitationsType = UserInvitation::class;
  protected $userInvitationsDataType = 'array';

  /**
   * @param string
   */
  public function setNextPageToken($nextPageToken)
  {
    $this->nextPageToken = $nextPageToken;
  }
  /**
   * @return string
   */
  public function getNextPageToken()
  {
    return $this->nextPageToken;
  }
  /**
   * @param UserInvitation[]
   */
  public function setUserInvitations($userInvitations)
  {
    $this->userInvitations = $userInvitations;
  }
  /**
   * @return UserInvitation[]
   */
  public function getUserInvitations()
  {
    return $this->userInvitations;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ListUserInvitationsResponse::class, 'Google_Service_CloudIdentity_ListUserInvitationsResponse');


text:
{% extends 'email/base.html' %}
            {% block content %}

Precisamos do seu Feedback.

Oi, você se cadastrou na vaga de voluntariado {{project_name}}

Então, clique no botão abaixo e conta para a gente, rapidinho, como foi.

                Conte-nos sobre sua experiência!

Valeu, hoje era só isso mesmo ;)

As suas respostas vão ajudar muito a gente a melhorar nossos serviços e mobilizar cada vez mais pessoas como você!

            {% endblock content %}


text:
package com.jetbrains.python.codeInsight.testIntegration;

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
import com.intellij.testIntegration.TestCreator;
import com.intellij.util.IncorrectOperationException;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.codeInsight.imports.AddImportHelper;
import com.jetbrains.python.psi.*;
import org.jetbrains.annotations.NotNull;

import java.util.List;

/**
 * User: catherine
 */
public class PyTestCreator implements TestCreator {
  private static final Logger LOG = Logger.getInstance("#com.jetbrains.python.codeInsight.testIntegration.PyTestCreator");

  @Override
  public boolean isAvailable(Project project, Editor editor, PsiFile file) {
    CreateTestAction action = new CreateTestAction();
    PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
    if (element != null) {
      return action.isAvailable(project, editor, element);
    }
    return false;
  }

  @Override
  public void createTest(Project project, Editor editor, PsiFile file) {
    try {
      CreateTestAction action = new CreateTestAction();
      PsiElement element = file.findElementAt(editor.getCaretModel().getOffset());
      if (action.isAvailable(project, editor, element)) {
        action.invoke(project, editor, file.getContainingFile());
      }
    }
    catch (IncorrectOperationException e) {
      LOG.warn(e);
    }
  }

  /**
   * Generates test, puts it into file and navigates to newly created class
   *
   * @return file with test
   */
  static PsiFile generateTestAndNavigate(@NotNull final Project project, @NotNull final CreateTestDialog dialog) {
    return PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Computable<PsiFile>() {
      public PsiFile compute() {
        return ApplicationManager.getApplication().runWriteAction(new Computable<PsiFile>() {
          public PsiFile compute() {
            try {
              final PyElement testClass = generateTest(project, dialog);
              testClass.navigate(false);
              return testClass.getContainingFile();
            }
            catch (IncorrectOperationException e) {
              LOG.warn(e);
              return null;
            }
          }
        });
      }
    });
  }

  /**
   * Generates test, puts it into file and returns class element for test
   *
   * @return newly created test class
   */
  @NotNull
  static PyElement generateTest(@NotNull final Project project, @NotNull final CreateTestDialog dialog) {
    IdeDocumentHistory.getInstance(project).includeCurrentPlaceAsChangePlace();

    String fileName = dialog.getFileName();
    if (!fileName.endsWith(".py")) {
      fileName = fileName + "." + PythonFileType.INSTANCE.getDefaultExtension();
    }

    StringBuilder fileText = new StringBuilder();
    fileText.append("class ").append(dialog.getClassName()).append("(TestCase):\n\t");
    List<String> methods = dialog.getMethods();
    if (methods.size() == 0) {
      fileText.append("pass\n");
    }

    for (String method : methods) {
      fileText.append("def ").append(method).append("(self):\n\tself.fail()\n\n\t");
    }

    PsiFile psiFile = PyUtil.getOrCreateFile(
      dialog.getTargetDir() + "/" + fileName, project);
    AddImportHelper.addOrUpdateFromImportStatement(psiFile, "unittest", "TestCase", null, AddImportHelper.ImportPriority.BUILTIN,
                                                   null);

    PyElement createdClass = PyElementGenerator.getInstance(project).createFromText(
      LanguageLevel.forElement(psiFile), PyClass.class, fileText.toString());
    createdClass = (PyElement)psiFile.addAfter(createdClass, psiFile.getLastChild());

    PostprocessReformattingAspect.getInstance(project).doPostponedFormatting(psiFile.getViewProvider());
    CodeStyleManager.getInstance(project).reformat(psiFile);
    return createdClass;
  }
}


text:
<!DOCTYPE refentry [ <!ENTITY % mathent SYSTEM "math.ent"> %mathent; ]>

<!-- Converted by db4-upgrade version 1.1 -->

<refentry xmlns="http://docbook.org/ns/docbook" version="5.0" xml:id="glGetUniform">
    <info>
    <copyright>
      <year>2003-2005</year>

      <holder>3Dlabs Inc. Ltd.</holder>
    </copyright>

    <copyright>
      <year>2010-2014</year>

      <holder>Khronos Group</holder>
    </copyright>
  </info>

  <refmeta>
    <refentrytitle>glGetUniform</refentrytitle>

    <manvolnum>3G</manvolnum>
  </refmeta>

  <refnamediv>
    <refdescriptor>glGetUniform</refdescriptor>

    <refname>glGetUniformfv</refname>

    <refname>glGetUniformiv</refname>

    <refpurpose>Returns the value of a uniform variable</refpurpose>
  </refnamediv>

  <refsynopsisdiv>
    <title>C Specification</title>

    <funcsynopsis>
      <funcprototype>
        <funcdef>void <function>glGetUniformfv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLfloat *<parameter>params</parameter></paramdef>
      </funcprototype>

      <funcprototype>
        <funcdef>void <function>glGetUniformiv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLint *<parameter>params</parameter></paramdef>
      </funcprototype>

      <funcprototype>
        <funcdef>void <function>glGetUniformuiv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLuint *<parameter>params</parameter></paramdef>
      </funcprototype>

      <funcprototype>
        <funcdef>void <function>glGetUniformdv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLdouble *<parameter>params</parameter></paramdef>
      </funcprototype>

      <!-- robustness commands -->

      <funcprototype>
        <funcdef>void <function>glGetnUniformfv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLsizei <parameter>bufSize</parameter></paramdef>

        <paramdef>GLfloat *<parameter>params</parameter></paramdef>
      </funcprototype>

      <funcprototype>
        <funcdef>void <function>glGetnUniformiv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLsizei <parameter>bufSize</parameter></paramdef>

        <paramdef>GLint *<parameter>params</parameter></paramdef>
      </funcprototype>

      <funcprototype>
        <funcdef>void <function>glGetnUniformuiv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLsizei <parameter>bufSize</parameter></paramdef>

        <paramdef>GLuint *<parameter>params</parameter></paramdef>
      </funcprototype>

      <funcprototype>
        <funcdef>void <function>glGetnUniformdv</function></funcdef>

        <paramdef>GLuint <parameter>program</parameter></paramdef>

        <paramdef>GLint <parameter>location</parameter></paramdef>

        <paramdef>GLsizei <parameter>bufSize</parameter></paramdef>

        <paramdef>GLdouble *<parameter>params</parameter></paramdef>
      </funcprototype>
    </funcsynopsis>
  </refsynopsisdiv>

  <refsect1 xml:id="parameters">
    <title>Parameters</title>

    <variablelist>
      <varlistentry>
        <term><parameter>program</parameter></term>

        <listitem>
          <para>Specifies the program object to be queried.</para>
        </listitem>
      </varlistentry>

      <varlistentry>
        <term><parameter>location</parameter></term>

        <listitem>
          <para>Specifies the location of the uniform variable to be
          queried.</para>
        </listitem>
      </varlistentry>

      <varlistentry>
        <term><parameter>bufSize</parameter></term>

        <listitem>
          <para>Specifies the size of the buffer
          <parameter>params</parameter>.</para>
        </listitem>
      </varlistentry>

      <varlistentry>
        <term><parameter>params</parameter></term>

        <listitem>
          <para>Returns the value of the specified uniform variable.</para>
        </listitem>
      </varlistentry>
    </variablelist>
  </refsect1>

  <refsect1 xml:id="description">
    <title>Description</title>

    <para><function>glGetUniform</function> and
    <function>glGetnUniform</function> return in <parameter>params</parameter>
    the value(s) of the specified uniform variable. The type of the uniform
    variable specified by <parameter>location</parameter> determines the
    number of values returned. If the uniform variable is defined in the
    shader as a boolean, int, or float, a single value will be returned. If it
    is defined as a vec2, ivec2, or bvec2, two values will be returned. If it
    is defined as a vec3, ivec3, or bvec3, three values will be returned, and
    so on. To query values stored in uniform variables declared as arrays,
    call <function>glGetUniform</function> for each element of the array. To
    query values stored in uniform variables declared as structures, call
    <function>glGetUniform</function> for each field in the structure. The
    values for uniform variables declared as a matrix will be returned in
    column major order.</para>

    <para>The locations assigned to uniform variables are not known until the
    program object is linked. After linking has occurred, the command
    <citerefentry><refentrytitle>glGetUniformLocation</refentrytitle></citerefentry>
    can be used to obtain the location of a uniform variable. This location
    value can then be passed to <function>glGetUniform</function> or
    <function>glGetnUniform</function> in order to query the current value
    of the uniform variable. After a program object has been linked
    successfully, the index values for uniform variables remain fixed until
    the next link command occurs. The uniform variable values can only be
    queried after a link if the link was successful.</para>

    <para>The only difference between <function>glGetUniform</function> and
    <function>glGetnUniform</function> is that
    <function>glGetnUniform</function> will generate an error if size of the
    <parameter>params</parameter> buffer,as described by
    <parameter>bufSize</parameter>, is not large enough to hold the result
    data.</para>
  </refsect1>

  <refsect1 xml:id="notes">
    <title>Notes</title>

    <para>If an error is generated, no change is made to the contents of
    <parameter>params</parameter>.</para>
  </refsect1>

  <refsect1 xml:id="errors">
    <title>Errors</title>

    <para><constant>GL_INVALID_VALUE</constant> is generated if
    <parameter>program</parameter> is not a value generated by OpenGL.</para>

    <para><constant>GL_INVALID_OPERATION</constant> is generated if
    <parameter>program</parameter> is not a program object.</para>

    <para><constant>GL_INVALID_OPERATION</constant> is generated if
    <parameter>program</parameter> has not been successfully linked.</para>

    <para><constant>GL_INVALID_OPERATION</constant> is generated if
    <parameter>location</parameter> does not correspond to a valid uniform
    variable location for the specified program object.</para>

    <para><constant>GL_INVALID_OPERATION</constant> is generated by
    <function>glGetnUniform</function> if the buffer size required to store
    the requested data is greater than <parameter>bufSize</parameter>.</para>
  </refsect1>

  <refsect1 xml:id="associatedgets">
    <title>Associated Gets</title>

    <para><citerefentry><refentrytitle>glGetActiveUniform</refentrytitle></citerefentry>
    with arguments <parameter>program</parameter> and the index of an active
    uniform variable</para>

    <para><citerefentry><refentrytitle>glGetProgram</refentrytitle></citerefentry>
    with arguments <parameter>program</parameter> and
    <constant>GL_ACTIVE_UNIFORMS</constant> or
    <constant>GL_ACTIVE_UNIFORM_MAX_LENGTH</constant></para>

    <para><citerefentry><refentrytitle>glGetUniformLocation</refentrytitle></citerefentry>
    with arguments <parameter>program</parameter> and the name of a uniform
    variable</para>

    <para><citerefentry><refentrytitle>glIsProgram</refentrytitle></citerefentry></para>

  </refsect1>
    <refsect1 xml:id="versions"><title>Version Support</title>
        <informaltable>
            <tgroup cols="13" align="left">
                <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apifunchead.xml" xpointer="xpointer(/*/*)"/>
                <tbody>
                    <row>
                        <entry><function>glGetUniformdv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='40']/*)"/>
                    </row>
                    <row>
                        <entry><function>glGetUniformfv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='20']/*)"/>
                    </row>
                    <row>
                        <entry><function>glGetUniformiv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='20']/*)"/>
                    </row>
                    <row>
                        <entry><function>glGetUniformuiv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='30']/*)"/>
                    </row>
                    <row>
                        <entry><function>glGetnUniformdv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='45']/*)"/>
                    </row>
                    <row>
                        <entry><function>glGetnUniformfv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='45']/*)"/>
                    </row>
                    <row>
                        <entry><function>glGetnUniformiv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='45']/*)"/>
                    </row>
                    <row>
                        <entry><function>glGetnUniformuiv</function></entry>
                        <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" href="apiversion.xml" xpointer="xpointer(/*/*[@role='45']/*)"/>
                    </row>
                </tbody>
            </tgroup>
        </informaltable>
    </refsect1>
    <refsect1 xml:id="seealso"><title>See Also</title>
    <para><citerefentry><refentrytitle>glCreateProgram</refentrytitle></citerefentry>,
    <citerefentry><refentrytitle>glLinkProgram</refentrytitle></citerefentry>,
    <citerefentry><refentrytitle>glUniform</refentrytitle></citerefentry></para>
    </refsect1>
    <refsect1 xml:id="Copyright"><title>Copyright</title>
        <para>
            Copyright <trademark class="copyright"/> 2003-2005 3Dlabs Inc. Ltd.
            Copyright <trademark class="copyright"/> 2010-2014 Khronos Group.
            This material may be distributed subject to the terms and conditions set forth in
            the Open Publication License, v 1.0, 8 June 1999.
            <link xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://opencontent.org/openpub/">http://opencontent.org/openpub/</link>.
        </para>
    </refsect1>
</refentry>


text:
.. EN-Revision: none
.. _zend.view.helpers.initial.headscript:

Помощник HeadScript Helper
==========================

HTML-элемент *<script>* используется для добавления скриптового
кода, исполняемого на клиентской стороне, как непосредственно
в документ, так и через ссылки на удаленные ресурсы, содержащие
этот код. Помощник *HeadScript* позволяет использовать оба способа
включения.

Помощник *HeadScript* поддерживает следующие методы для установки и
добавления скриптов:

- *appendFile($src, $type = 'text/javascript', $attrs = array())*

- *offsetSetFile($index, $src, $type = 'text/javascript', $attrs = array())*

- *prependFile($src, $type = 'text/javascript', $attrs = array())*

- *setFile($src, $type = 'text/javascript', $attrs = array())*

- *appendScript($script, $type = 'text/javascript', $attrs = array())*

- *offsetSetScript($index, $script, $type = 'text/javascript', $attrs = array())*

- *prependScript($script, $type = 'text/javascript', $attrs = array())*

- *setScript($script, $type = 'text/javascript', $attrs = array())*

В методах **File()* через параметр ``$src`` указывается
местоположение скрипта, который требуется загрузить; обычно
оно указывется в виде URL или пути к нему. В методах **Script()* через
параметр ``$script`` передается скриптовый код, который требуется
включить в элемент *<script>*.

.. note::

   **Установка условных комментариев**

   *HeadScript* поддерживает включение тега в условные комментарии с
   тем, чтобы скрыть его от определенных браузеров. Для того,
   чтобы добавить условные теги, передавайте условие через
   параметр ``$attrs`` в вызове метода, как показано в примере:

   .. _zend.view.helpers.initial.headscript.conditional:

   .. rubric:: Скрипты с условными комментариями

   .. code-block:: php
      :linenos:

      // добавление скриптов
      $this->headScript()->appendFile(
          '/js/prototype.js',
          'text/javascript',
          array('conditional' => 'lt IE 7')
      );

*HeadScript* также позволяет "захватывать" вывод скриптов; это может
быть полезным при создании скриптов программным способом.
Пример использования этой возможности будут показан ниже.

Для быстрого добавления скриптовых элементов Вы можете
использовать метод *headScript()*, сигнатура этого метода -*headScript($mode =
'FILE', $spec, $placement = 'APPEND')*. Параметр ``$mode`` может иметь значение 'FILE'
или 'SCRIPT', в зависимости от того, ссылаетесь ли вы на уже
существующий скрипт или передаете код для влючения в элемент
*<script>*. ``$spec`` содержит либо путь к файлу, к которому нужно
добавить ссылку, либо сам скриптовый код. ``$placement`` должен иметь
одно из следующих значений: 'APPEND', 'PREPEND' или 'SET'.

*HeadScript* перегружает методы *append()*, *offsetSet()*, *prepend()* и *set()* с целью
принудительного использования специальных методов,
перечисленных выше. Внутри себя помощник сохраняет каждый
элемент в виде маркера *stdClass*, который затем преобразовывается
в строку через метод *itemToString()*. Это позволяет производить
проверку элементов в стеке и при необходимости модифицировать
их, просто извлекая объект и изменяя его.

Помощник *HeadScript* является частной реализацией :ref:`помощника
Placeholder <zend.view.helpers.initial.placeholder>`.

.. note::

   **Используйте InlineScript для скриптов в теле документа**

   Для добавления скриптов внутри HTML-элемента *body* должен
   использоваться родственный помощник :ref:`InlineScript
   <zend.view.helpers.initial.inlinescript>`. Помещение скриптов в конец документа
   является хорошей практикой для повышения скорости отдачи
   страницы, особенно если используются сторонние
   скрипты-аналитики.

.. note::

   **Установка произвольных атрибутов по умолчанию отключена**

   По умолчанию *HeadScript* будет генерировать только атрибуты,
   соответствующие спецификации W3C. В список этих атрибутов
   входят 'type', 'charset', 'defer', 'language' и 'src'. Однако некоторые JavaScript
   фреймворки, а в особенности `Dojo`_, используют специальные
   атрибуты в целях изменения поведения. Вы можете разрешить
   использование таких атрибутов, воспользовавшись методом
   *setAllowArbitraryAttributes()*:

   .. code-block:: php
      :linenos:

      $this->headScript()->setAllowArbitraryAttributes(true);

.. _zend.view.helpers.initial.headscript.basicusage:

.. rubric:: Использование помощника HeadScript

Вы можете указывать скрипты для добавления в документ в любой
момент времени. Как было указано ранее, это могут быть как
ссылки на файлы со скриптами, так и сами скрипты.

.. code-block:: php
   :linenos:

   // добавление скриптов
   $this->headScript()->appendFile('/js/prototype.js')
                      ->appendScript($onloadScript);

Порядок следования часто важен в скриптах, интерпретируемых
на стороне клиента - например, нужно быть уверенным в том, что
библиотеки загружаются в порядке, обусловленном
зависимостями между ними. В этом случае используйте
специальные методы методы для добавления в начало, конец, и по
определенному смещению:

.. code-block:: php
   :linenos:

   // Размещение скриптов в определенном порядке

   // Добавление по определенному смещению
   $this->headScript()->offsetSetFile(100, '/js/myfuncs.js');

   // Используем эффекты из библиотеки script.aculo.us
   // (будет добавлена с использованием следующего смещения, 101)
   $this->headScript()->appendFile('/js/scriptaculous.js');

   // Но скрипт prototype всегда должен загружаться первым:
   $this->headScript()->prependFile('/js/prototype.js');

Когда все будет готово для размещения скриптов в макете,
просто "выводите" помощника:

.. code-block:: php
   :linenos:

   <?php echo $this->headScript() ?>

.. _zend.view.helpers.initial.headscript.capture:

.. rubric:: Составление скриптов с использованием помощника HeadScript

Иногда нужно генерировать скрипты программым способом. Хотя
вы можете использовать конкатенацию строк, синтаксис heredoc и
т.п., часто бывает легче создать скрипт с включением PHP-тегов.
*HeadScript* позволяет делать это, захватывая вывод в стек:

.. code-block:: php
   :linenos:

   <?php $this->headScript()->captureStart() ?>
   var action = '<?php echo $this->baseUrl ?>';
   $('foo_form').action = action;
   <?php $this->headScript()->captureEnd() ?>

Используются следующие допущения:

- Скрипт будет добавлен в конец стека. Если требуется
  переопределить содержимое стека или добавить скрипт в конец
  стека, то передавайте соответственно 'SET' или 'PREPEND' в качестве
  первого аргумента *captureStart()*.

- По умолчанию предполагается, что MIME-тип скрипта - 'text/javascript'.
  Если требуется указать другой тип скрипта, то передавайте его
  в качестве второго аргумента *captureStart()*.

- Если вы хотите указать какие-либо дополнительные аргументы
  для тега *<script>*, то передавайте их в массиве в качестве
  третьего аргумента *captureStart()*.

.. _`Dojo`: http://www.dojotoolkit.org/