Example of how to enable Bucket Policy Only for a bucket
357448
public Bucket enableBucketPolicyOnly(String bucketName) throws StorageException {
    // [START storage_enable_bucket_policy_only]
    // Instantiate a Google Cloud Storage client
    Storage storage = StorageOptions.getDefaultInstance().getService();

    // The name of a bucket, e.g. "my-bucket"
    // String bucketName = "my-bucket";

    BucketInfo.IamConfiguration iamConfiguration =
        BucketInfo.IamConfiguration.newBuilder().setIsBucketPolicyOnlyEnabled(true).build();
    Bucket bucket =
        storage.update(
            BucketInfo.newBuilder(bucketName).setIamConfiguration(iamConfiguration).build());

    System.out.println("Bucket Policy Only was enabled for " + bucketName);
    // [END storage_enable_bucket_policy_only]
    return bucket;
  }
228441
def default_bucket_link_factory(pid):
    """"""
    try:
        record = Record.get_record(pid.get_assigned_object())
        bucket = record.files.bucket

        return url_for('invenio_files_rest.bucket_api',
                       bucket_id=bucket.id, _external=True)
    except AttributeError:
        return None
1083182
def delete(bucket, path=None, action=None, key=None, keyid=None,
           service_url=None, verify_ssl=None, kms_keyid=None, location=None,
           role_arn=None, path_style=None, https_enable=None):
    '''
    
    '''
    key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable = _get_key(
        key,
        keyid,
        service_url,
        verify_ssl,
        kms_keyid,
        location,
        role_arn,
        path_style,
        https_enable,
    )

    return __utils__['s3.query'](method='DELETE',
                                 bucket=bucket,
                                 path=path,
                                 action=action,
                                 key=key,
                                 keyid=keyid,
                                 kms_keyid=kms_keyid,
                                 service_url=service_url,
                                 verify_ssl=verify_ssl,
                                 location=location,
                                 role_arn=role_arn,
                                 path_style=path_style,
                                 https_enable=https_enable)
136889
def head_bucket(self, name):
        
        try:
            self.s3.head_bucket(Bucket=name)
            info = self.s3.get_bucket_website(Bucket=self.sitename)
            if not info:
                return False, 404, "Configure improrperly"
            return True, None, None
        except botocore.exceptions.ClientError as e:
            if e.response["Error"]["Code"] in ["403", "404"]:
                return False, e.response["Error"]["Code"], e.response["Error"]["Message"]
            else:
                raise e
883085
def stop_s3_bucket(client, resource):
    

    bucket_policy = {
        'Version': '2012-10-17',
        'Id': 'PutObjPolicy',
        'Statement': [
            {
                'Sid': 'cinqDenyObjectUploads',
                'Effect': 'Deny',
                'Principal': '*',
                'Action': ['s3:PutObject', 's3:GetObject'],
                'Resource': 'arn:aws:s3:::{}/*'.format(resource.id)
            }
        ]
    }

    s3_removal_lifecycle_policy = {
        'Rules': [
            {'Status': 'Enabled',
             'NoncurrentVersionExpiration': {u'NoncurrentDays': 1},
             'Filter': {u'Prefix': ''},
             'Expiration': {
                 u'Date': datetime.utcnow().replace(
                     hour=0, minute=0, second=0, microsecond=0
                 ) + timedelta(days=dbconfig.get('lifecycle_expiration_days', NS_AUDITOR_REQUIRED_TAGS, 3))
             },
             'AbortIncompleteMultipartUpload': {u'DaysAfterInitiation': 3},
             'ID': 'cloudInquisitor'}
        ]
    }

    policy_exists = s3_removal_policy_exists(client, resource)
    lifecycle_policy_exists = s3_removal_lifecycle_policy_exists(client, resource)
    if policy_exists and lifecycle_policy_exists:
        return ActionStatus.IGNORED, {}

    if not policy_exists:
        client.put_bucket_policy(Bucket=resource.id, Policy=json.dumps(bucket_policy))
        logger.info('Added policy to prevent putObject in s3 bucket {} in {}'.format(
            resource.id,
            resource.account.account_name
        ))

    if not lifecycle_policy_exists:
        # Grab S3 Metrics before lifecycle policies start removing objects

        client.put_bucket_lifecycle_configuration(
            Bucket=resource.id,
            LifecycleConfiguration=s3_removal_lifecycle_policy
        )
        logger.info('Added policy to delete bucket contents in s3 bucket {} in {}'.format(
            resource.id,
            resource.account.account_name
        ))

    return ActionStatus.SUCCEED, resource.metrics()
1272694
def add_policy(self, scaling_group, name, policy_type, cooldown,
            change=None, is_percent=False, desired_capacity=None, args=None):
        
        return self._manager.add_policy(scaling_group, name, policy_type,
                cooldown, change=change, is_percent=is_percent,
                desired_capacity=desired_capacity, args=args)
1115058
public List<Acl> listBucketAcls(String bucketName) {
    // [START listBucketAcls]
    List<Acl> acls = storage.listAcls(bucketName);
    for (Acl acl : acls) {
      // do something with ACL entry
    }
    // [END listBucketAcls]
    return acls;
  }
1245321
def put_bucket_policy(bucket_policy)
        if bucket_policy && bucket_policy.is_a?(String) && bucket_policy.strip != ''
             bucket_request(:put,:body => bucket_policy,:subresource=>"policy")
             true
        else  
            false
        end
    end
1037615
private void setBucketAccessPolicy(String bucketName, String oaIdentityId) {
        CloudFrontOriginAccessIdentity cfOAIdentity =
            cfClient.getCloudFrontOriginAccessIdentity(
                new GetCloudFrontOriginAccessIdentityRequest(oaIdentityId))
                    .getCloudFrontOriginAccessIdentity();
        String s3UserId = cfOAIdentity.getS3CanonicalUserId();

        StringBuilder policyText = new StringBuilder();
        policyText.append("{\"Version\":\"2012-10-17\",");
        policyText.append("\"Id\":\"PolicyForCloudFrontPrivateContent\",");
        policyText.append("\"Statement\":[{");
        policyText.append("\"Sid\":\"Grant CloudFront access to private content\",");
        policyText.append("\"Effect\":\"Allow\",");
        policyText.append("\"Principal\":{\"CanonicalUser\":\"" + s3UserId + "\"},");
        policyText.append("\"Action\":\"s3:GetObject\",");
        policyText.append("\"Resource\":\"arn:aws:s3:::" + bucketName + "/*\"");
        policyText.append("}]}");
        s3Client.setBucketPolicy(bucketName, policyText.toString());
    }
623012
def upload_token(
            self,
            bucket,
            key=None,
            expires=3600,
            policy=None,
            strict_policy=True):
        
        if bucket is None or bucket == '':
            raise ValueError('invalid bucket name')

        scope = bucket
        if key is not None:
            scope = '{0}:{1}'.format(bucket, key)

        args = dict(
            scope=scope,
            deadline=int(time.time()) + expires,
        )

        if policy is not None:
            self.__copy_policy(policy, args, strict_policy)

        return self.__upload_token(args)
390577
def delete(self):
    
    if self.exists():
      try:
        self._api.buckets_delete(self._name)
      except Exception as e:
        raise e
300832
async function bucketExists(cli, bucket) {
  try {
    await cli.headBucket({
      Bucket: bucket
    }).promise();
    return true;
  } catch (e) {
    switch (e.statusCode) {
      case 403:
        throw new Error(
          '403: You don\'t have permissions to access this bucket');
      case 404:
        return false;
      default:
        throw e;
    }
  }
}
1003673
public static function setAccessControlPolicy($bucket, $uri = '', $acp = array())
	{
		$dom = new DOMDocument;
		$dom->formatOutput = true;
		$accessControlPolicy = $dom->createElement('AccessControlPolicy');
		$accessControlList = $dom->createElement('AccessControlList');

		// It seems the owner has to be passed along too
		$owner = $dom->createElement('Owner');
		$owner->appendChild($dom->createElement('ID', $acp['owner']['id']));
		$owner->appendChild($dom->createElement('DisplayName', $acp['owner']['name']));
		$accessControlPolicy->appendChild($owner);

		foreach ($acp['acl'] as $g)
		{
			$grant = $dom->createElement('Grant');
			$grantee = $dom->createElement('Grantee');
			$grantee->setAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance');
			if (isset($g['id']))
			{ // CanonicalUser (DisplayName is omitted)
				$grantee->setAttribute('xsi:type', 'CanonicalUser');
				$grantee->appendChild($dom->createElement('ID', $g['id']));
			}
			elseif (isset($g['email']))
			{ // AmazonCustomerByEmail
				$grantee->setAttribute('xsi:type', 'AmazonCustomerByEmail');
				$grantee->appendChild($dom->createElement('EmailAddress', $g['email']));
			}
			elseif ($g['type'] == 'Group')
			{ // Group
				$grantee->setAttribute('xsi:type', 'Group');
				$grantee->appendChild($dom->createElement('URI', $g['uri']));
			}
			$grant->appendChild($grantee);
			$grant->appendChild($dom->createElement('Permission', $g['permission']));
			$accessControlList->appendChild($grant);
		}

		$accessControlPolicy->appendChild($accessControlList);
		$dom->appendChild($accessControlPolicy);

		$rest = new S3Request('PUT', $bucket, $uri, self::$endpoint);
		$rest->setParameter('acl', null);
		$rest->data = $dom->saveXML();
		$rest->size = strlen($rest->data);
		$rest->setHeader('Content-Type', 'application/xml');
		$rest = $rest->getResponse();
		if ($rest->error === false && $rest->code !== 200)
			$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
		if ($rest->error !== false)
		{
			self::__triggerError(sprintf("S3::setAccessControlPolicy({$bucket}, {$uri}): [%s] %s",
			$rest->error['code'], $rest->error['message']), __FILE__, __LINE__);
			return false;
		}
		return true;
	}
1002622
async def set_bucket(self, *,
                         chat: typing.Union[str, int, None] = None,
                         user: typing.Union[str, int, None] = None,
                         bucket: typing.Dict = None):
        
        raise NotImplementedError
823424
private Terms filterBuckets(Terms buckets, KunderaQuery query)
    {
        Expression havingClause = query.getSelectStatement().getHavingClause();

        if (!(havingClause instanceof NullExpression) && havingClause != null)
        {
            Expression conditionalExpression = ((HavingClause) havingClause).getConditionalExpression();

            for (Iterator<Bucket> bucketIterator = buckets.getBuckets().iterator(); bucketIterator.hasNext();)
            {
                InternalAggregations internalAgg = (InternalAggregations) bucketIterator.next().getAggregations();
                if (!isValidBucket(internalAgg, query, conditionalExpression))
                {
                    bucketIterator.remove();
                }
            }
        }
        return buckets;
    }
789057
async def reset_bucket(self, *,
                           chat: typing.Union[str, int, None] = None,
                           user: typing.Union[str, int, None] = None):
        
        await self.set_data(chat=chat, user=user, data={})
863647
def add_policy(self, name, policy_type, cooldown, change=None,
            is_percent=False, desired_capacity=None, args=None):
        
        return self.manager.add_policy(self, name, policy_type, cooldown,
                change=change, is_percent=is_percent,
                desired_capacity=desired_capacity, args=args)