Example usage for com.amazonaws.services.s3.model PutObjectRequest setCannedAcl

List of usage examples for com.amazonaws.services.s3.model PutObjectRequest setCannedAcl

Introduction

In this page you can find the example usage for com.amazonaws.services.s3.model PutObjectRequest setCannedAcl.

Prototype

public void setCannedAcl(CannedAccessControlList cannedAcl) 

Source Link

Document

Sets the optional pre-configured access control policy to use for the new object.

Usage

From source file:PutTestFile.java

License:Apache License

public static void main(String[] args) throws IOException {
    /*/*from  w  ww. j av  a 2  s.  c o m*/
     * Important: Be sure to fill in your AWS access credentials in the
     * AwsCredentials.properties file before you try to run this sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(

            PutTestFile.class.getResourceAsStream("AwsCredentials.properties")));
    String bucketName = "dtccTest";

    String key = "largerfile.txt";

    System.out.println("===========================================");
    System.out.println("Getting Started with Amazon S3");
    System.out.println("===========================================\n");

    try {

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();

        System.out.println("Uploading a new object to S3 from a file\n");

        PutObjectRequest request = new PutObjectRequest(bucketName, key, createSampleFile());
        request.setCannedAcl(CannedAccessControlList.PublicRead);
        s3.putObject(request);

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, whichmeans your request made it "
                + "to Amazon S3, but was rejected with an errorresponse for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, whichmeans the client encountered "
                + "a serious internal problem while trying tocommunicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:PutFile.java

License:Apache License

public static void main(String[] args) throws IOException {
    /*/*from  www  .j a  va  2  s . c  o  m*/
     * Important: Be sure to fill in your AWS access credentials in the
     * AwsCredentials.properties file before you try to run this sample.
     * http://aws.amazon.com/security-credentials
     */
    AmazonS3 s3 = new AmazonS3Client(new PropertiesCredentials(

            PutFile.class.getResourceAsStream("AwsCredentials.properties")));
    String bucketName = "dtccTest";

    System.out.println("===========================================");
    System.out.println(" Amazon S3 Test");
    System.out.println("===========================================\n");

    try {

        /*
         * List the buckets in your account
         */
        System.out.println("Listing buckets");
        for (Bucket bucket : s3.listBuckets()) {
            System.out.println(" - " + bucket.getName());
        }
        System.out.println();
        String fileName = "S3HWTest.zip";
        File file = new File(fileName);
        System.out.println("Uploading a new object to S3 from a file " + fileName + "\n");
        System.out.println("file.length() " + file.length() + "\n");

        long start = System.currentTimeMillis();
        PutObjectRequest request = new PutObjectRequest(bucketName, fileName, file);
        request.setCannedAcl(CannedAccessControlList.PublicRead);
        s3.putObject(request);
        System.out.println("Uploading done in " + (System.currentTimeMillis() - start) + " ms.\n");

    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, whichmeans your request made it "
                + "to Amazon S3, but was rejected with an errorresponse for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, whichmeans the client encountered "
                + "a serious internal problem while trying tocommunicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.amazon.photosharing.utils.content.UploadThread.java

License:Open Source License

@Override
public void run() {
    ObjectMetadata meta_data = new ObjectMetadata();
    if (p_content_type != null)
        meta_data.setContentType(p_content_type);

    meta_data.setContentLength(p_size);/*from w w  w . ja v a2 s.  c o  m*/

    PutObjectRequest putObjectRequest = new PutObjectRequest(p_bucket_name, p_s3_key, p_file_stream, meta_data);
    putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
    PutObjectResult res = s3Client.putObject(putObjectRequest);
}

From source file:com.eBilling.util.S3Example.java

void uploadfile(AWSCredentials credentials) {
    AmazonS3 s3client = new AmazonS3Client(credentials);

    try {/* ww w  .  ja  v  a2s  .  com*/
        File file = new File(uploadFileName);
        PutObjectRequest p = new PutObjectRequest(bucketName, keyName, file);
        p.setCannedAcl(CannedAccessControlList.PublicRead);
        s3client.putObject(p);
        String _finalUrl = "https://" + bucketName + ".s3.amazonaws.com/" + keyName;
        System.out.println(_finalUrl);
    } catch (AmazonServiceException ase) {
        System.out.println("Caught an AmazonServiceException, which " + "means your request made it "
                + "to Amazon S3, but was rejected with an error response" + " for some reason.");
        System.out.println("Error Message:    " + ase.getMessage());
        System.out.println("HTTP Status Code: " + ase.getStatusCode());
        System.out.println("AWS Error Code:   " + ase.getErrorCode());
        System.out.println("Error Type:       " + ase.getErrorType());
        System.out.println("Request ID:       " + ase.getRequestId());
    } catch (AmazonClientException ace) {
        System.out.println("Caught an AmazonClientException, which " + "means the client encountered "
                + "an internal error while trying to " + "communicate with S3, "
                + "such as not being able to access the network.");
        System.out.println("Error Message: " + ace.getMessage());
    }
}

From source file:com.erudika.para.storage.AWSFileStore.java

License:Apache License

@Override
public String store(String path, InputStream data) {
    if (StringUtils.startsWith(path, "/")) {
        path = path.substring(1);// ww w  .  ja v a 2 s  . com
    }
    if (StringUtils.isBlank(path) || data == null) {
        return null;
    }
    int maxFileSizeMBytes = Config.getConfigInt("para.s3.max_filesize_mb", 10);
    try {
        if (data.available() > 0 && data.available() <= (maxFileSizeMBytes * 1024 * 1024)) {
            ObjectMetadata om = new ObjectMetadata();
            om.setCacheControl("max-age=15552000, must-revalidate"); // 180 days
            if (path.endsWith(".gz")) {
                om.setContentEncoding("gzip");
                path = path.substring(0, path.length() - 3);
            }
            path = System.currentTimeMillis() + "." + path;
            PutObjectRequest por = new PutObjectRequest(bucket, path, data, om);
            por.setCannedAcl(CannedAccessControlList.PublicRead);
            por.setStorageClass(StorageClass.ReducedRedundancy);
            s3.putObject(por);
            return Utils.formatMessage(baseUrl, Config.AWS_REGION, bucket, path);
        }
    } catch (IOException e) {
        logger.error(null, e);
    } finally {
        try {
            data.close();
        } catch (IOException ex) {
            logger.error(null, ex);
        }
    }
    return null;
}

From source file:com.flipzu.PostProcThread.java

License:Apache License

private boolean uploadToS3(Broadcast bcast, boolean delete) {
    debug.logPostProc("PostProcThread, S3 upload for " + bcast.getFilename());

    if (bcast.getFilename() == null) {
        debug.logPostProc("PostProcThread, uploadToS3, filename is null");
        return false;
    }//from  ww w. ja  v a 2  s  .c o m

    File file = new File(bcast.getFilename());
    if (!file.exists()) {
        debug.logPostProc("PostProcThread, uploadToS3, " + bcast.getFilename() + " does not exist");
        return false;
    }

    AmazonS3 s3 = null;

    try {
        InputStream is = new FileInputStream("aws.properties");
        s3 = new AmazonS3Client(new PropertiesCredentials(is));
    } catch (Exception e) {
        Debug.getInstance().logError("uploadToS3 Error ", e);
        return false;
    }

    String bucketName = Config.getInstance().getS3Bucket();
    String dirName = Config.getInstance().getS3dir();
    String objName = dirName + "/" + bcast.getId() + Config.getInstance().getFileWriterExtension();

    PutObjectRequest po = new PutObjectRequest(bucketName, objName, file);

    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentType("audio/mpeg");
    po.setMetadata(metadata);
    po.setCannedAcl(CannedAccessControlList.PublicRead);

    try {
        s3.putObject(po);
    } catch (AmazonServiceException ase) {
        debug.logPostProc("Caught an AmazonServiceException, which means your request made it "
                + "to Amazon S3, but was rejected with an error response for some reason.");
        debug.logPostProc("Error Message:    " + ase.getMessage());
        debug.logPostProc("HTTP Status Code: " + ase.getStatusCode());
        debug.logPostProc("AWS Error Code:   " + ase.getErrorCode());
        debug.logPostProc("Error Type:       " + ase.getErrorType());
        debug.logPostProc("Request ID:       " + ase.getRequestId());
        return false;

    } catch (AmazonClientException ace) {
        debug.logPostProc("Caught an AmazonClientException, which means the client encountered "
                + "a serious internal problem while trying to communicate with S3, "
                + "such as not being able to access the network.");
        debug.logPostProc("Error Message: " + ace.getMessage());
        return false;
    }

    if (delete) {
        if (Config.getInstance().deleteSmallBcasts())
            /* check and remove empty/short broadcasts */
            cleanCrappyBroadcasts(bcast.getKey(), file);

        debug.logPostProc("uploadToS3, deleting file " + bcast.getFilename());
        file.delete();
    }

    return true;

}

From source file:com.gendevs.bedrock.appengine.service.storage.StorageProvider.java

License:Apache License

private String uploadFile(InputStream imageInputStream, String contentType, String organisationId, String id,
        String type) {/*from ww  w. jav a 2s.  c o m*/
    initalizeS3();
    String fileName = null;
    switch (type) {
    case "app":
        fileName = String.format(StorageConstants.APP_PROFILE_PHOTOS, organisationId, id);
        break;
    case "user":
        fileName = String.format(StorageConstants.USER_PROFILE_PHOTOS, organisationId, id);
        break;
    }
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentType(contentType);

    PutObjectRequest por = new PutObjectRequest(bucketName, fileName, imageInputStream, metadata);
    por.setCannedAcl(CannedAccessControlList.PublicRead);
    Upload upload = manager.upload(por);
    try {
        upload.waitForCompletion();
    } catch (AmazonServiceException e) {
        e.printStackTrace();
    } catch (AmazonClientException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return fileName;
}

From source file:com.github.abhinavmishra14.aws.s3.service.impl.AwsS3IamServiceImpl.java

License:Open Source License

@Override
public PutObjectResult uploadObject(final String bucketName, final String fileName,
        final InputStream inputStream, final boolean isPublicAccessible)
        throws AmazonClientException, AmazonServiceException, IOException {
    LOGGER.info("uploadObject invoked, bucketName: {} , fileName: {} and isPublicAccessible: {}", bucketName,
            fileName, isPublicAccessible);
    File tempFile = null;/*from   www. ja v  a 2  s .c o m*/
    PutObjectRequest putObjectRequest = null;
    PutObjectResult uploadResult = null;
    try {
        // Create temporary file from stream to avoid 'out of memory' exception
        tempFile = AWSUtil.createTempFileFromStream(inputStream);
        putObjectRequest = new PutObjectRequest(bucketName, fileName, tempFile);
        if (isPublicAccessible) {
            putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        }
        uploadResult = uploadObject(putObjectRequest);
    } finally {
        AWSUtil.deleteTempFile(tempFile); // Delete the temporary file once uploaded
    }
    return uploadResult;
}

From source file:com.github.abhinavmishra14.aws.s3.service.impl.AwsS3IamServiceImpl.java

License:Open Source License

@Override
public boolean uploadObjectAndListenProgress(final String bucketName, final String fileName,
        final InputStream inputStream, final boolean isPublicAccessible)
        throws AmazonClientException, AmazonServiceException, IOException {
    LOGGER.info(//from   w  w w .  j a v  a2  s  .co  m
            "uploadObjectAndListenProgress invoked, bucketName: {} , fileName: {} and isPublicAccessible: {}",
            bucketName, fileName, isPublicAccessible);
    File tempFile = null;
    PutObjectRequest putObjectRequest = null;
    Upload upload = null;
    try {
        // Create temporary file from stream to avoid 'out of memory' exception
        tempFile = AWSUtil.createTempFileFromStream(inputStream);
        putObjectRequest = new PutObjectRequest(bucketName, fileName, tempFile);
        if (isPublicAccessible) {
            putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
        }
        final TransferManager transferMgr = new TransferManager(s3client);
        upload = transferMgr.upload(putObjectRequest);
        // You can poll your transfer's status to check its progress
        if (upload.isDone()) {
            LOGGER.info("Start: {}  , State: {} and Progress (%): {}", upload.getDescription(),
                    upload.getState(), upload.getProgress().getPercentTransferred());
        }

        // Add progressListener to listen asynchronous notifications about your transfer's progress
        // Uncomment below code snippet during development
        /*upload.addProgressListener(new ProgressListener() {
           public void progressChanged(ProgressEvent event) {
              if (LOGGER.isDebugEnabled()) {
          LOGGER.debug("Transferred bytes: " + (long) event.getBytesTransferred());
              }
        }
        });*/

        try {
            //Block the current thread and wait for completion
            //If the transfer fails AmazonClientException will be thrown
            upload.waitForCompletion();
        } catch (AmazonClientException | InterruptedException excp) {
            LOGGER.error("Exception occured while waiting for transfer: ", excp);
        }
    } finally {
        AWSUtil.deleteTempFile(tempFile); // Delete the temporary file once uploaded
    }
    LOGGER.info("End: {} , State: {} , Progress (%): {}", upload.getDescription(), upload.getState(),
            upload.getProgress().getPercentTransferred());
    return upload.isDone();
}

From source file:com.github.abhinavmishra14.aws.s3.service.impl.AwsS3IamServiceImpl.java

License:Open Source License

@Override
public Upload uploadFileAsync(final String bucketName, final String fileName, final File fileObj,
        final boolean isPublicAccessible) throws AmazonClientException, AmazonServiceException, IOException {
    LOGGER.info("uploadObjectAsync invoked, bucketName: {} , fileName: {} and isPublicAccessible: {}",
            bucketName, fileName, isPublicAccessible);
    final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, fileObj);
    if (isPublicAccessible) {
        putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
    }//from   w  w w . jav  a  2 s .  c  o m
    final TransferManager transferMgr = new TransferManager(s3client);
    return transferMgr.upload(putObjectRequest);
}