Java 类com.amazonaws.services.s3.internal.Constants 实例源码

项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public VersionListing listVersions(ListVersionsRequest listVersionsRequest)
        throws SdkClientException, AmazonServiceException {
    listVersionsRequest = beforeClientExecution(listVersionsRequest);
    rejectNull(listVersionsRequest.getBucketName(), "The bucket name parameter must be specified when listing versions in a bucket");

    /**
     * This flag shows whether we need to url decode S3 key names. This flag is enabled
     * only when the customers don't explicitly call {@link listVersionsRequest#setEncodingType(String)},
     * otherwise, it will be disabled for maintaining backwards compatibility.
     */
    final boolean shouldSDKDecodeResponse = listVersionsRequest.getEncodingType() == null;

    Request<ListVersionsRequest> request = createRequest(listVersionsRequest.getBucketName(), null, listVersionsRequest, HttpMethodName.GET);
    request.addParameter("versions", null);

    addParameterIfNotNull(request, "prefix", listVersionsRequest.getPrefix());
    addParameterIfNotNull(request, "key-marker", listVersionsRequest.getKeyMarker());
    addParameterIfNotNull(request, "version-id-marker", listVersionsRequest.getVersionIdMarker());
    addParameterIfNotNull(request, "delimiter", listVersionsRequest.getDelimiter());

    if (listVersionsRequest.getMaxResults() != null && listVersionsRequest.getMaxResults() >= 0) request.addParameter("max-keys", listVersionsRequest.getMaxResults().toString());
    request.addParameter("encoding-type", shouldSDKDecodeResponse ? Constants.URL_ENCODING : listVersionsRequest.getEncodingType());

    return invoke(request, new Unmarshallers.VersionListUnmarshaller(shouldSDKDecodeResponse), listVersionsRequest.getBucketName(), null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public ObjectListing listObjects(ListObjectsRequest listObjectsRequest)
        throws SdkClientException, AmazonServiceException {
    listObjectsRequest = beforeClientExecution(listObjectsRequest);
    rejectNull(listObjectsRequest.getBucketName(), "The bucket name parameter must be specified when listing objects in a bucket");

    /**
     * This flag shows whether we need to url decode S3 key names. This flag is enabled
     * only when the customers don't explicitly call {@link ListObjectsRequest#setEncodingType(String)},
     * otherwise, it will be disabled for maintaining backwards compatibility.
     */
    final boolean shouldSDKDecodeResponse = listObjectsRequest.getEncodingType() == null;

    Request<ListObjectsRequest> request = createRequest(listObjectsRequest.getBucketName(), null, listObjectsRequest, HttpMethodName.GET);
    addParameterIfNotNull(request, "prefix", listObjectsRequest.getPrefix());
    addParameterIfNotNull(request, "marker", listObjectsRequest.getMarker());
    addParameterIfNotNull(request, "delimiter", listObjectsRequest.getDelimiter());
    if (listObjectsRequest.getMaxKeys() != null && listObjectsRequest.getMaxKeys().intValue() >= 0) request.addParameter("max-keys", listObjectsRequest.getMaxKeys().toString());
    request.addParameter("encoding-type", shouldSDKDecodeResponse ? Constants.URL_ENCODING : listObjectsRequest.getEncodingType());

    return invoke(request, new Unmarshallers.ListObjectsUnmarshaller(shouldSDKDecodeResponse), listObjectsRequest.getBucketName(), null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public boolean doesBucketExist(String bucketName)
        throws SdkClientException, AmazonServiceException {

    try {
        headBucket(new HeadBucketRequest(bucketName));
        return true;
    } catch (AmazonServiceException ase) {
        // A redirect error or a forbidden error means the bucket exists. So
        // returning true.
        if ((ase.getStatusCode() == Constants.BUCKET_REDIRECT_STATUS_CODE)
                || (ase.getStatusCode() == Constants.BUCKET_ACCESS_FORBIDDEN_STATUS_CODE)) {
            return true;
        }
        if (ase.getStatusCode() == Constants.NO_SUCH_BUCKET_STATUS_CODE) {
            return false;
        }
        throw ase;

    }
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
protected <X extends AmazonWebServiceRequest> Request<X> createRequest(String bucketName, String key, X originalRequest, HttpMethodName httpMethod, URI endpoint) {
    // If the underlying AmazonS3Client has enabled accelerate mode and the original
    // request operation is accelerate mode supported, then the request will use the
    // s3-accelerate endpoint to performe the operations.
    if (clientOptions.isAccelerateModeEnabled() && !(originalRequest instanceof S3AccelerateUnsupported)) {
        if (clientOptions.isDualstackEnabled()) {
            endpoint = RuntimeHttpUtils.toUri(Constants.S3_ACCELERATE_DUALSTACK_HOSTNAME, clientConfiguration);
        } else {
            endpoint = RuntimeHttpUtils.toUri(Constants.S3_ACCELERATE_HOSTNAME, clientConfiguration);
        }
    }

    Request<X> request = new DefaultRequest<X>(originalRequest, Constants.S3_SERVICE_DISPLAY_NAME);
    request.setHttpMethod(httpMethod);
    request.addHandlerContext(S3HandlerContextKeys.IS_CHUNKED_ENCODING_DISABLED,
            Boolean.valueOf(clientOptions.isChunkedEncodingDisabled()));
    request.addHandlerContext(S3HandlerContextKeys.IS_PAYLOAD_SIGNING_ENABLED,
            Boolean.valueOf(clientOptions.isPayloadSigningEnabled()));
    resolveRequestEndpoint(request, bucketName, key, endpoint);

    return request;
}
项目:ibm-cos-sdk-java    文件:RequestPaymentConfigurationXmlFactory.java   
/**
 * Converts the specified request payment configuration into an XML byte
 * array to send to Amazon S3.
 *
 * Sample XML:
 * <RequestPaymentConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
 *      <Payer>Requester</Payer>
 * </RequestPaymentConfiguration>
 *
 * @param requestPaymentConfiguration
 *            The request payment configuration request to convert..
 * @return The XML byte array representation.
 */
public byte[] convertToXmlByteArray(
        RequestPaymentConfiguration requestPaymentConfiguration) {
    XmlWriter xml = new XmlWriter();
    xml.start("RequestPaymentConfiguration", "xmlns",
            Constants.XML_NAMESPACE);

    Payer payer = requestPaymentConfiguration.getPayer();
    if (payer != null) {
        XmlWriter payerDocumentElement = xml.start("Payer");
        payerDocumentElement.value(payer.toString());
        payerDocumentElement.end();
    }
    xml.end();
    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified versioning configuration into an XML byte array.
 *
 * @param versioningConfiguration
 *            The configuration to convert.
 *
 * @return The XML byte array representation.
 */
public byte[] convertToXmlByteArray(BucketVersioningConfiguration versioningConfiguration) {
    XmlWriter xml = new XmlWriter();
    xml.start("VersioningConfiguration", "xmlns", Constants.XML_NAMESPACE);
    xml.start("Status").value(versioningConfiguration.getStatus()).end();

    Boolean mfaDeleteEnabled = versioningConfiguration.isMfaDeleteEnabled();
    if (mfaDeleteEnabled != null) {
        if (mfaDeleteEnabled) {
            xml.start("MfaDelete").value("Enabled").end();
        } else {
            xml.start("MfaDelete").value("Disabled").end();
        }
    }

    xml.end();

    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified logging configuration into an XML byte array.
 *
 * @param loggingConfiguration
 *            The configuration to convert.
 *
 * @return The XML byte array representation.
 */
public byte[] convertToXmlByteArray(BucketLoggingConfiguration loggingConfiguration) {
    // Default log file prefix to the empty string if none is specified
    String logFilePrefix = loggingConfiguration.getLogFilePrefix();
    if (logFilePrefix == null)
        logFilePrefix = "";

    XmlWriter xml = new XmlWriter();
    xml.start("BucketLoggingStatus", "xmlns", Constants.XML_NAMESPACE);
    if (loggingConfiguration.isLoggingEnabled()) {
        xml.start("LoggingEnabled");
        xml.start("TargetBucket").value(loggingConfiguration.getDestinationBucketName()).end();
        xml.start("TargetPrefix").value(loggingConfiguration.getLogFilePrefix()).end();
        xml.end();
    }
    xml.end();

    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified {@link BucketCrossOriginConfiguration} object to an XML fragment that
 * can be sent to Amazon S3.
 *
 * @param config
 *            The {@link BucketCrossOriginConfiguration}
 */
/*
 * <CORSConfiguration>
         <CORSRule>
           <AllowedOrigin>http://www.foobar.com</AllowedOrigin>
           <AllowedMethod>GET</AllowedMethod>
           <MaxAgeSeconds>3000</MaxAgeSec>
           <ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
         </CORSRule>
   </CORSConfiguration>
 */
public byte[] convertToXmlByteArray(BucketCrossOriginConfiguration config) throws SdkClientException {

    XmlWriter xml = new XmlWriter();
    xml.start("CORSConfiguration", "xmlns", Constants.XML_NAMESPACE);

    for (CORSRule rule : config.getRules()) {
        writeRule(xml, rule);
    }

    xml.end();

    return xml.getBytes();
}
项目:dcos-cassandra-service    文件:S3StorageDriver.java   
String getEndpoint(BackupRestoreContext ctx) throws URISyntaxException {
    URI uri = new URI(ctx.getExternalLocation());
    String scheme = uri.getScheme();
    if (scheme.equals(AmazonS3Client.S3_SERVICE_NAME)) {
        return Constants.S3_HOSTNAME;
    } else {
        String endpoint = scheme + "://" + uri.getHost();

        int port = uri.getPort();
        if (port != -1) {
            endpoint += ":" + Integer.toString(port);
        }

        return endpoint;
    }
}
项目:components    文件:S3OutputWriter.java   
@Override
public void open(String uId) throws IOException {
    // connect to s3
    s3_client = S3Connection.createClient(properties);
    try {
        s3_client.listObjects(properties.getDatasetProperties().bucket.getValue(), "any");
    } catch (AmazonServiceException ase) {
        if (ase.getStatusCode() != Constants.NO_SUCH_BUCKET_STATUS_CODE) {
            throw ase;
        }
    }

    // prepare the local target, will upload it to s3 and clear it in the close method
    data_file = File.createTempFile("s3-", ".csv");

    OutputStream outputStream = new FileOutputStream(data_file);
    writer = new CsvWriter(new OutputStreamWriter(outputStream), ';');
}
项目:components    文件:S3SourceOrSink.java   
@Override
public ValidationResult validate(RuntimeContainer container) {
    try {
        AmazonS3 conn = S3Connection.createClient(properties);
        try {
            conn.listObjects(properties.getDatasetProperties().bucket.getValue(), "any");
        } catch (AmazonServiceException ase) {
            if (ase.getStatusCode() != Constants.NO_SUCH_BUCKET_STATUS_CODE) {
                throw ase;
            }
        }
        return ValidationResult.OK;
    } catch (Exception e) {
        ValidationResultMutable vr = new ValidationResultMutable();
        vr.setMessage(e.getClass() + " : " + e.getMessage());
        vr.setStatus(ValidationResult.Result.ERROR);
        return vr;
    }
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
private void init() {

        // calling this.setEndpoint(...) will also modify the signer accordingly
        setEndpoint(Constants.S3_HOSTNAME);

        HandlerChainFactory chainFactory = new HandlerChainFactory();
        requestHandler2s.addAll(chainFactory.newRequestHandlerChain(
                "/com/amazonaws/services/s3/request.handlers"));
        requestHandler2s.addAll(chainFactory.newRequestHandler2Chain(
                "/com/amazonaws/services/s3/request.handler2s"));
        requestHandler2s.addAll(chainFactory.getGlobalHandlers());
    }
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public ListObjectsV2Result listObjectsV2(ListObjectsV2Request listObjectsV2Request)
        throws SdkClientException, AmazonServiceException {
    listObjectsV2Request = beforeClientExecution(listObjectsV2Request);
    rejectNull(listObjectsV2Request.getBucketName(), "The bucket name parameter must be specified when listing objects in a bucket");
    Request<ListObjectsV2Request> request = createRequest(listObjectsV2Request.getBucketName(), null, listObjectsV2Request, HttpMethodName.GET);

    /**
     * List type '2' is required to opt-in to listObjectsV2.
     */
    request.addParameter("list-type", "2");

    addParameterIfNotNull(request, "start-after", listObjectsV2Request.getStartAfter());
    addParameterIfNotNull(request, "continuation-token", listObjectsV2Request.getContinuationToken());
    addParameterIfNotNull(request, "delimiter", listObjectsV2Request.getDelimiter());
    addParameterIfNotNull(request, "max-keys", listObjectsV2Request.getMaxKeys());
    addParameterIfNotNull(request, "prefix", listObjectsV2Request.getPrefix());
    addParameterIfNotNull(request, "encoding-type", listObjectsV2Request.getEncodingType());
    request.addParameter("fetch-owner", Boolean.toString(listObjectsV2Request.isFetchOwner()));

    /**
     * If URL encoding has been requested from S3 we'll automatically decode the response.
     */
    final boolean shouldSDKDecodeResponse = listObjectsV2Request.getEncodingType() == Constants.URL_ENCODING;

    return invoke(request, new Unmarshallers.ListObjectsV2Unmarshaller(shouldSDKDecodeResponse), listObjectsV2Request.getBucketName(), null);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public synchronized Region getRegion() {
    String authority = super.endpoint.getAuthority();
    if (Constants.S3_HOSTNAME.equals(authority)) {
        return Region.US_Standard;
    } else {
        Matcher m = Region.S3_REGIONAL_ENDPOINT_PATTERN.matcher(authority);
        if (m.matches()) {
            return Region.fromValue(m.group(1));
        } else {
            throw new IllegalStateException(
                "S3 client with invalid S3 endpoint configured: " + authority);
        }
    }
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public String getRegionName() {
    String authority = super.endpoint.getAuthority();
    if(Constants.S3_HOSTNAME.equals(authority)) {
        return "us-east-1";
    }
    Matcher m = Region.S3_REGIONAL_ENDPOINT_PATTERN.matcher(authority);
    try {
        m.matches();
        return RegionUtils.getRegion(m.group(1)).getName();
    } catch (Exception e) {
        throw new IllegalStateException("No valid region has been specified. Unable to return region name", e);
    }
}
项目:ibm-cos-sdk-java    文件:AclXmlFactory.java   
/**
 * Converts the specified AccessControlList object to an XML fragment that
 * can be sent to Amazon S3.
 *
 * @param acl
 *            The AccessControlList to convert to XML.
 *
 * @return an XML representation of the Access Control List object, suitable
 *         to send in a request to Amazon S3.
 */
public byte[] convertToXmlByteArray(AccessControlList acl) throws SdkClientException {
    Owner owner = acl.getOwner();
    if (owner == null) {
        throw new SdkClientException("Invalid AccessControlList: missing an S3Owner");
    }

    XmlWriter xml = new XmlWriter();
    xml.start("AccessControlPolicy", "xmlns", Constants.XML_NAMESPACE);
    xml.start("Owner");
    if (owner.getId() != null) {
        xml.start("ID").value(owner.getId()).end();
    }
    if (owner.getDisplayName() != null) {
        xml.start("DisplayName").value(owner.getDisplayName()).end();
    }
    xml.end();
    xml.start("AccessControlList");
    for (Grant grant : acl.getGrantsAsList()) {
        xml.start("Grant");
        convertToXml(grant.getGrantee(), xml);
        xml.start("Permission").value(grant.getPermission().toString()).end();
        xml.end();
    }
    xml.end();
    xml.end();

    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified {@link com.amazonaws.services.s3.model.metrics.MetricsConfiguration}
 * object to an XML fragment that can be sent to Amazon S3.
 *
 * @param config
 *            The {@link com.amazonaws.services.s3.model.metrics.MetricsConfiguration}.
 */
 /*
  * <MetricsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
       <Id>metrics-id</Id>
       <Filter>
       <!-- A filter should have only one of Prefix, Tag or And-->
         <Prefix>prefix</Prefix>
         <Tag>
             <Key>Project</Key>
             <Value>Foo</Value>
         </Tag>
         <And>
           <Prefix>documents/</Prefix>
           <Tag>
             <Key>foo</Key>
             <Value>bar</Value>
           </Tag>
         </And>
       </Filter>
    </MetricsConfiguration>
 */
public byte[] convertToXmlByteArray(MetricsConfiguration config) throws SdkClientException {
    XmlWriter xml = new XmlWriter();

    xml.start("MetricsConfiguration", "xmlns", Constants.XML_NAMESPACE);

    addParameterIfNotNull(xml, "Id", config.getId());
    writeMetricsFilter(xml, config.getFilter());

    xml.end();

    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:AmazonS3ClientTest.java   
/**
 * Test Service Instance Id is added to the Request Object and
 * the runtime parameter takes precedence over any set by the
 * CredentialProvider
 * 
 */ 
@Test
public void testServiceInstanceRuntimeParamTakesPrecedence() {

    String serviceInstanceId = "12345";

    CreateBucketRequest request = new CreateBucketRequest("testbucket").withServiceInstanceId(serviceInstanceId);
    Request<CreateBucketRequest> defaultRequest = new DefaultRequest(Constants.S3_SERVICE_DISPLAY_NAME);
    AmazonS3Client s3Client = new AmazonS3Client(new BasicIBMOAuthCredentials(new TokenMangerUtilTest(), "54321"));
    defaultRequest = s3Client.addIAMHeaders(defaultRequest, request);

    assertEquals(defaultRequest.getHeaders().get(Headers.IBM_SERVICE_INSTANCE_ID), serviceInstanceId);
}
项目:ibm-cos-sdk-java    文件:AmazonS3ClientTest.java   
/**
 * Test Service Instance Id is added to the Request Object by 
 * the CredentialProvider
 * 
 */ 
@Test
public void testServiceInstanceHeaderIsAddedByCredentialProvdier() {

    String serviceInstanceId = "12345";

    CreateBucketRequest request = new CreateBucketRequest("testbucket");
    Request<CreateBucketRequest> defaultRequest = new DefaultRequest(Constants.S3_SERVICE_DISPLAY_NAME);
    AmazonS3Client s3Client = new AmazonS3Client(new BasicIBMOAuthCredentials(new TokenMangerUtilTest(), serviceInstanceId));
    defaultRequest = s3Client.addIAMHeaders(defaultRequest, request);

    assertEquals(defaultRequest.getHeaders().get(Headers.IBM_SERVICE_INSTANCE_ID), serviceInstanceId);
}
项目:ibm-cos-sdk-java    文件:AmazonS3ClientTest.java   
/**
 * Test No IAM Headers are added & no null pointers are thrown
 * 
 */ 
@Test
public void testNoIAMHeadersAreAdded() {

    CreateBucketRequest request = new CreateBucketRequest("testbucket");
    Request<CreateBucketRequest> defaultRequest = new DefaultRequest(Constants.S3_SERVICE_DISPLAY_NAME);
    AmazonS3Client s3Client = new AmazonS3Client(new BasicAWSCredentials("987654321", "123456789"));
    defaultRequest = s3Client.addIAMHeaders(defaultRequest, request);

    assertEquals(defaultRequest.getHeaders().get(Headers.IBM_SERVICE_INSTANCE_ID), null);
}
项目:s3-cluster-discovery-plugin    文件:Configuration.java   
public String getEndpoint() {
    final String property = getProperty("s3-endpoint");
    if (property == null) {
        return Constants.S3_HOSTNAME;
    }

    return property;
}
项目:dcos-cassandra-service    文件:S3StorageDriverTest.java   
@Test
public void testGetEndpointS3Protocol() throws URISyntaxException {
    BackupRestoreContext backupRestoreContext = BackupRestoreContext.create(
            "node-id",
            "name",
            "s3://cassandrabackup",
            "local-location",
            "account-id",
            "secret-key",
            false,
            "existing");
    Assert.assertEquals(Constants.S3_HOSTNAME, s3StorageDriver.getEndpoint(backupRestoreContext));
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public Bucket createBucket(CreateBucketRequest createBucketRequest)
        throws SdkClientException, AmazonServiceException {
    createBucketRequest = beforeClientExecution(createBucketRequest);
    rejectNull(createBucketRequest,
               "The CreateBucketRequest parameter must be specified when creating a bucket");

    String bucketName = createBucketRequest.getBucketName();
    rejectNull(bucketName, "The bucket name parameter must be specified when creating a bucket");
    bucketName = bucketName.trim();

    String requestRegion = createBucketRequest.getRegion();
    URI requestEndpoint = getCreateBucketEndpoint(requestRegion);

    BucketNameUtils.validateBucketName(bucketName);

    Request<CreateBucketRequest> request = createRequest(bucketName, null, createBucketRequest, HttpMethodName.PUT, requestEndpoint);

    //Add IBM Service Instance Id & Encryption to headers
    if ((null != this.awsCredentialsProvider ) && (this.awsCredentialsProvider.getCredentials() instanceof IBMOAuthCredentials)) {
        IBMOAuthCredentials oAuthCreds = (IBMOAuthCredentials)this.awsCredentialsProvider.getCredentials();
        if (oAuthCreds.getServiceInstanceId() != null) {
            request.addHeader(Headers.IBM_SERVICE_INSTANCE_ID, oAuthCreds.getServiceInstanceId());
            if (null != createBucketRequest.getEncryptionType()) {
            request.addHeader(Headers.IBM_SSE_KP_ENCRYPTION_ALGORITHM, createBucketRequest.getEncryptionType().getKmsEncryptionAlgorithm());
            request.addHeader(Headers.IBM_SSE_KP_CUSTOMER_ROOT_KEY_CRN, createBucketRequest.getEncryptionType().getIBMSSEKMSCustomerRootKeyCrn());
            }
        }
    }

    if (createBucketRequest.getAccessControlList() != null) {
        addAclHeaders(request, createBucketRequest.getAccessControlList());
    } else if (createBucketRequest.getCannedAcl() != null) {
        request.addHeader(Headers.S3_CANNED_ACL, createBucketRequest.getCannedAcl().toString());
    }

    /*
     * If we're talking to a region-specific endpoint other than the US, we
     * *must* specify a location constraint. Try to derive the region from
     * the endpoint.
     */
    if (getSignerRegion() != null && !getSignerRegion().equals("us-east-1") && StringUtils.isNullOrEmpty(requestRegion)) {
        requestRegion = AwsHostNameUtils.parseRegion(requestEndpoint.getHost(), S3_SERVICE_NAME);
    }

    /*
     * We can only send the CreateBucketConfiguration if we're *not*
     * creating a bucket in the US region.
     */
    if (requestRegion != null && !StringUtils.upperCase(requestRegion).equals(Region.US_Standard.toString())) {
        XmlWriter xml = new XmlWriter();
        xml.start("CreateBucketConfiguration", "xmlns", Constants.XML_NAMESPACE);
        xml.start("LocationConstraint").value(requestRegion).end();
        xml.end();

        request.setContent(new ByteArrayInputStream(xml.getBytes()));
    }

    invoke(request, voidResponseHandler, bucketName, null);

    return new Bucket(bucketName);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
private boolean isStandardEndpoint(URI endpoint) {
    return endpoint.getHost().endsWith(Constants.S3_HOSTNAME);
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
@Override
public URL getUrl(String bucketName, String key) {
    Request<?> request = new DefaultRequest<Object>(Constants.S3_SERVICE_DISPLAY_NAME);
    resolveRequestEndpoint(request, bucketName, key, endpoint);
    return ServiceUtils.convertRequestToUrl(request, false, false);
}
项目:ibm-cos-sdk-java    文件:S3ServiceMetric.java   
@Override public String getServiceName() {
    return Constants.S3_SERVICE_DISPLAY_NAME;
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified notification configuration into an XML byte array.
 *
 * @param notificationConfiguration
 *            The configuration to convert.
 *
 * @return The XML byte array representation.
 */
public byte[] convertToXmlByteArray(
        BucketNotificationConfiguration notificationConfiguration) {
    XmlWriter xml = new XmlWriter();
    xml.start("NotificationConfiguration", "xmlns", Constants.XML_NAMESPACE);
    Map<String, NotificationConfiguration> configurations = notificationConfiguration
            .getConfigurations();

    for (Map.Entry<String, NotificationConfiguration> entry : configurations
            .entrySet()) {
        String configName = entry.getKey();
        NotificationConfiguration config = entry.getValue();
        if (config instanceof TopicConfiguration) {
            xml.start("TopicConfiguration");
            xml.start("Id").value(configName).end();
            xml.start("Topic")
                    .value(((TopicConfiguration) config).getTopicARN())
                    .end();
            addEventsAndFilterCriteria(xml, config);
            xml.end();
        } else if (config instanceof QueueConfiguration) {
            xml.start("QueueConfiguration");
            xml.start("Id").value(configName).end();
            xml.start("Queue")
                    .value(((QueueConfiguration) config).getQueueARN())
                    .end();
            addEventsAndFilterCriteria(xml, config);
            xml.end();
        } else if (config instanceof CloudFunctionConfiguration) {
            xml.start("CloudFunctionConfiguration");
            xml.start("Id").value(configName).end();
            xml.start("InvocationRole")
                    .value(((CloudFunctionConfiguration) config)
                            .getInvocationRoleARN()).end();
            xml.start("CloudFunction")
                    .value(((CloudFunctionConfiguration) config).getCloudFunctionARN())
                    .end();
            addEventsAndFilterCriteria(xml, config);
            xml.end();
        } else if (config instanceof LambdaConfiguration) {
            xml.start("CloudFunctionConfiguration");
            xml.start("Id").value(configName).end();
            xml.start("CloudFunction")
                    .value(((LambdaConfiguration) config).getFunctionARN())
                    .end();
            addEventsAndFilterCriteria(xml, config);
            xml.end();
        }
    }
    xml.end();
    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified website configuration into an XML byte array to
 * send to S3.
 *
 * Sample XML:
 * <WebsiteConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
 *    <IndexDocument>
 *      <Suffix>index.html</Suffix>
 *    </IndexDocument>
 *    <ErrorDocument>
 *      <Key>404.html</Key>
 *    </ErrorDocument>
 *  </WebsiteConfiguration>
 *
 * @param websiteConfiguration
 *            The configuration to convert.
 * @return The XML byte array representation.
 */
public byte[] convertToXmlByteArray(BucketWebsiteConfiguration websiteConfiguration) {
    XmlWriter xml = new XmlWriter();
    xml.start("WebsiteConfiguration", "xmlns", Constants.XML_NAMESPACE);

    if (websiteConfiguration.getIndexDocumentSuffix() != null) {
        XmlWriter indexDocumentElement = xml.start("IndexDocument");
        indexDocumentElement.start("Suffix").value(websiteConfiguration.getIndexDocumentSuffix()).end();
        indexDocumentElement.end();
    }

    if (websiteConfiguration.getErrorDocument() != null) {
        XmlWriter errorDocumentElement = xml.start("ErrorDocument");
        errorDocumentElement.start("Key").value(websiteConfiguration.getErrorDocument()).end();
        errorDocumentElement.end();
    }

    RedirectRule redirectAllRequestsTo = websiteConfiguration.getRedirectAllRequestsTo();
    if (redirectAllRequestsTo != null) {
        XmlWriter redirectAllRequestsElement = xml.start("RedirectAllRequestsTo");
        if (redirectAllRequestsTo.getprotocol() != null) {
            xml.start("Protocol").value(redirectAllRequestsTo.getprotocol()).end();
        }

        if (redirectAllRequestsTo.getHostName() != null) {
            xml.start("HostName").value(redirectAllRequestsTo.getHostName()).end();
        }

        if (redirectAllRequestsTo.getReplaceKeyPrefixWith() != null) {
            xml.start("ReplaceKeyPrefixWith").value(redirectAllRequestsTo.getReplaceKeyPrefixWith()).end();
        }

        if (redirectAllRequestsTo.getReplaceKeyWith() != null) {
            xml.start("ReplaceKeyWith").value(redirectAllRequestsTo.getReplaceKeyWith()).end();
        }
        redirectAllRequestsElement.end();
    }

    if (websiteConfiguration.getRoutingRules() != null && websiteConfiguration.getRoutingRules().size() > 0) {

        XmlWriter routingRules = xml.start("RoutingRules");
        for (RoutingRule rule : websiteConfiguration.getRoutingRules()) {
            writeRule(routingRules, rule);
        }

        routingRules.end();
    }

    xml.end();
    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified {@link InventoryConfiguration} object to an XML fragment that
 * can be sent to Amazon S3.
 *
 * @param config
 *            The {@link InventoryConfiguration}
 */
 /*
    <?xml version="1.0" encoding="UTF-8"?>
    <InventoryConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
       <Destination>
          <S3BucketDestination>
             <AccountId>A2OCNCIEQW9MSG</AccountId>
             <Bucket>s3-object-inventory-list-gamma-us-east-1</Bucket>
             <Format>CSV</Format>
             <Prefix>string</Prefix>
          </S3BucketDestination>
       </Destination>
       <IsEnabled>true</IsEnabled>
       <Filter>
          <Prefix>string</Prefix>
       </Filter>
       <Id>configId</Id>
       <IncludedObjectVersions>All</IncludedObjectVersions>
       <OptionalFields>
          <Field>Size</Field>
          <Field>LastModifiedDate</Field>
          <Field>StorageClass</Field>
          <Field>ETag</Field>
          <Field>IsMultipartUploaded</Field>
          <Field>ReplicationStatus</Field>
       </OptionalFields>
       <Schedule>
          <Frequency>Daily</Frequency>
       </Schedule>
    </InventoryConfiguration>
*/
public byte[] convertToXmlByteArray(InventoryConfiguration config) throws SdkClientException {
    XmlWriter xml = new XmlWriter();
    xml.start("InventoryConfiguration", "xmlns", Constants.XML_NAMESPACE);

    xml.start("Id").value(config.getId()).end();
    xml.start("IsEnabled").value(String.valueOf(config.isEnabled())).end();
    xml.start("IncludedObjectVersions").value(config.getIncludedObjectVersions()).end();

    writeInventoryDestination(xml, config.getDestination());
    writeInventoryFilter(xml, config.getInventoryFilter());
    addInventorySchedule(xml, config.getSchedule());
    addInventoryOptionalFields(xml, config.getOptionalFields());

    xml.end(); // </InventoryConfiguration>

    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified {@link com.amazonaws.services.s3.model.analytics.AnalyticsConfiguration} object to an
 * XML fragment that can be sent to Amazon S3.
 *
 * @param config
 *            The {@link com.amazonaws.services.s3.model.analytics.AnalyticsConfiguration}
 */
 /*
  * <AnalyticsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
       <Id>XXX</Id>
       <Filter>
         <And>
           <Prefix>documents/</Prefix>
           <Tag>
             <Key>foo</Key>
             <Value>bar</Value>
           </Tag>
         </And>
       </Filter>
       <StorageClassAnalysis>
         <DataExport>
           <OutputSchemaVersion>1</OutputSchemaVersion>
           <Destination>
             <S3BucketDestination>
               <Format>CSV</Format>
               <BucketAccountId>123456789</BucketAccountId>
               <Bucket>destination-bucket</Bucket>
               <Prefix>destination-prefix</Prefix>
             </S3BucketDestination>
           </Destination>
         </DataExport>
       </StorageClassAnalysis>
    </AnalyticsConfiguration>
 */
public byte[] convertToXmlByteArray(AnalyticsConfiguration config) throws SdkClientException {
    XmlWriter xml = new XmlWriter();

    xml.start("AnalyticsConfiguration", "xmlns", Constants.XML_NAMESPACE);

    addParameterIfNotNull(xml, "Id", config.getId());
    writeAnalyticsFilter(xml, config.getFilter());
    writeStorageClassAnalysis(xml, config.getStorageClassAnalysis());

    xml.end();

    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:ObjectMetadata.java   
@Override
public void setRequesterCharged(boolean isRequesterCharged) {
    if (isRequesterCharged) {
        metadata.put(Headers.REQUESTER_CHARGED_HEADER, Constants.REQUESTER_PAYS);
    }
}
项目:ibm-cos-sdk-java    文件:BucketConfigurationXmlFactory.java   
/**
 * Converts the specified accelerate configuration into an XML byte array.
 *
 * @param accelerateConfiguration
 *            The configuration to convert.
 *
 * @return The XML byte array representation.
 */
public byte[] convertToXmlByteArray(BucketAccelerateConfiguration accelerateConfiguration) {
    XmlWriter xml = new XmlWriter();
    xml.start("AccelerateConfiguration", "xmlns", Constants.XML_NAMESPACE);
    xml.start("Status").value(accelerateConfiguration.getStatus()).end();
    xml.end();
    return xml.getBytes();
}
项目:ibm-cos-sdk-java    文件:AmazonS3Client.java   
/**
 * <p>
 * Populate the specified request with {@link Constants#REQUESTER_PAYS} to header {@link Headers#REQUESTER_PAYS_HEADER},
 * if isRequesterPays is true.
 * </p>
 *
 * @param request
 *              The specified request to populate.
 * @param isRequesterPays
 *              The flag whether to populate the header or not.
 */
protected static void populateRequesterPaysHeader(Request<?> request, boolean isRequesterPays) {
    if (isRequesterPays) {
        request.addHeader(Headers.REQUESTER_PAYS_HEADER, Constants.REQUESTER_PAYS);
    }
}