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:com.github.abhinavmishra14.aws.s3.service.impl.AwsS3IamServiceImpl.java

License:Open Source License

@Override
public PutObjectResult createDirectory(final String bucketName, final String dirName,
        final boolean isPublicAccessible) throws AmazonClientException, AmazonServiceException {
    LOGGER.info("createDirectory invoked, bucketName: {}, dirName: {} and isPublicAccessible: {}", bucketName,
            dirName, isPublicAccessible);
    final ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(0);//ww w  . j av  a  2s  .  co  m
    // Create empty content,since creating empty folder needs an empty content
    final InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
    // Create a PutObjectRequest passing the directory name suffixed by '/'
    final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
            dirName + AWSUtilConstants.SEPARATOR, emptyContent, metadata);
    if (isPublicAccessible) {
        putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
    }
    return s3client.putObject(putObjectRequest);
}

From source file:com.mrbjoern.blog.api.service.s3.S3Wrapper.java

License:Open Source License

private PutObjectResult upload(InputStream inputStream, final String uploadKey) {
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, uploadKey, inputStream,
            new ObjectMetadata());
    putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);

    PutObjectResult putObjectResult = amazonS3Client.putObject(putObjectRequest);

    return putObjectResult;
}

From source file:com.vitembp.services.interfaces.AmazonSimpleStorageService.java

License:Open Source License

/**
 * Uploads a file to S3 storage and sets its ACL to allow public access.
 * @param toUpload The file to uploadPublic.
 * @param destination The destination in the bucket to store the file.
 * @throws java.io.IOException If an I/O exception occurs while uploading
 * the file.//from   w  w  w. java2 s .  co  m
 */
public void uploadPublic(File toUpload, String destination) throws IOException {
    try {
        // create a request that makes the object public
        PutObjectRequest req = new PutObjectRequest(this.bucketName, destination, toUpload);
        req.setCannedAcl(CannedAccessControlList.PublicRead);

        // uploadPublic the file and wait for completion
        Upload xfer = this.transferManager.upload(req);
        xfer.waitForCompletion();
    } catch (AmazonServiceException ex) {
        LOGGER.error("Exception uploading " + toUpload.toString(), ex);
        throw new IOException("Exception uploading " + toUpload.toString(), ex);
    } catch (AmazonClientException | InterruptedException ex) {
        LOGGER.error("Exception uploading " + toUpload.toString(), ex);
        throw new IOException("Exception uploading " + toUpload.toString(), ex);
    }
}

From source file:generator.components.S3FileUtility.java

License:Apache License

/**
 * Upload file to s3 bucket/*  ww  w .  j a  v  a2  s  .c  o m*/
 * 
 * @param file
 *            the object
 */
public String writeFileToS3(File file, FileLocation fileLocation) throws FileNotFoundException {

    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(file.length());
    String fileKey = String.format("%s-%s", uuidFactory.getUUID(), file.getName());

    // BasicAWSCredentials credentials = new BasicAWSCredentials(AMAZONS3_ACCESS_KEY, AMAZONS3_PRIVATE_KEY);
    s3Client = new AmazonS3Client();

    // Making the object public
    PutObjectRequest putObj = new PutObjectRequest(S3_OUTPUT_BUCKET, fileKey, file);
    putObj.setCannedAcl(CannedAccessControlList.PublicRead);
    s3Client.putObject(putObj);

    return fileKey;
}

From source file:gov.cdc.sdp.cbr.aphl.AphlS3Producer.java

License:Apache License

public void processSingleOp(final Exchange exchange) throws Exception {

    ObjectMetadata objectMetadata = determineMetadata(exchange);

    File filePayload = null;//  www.  jav  a 2  s.c  o  m
    InputStream is = null;
    Object obj = exchange.getIn().getMandatoryBody();
    PutObjectRequest putObjectRequest = null;
    // Need to check if the message body is WrappedFile
    if (obj instanceof WrappedFile) {
        obj = ((WrappedFile<?>) obj).getFile();
    }
    if (obj instanceof File) {
        filePayload = (File) obj;
        is = new FileInputStream(filePayload);
    } else {
        is = exchange.getIn().getMandatoryBody(InputStream.class);
    }

    putObjectRequest = new PutObjectRequest(getConfiguration().getBucketName(), determineKey(exchange), is,
            objectMetadata);

    String storageClass = determineStorageClass(exchange);
    if (storageClass != null) {
        putObjectRequest.setStorageClass(storageClass);
    }

    String cannedAcl = exchange.getIn().getHeader(S3Constants.CANNED_ACL, String.class);
    if (cannedAcl != null) {
        CannedAccessControlList objectAcl = CannedAccessControlList.valueOf(cannedAcl);
        putObjectRequest.setCannedAcl(objectAcl);
    }

    AccessControlList acl = exchange.getIn().getHeader(S3Constants.ACL, AccessControlList.class);
    if (acl != null) {
        // note: if cannedacl and acl are both specified the last one will
        // be used. refer to
        // PutObjectRequest#setAccessControlList for more details
        putObjectRequest.setAccessControlList(acl);
    }

    PutObjectResult putObjectResult = getEndpoint().getS3Client().putObject(putObjectRequest);

    Message message = getMessageForResponse(exchange);
    message.setHeader(S3Constants.E_TAG, putObjectResult.getETag());
    if (putObjectResult.getVersionId() != null) {
        message.setHeader(S3Constants.VERSION_ID, putObjectResult.getVersionId());
    }

    if (getConfiguration().isDeleteAfterWrite() && filePayload != null) {
        // close streams
        IOHelper.close(putObjectRequest.getInputStream());
        IOHelper.close(is);
        FileUtil.deleteFile(filePayload);
    }
}

From source file:io.konig.camel.aws.s3.DeleteObjectProducer.java

License:Apache License

public void processSingleOp(final Exchange exchange) throws Exception {

    ObjectMetadata objectMetadata = determineMetadata(exchange);

    File filePayload = null;/* w  ww  . j  a  v  a 2s .c  o  m*/
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    Object obj = exchange.getIn().getMandatoryBody();
    PutObjectRequest putObjectRequest = null;
    // Need to check if the message body is WrappedFile
    if (obj instanceof WrappedFile) {
        obj = ((WrappedFile<?>) obj).getFile();
    }
    if (obj instanceof File) {
        filePayload = (File) obj;
        is = new FileInputStream(filePayload);
    } else {
        is = exchange.getIn().getMandatoryBody(InputStream.class);
        baos = determineLengthInputStream(is);
        objectMetadata.setContentLength(baos.size());
        is = new ByteArrayInputStream(baos.toByteArray());
    }

    putObjectRequest = new PutObjectRequest(getConfiguration().getBucketName(), determineKey(exchange), is,
            objectMetadata);

    String storageClass = determineStorageClass(exchange);
    if (storageClass != null) {
        putObjectRequest.setStorageClass(storageClass);
    }

    String cannedAcl = exchange.getIn().getHeader(S3Constants.CANNED_ACL, String.class);
    if (cannedAcl != null) {
        CannedAccessControlList objectAcl = CannedAccessControlList.valueOf(cannedAcl);
        putObjectRequest.setCannedAcl(objectAcl);
    }

    AccessControlList acl = exchange.getIn().getHeader(S3Constants.ACL, AccessControlList.class);
    if (acl != null) {
        // note: if cannedacl and acl are both specified the last one will
        // be used. refer to
        // PutObjectRequest#setAccessControlList for more details
        putObjectRequest.setAccessControlList(acl);
    }

    if (getConfiguration().isUseAwsKMS()) {
        SSEAwsKeyManagementParams keyManagementParams;
        if (ObjectHelper.isNotEmpty(getConfiguration().getAwsKMSKeyId())) {
            keyManagementParams = new SSEAwsKeyManagementParams(getConfiguration().getAwsKMSKeyId());
        } else {
            keyManagementParams = new SSEAwsKeyManagementParams();
        }
        putObjectRequest.setSSEAwsKeyManagementParams(keyManagementParams);
    }

    LOG.trace("Put object [{}] from exchange [{}]...", putObjectRequest, exchange);

    PutObjectResult putObjectResult = getEndpoint().getS3Client().putObject(putObjectRequest);

    LOG.trace("Received result [{}]", putObjectResult);

    Message message = getMessageForResponse(exchange);
    message.setHeader(S3Constants.E_TAG, putObjectResult.getETag());
    if (putObjectResult.getVersionId() != null) {
        message.setHeader(S3Constants.VERSION_ID, putObjectResult.getVersionId());
    }

    if (getConfiguration().isDeleteAfterWrite() && filePayload != null) {
        // close streams
        IOHelper.close(putObjectRequest.getInputStream());
        IOHelper.close(is);
        FileUtil.deleteFile(filePayload);
    }
}

From source file:itcr.gitsnes.MainActivity.java

License:Open Source License

/** The method sendGame makes many functions:
 *      - Get all data from text boxes on layout add_game
 *      - Makes a random bucket key for a photo/file and put the object into the bucket
 *      - Wait for the success signal and send the JSON build from BackendHandler
 *        to app-engine (Google)/*from  ww  w. j  a  v a2s.  co m*/
 */
public void sendGame(View view) throws IOException {

    Toast.makeText(this, "Wait, we are uploading your game =) ", Toast.LENGTH_LONG);
    /* GET DATA FROM INTERFACE*/
    EditText name = (EditText) this.findViewById(R.id.txt_name);
    EditText description = (EditText) this.findViewById(R.id.txt_desc);
    EditText category = (EditText) this.findViewById(R.id.txt_cat);

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    /* GENERATE RANDOM KEYS FOR PHOTO AND FILE*/
    this.file_key = "" + UUID.randomUUID().toString().replace("-", "");
    this.image_key = "" + UUID.randomUUID().toString().replace("-", "");

    /* SAVING GAME FILE/PHOTO ON AWS BUCKET*/
    AmazonS3Client s3Client = new AmazonS3Client(
            new BasicAWSCredentials(KS.MY_ACCESS_KEY_ID, KS.MY_SECRET_KEY));

    PutObjectRequest putObjectRequestnew = new PutObjectRequest(KS.BUCKET_NAME, this.file_key, this.s3game);
    putObjectRequestnew.setCannedAcl(CannedAccessControlList.PublicRead);
    s3Client.putObject(putObjectRequestnew);

    PutObjectRequest putObjectImagenew = new PutObjectRequest(KS.BUCKET_IMG, this.image_key, this.s3image);
    putObjectImagenew.setCannedAcl(CannedAccessControlList.PublicRead);
    s3Client.putObject(putObjectImagenew);

    String actual_key = "none";
    String actual_image = "none";

    if (this.file_key != "none")
        actual_key = this.file_key;

    if (this.image_key != "none")
        actual_image = this.image_key;

    /* SEND JSON*/
    new BackendHandler().sendJSON(KS.getCurrent_user(), name.getText().toString(),
            category.getText().toString(), description.getText().toString(), actual_image, actual_key);
    Log.i(TAG, "Successful JSON send");
    Toast.makeText(this, "Congratulations your game has been sent", Toast.LENGTH_LONG);

}

From source file:md.djembe.aws.AmazonS3WebClient.java

License:Apache License

public static void uploadToBucket(final String filename, final File image) {

    PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, filename, image);
    putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
    if (putObjectRequest.getMetadata() == null) {
        putObjectRequest.setMetadata(new ObjectMetadata());
    }/*from  w w  w . j  a v  a  2 s  .c o  m*/
    putObjectRequest.getMetadata().setContentType("image/jpeg");

    AmazonS3 s3Client = getS3Client();
    s3Client.putObject(putObjectRequest);
    LOGGER.info("File Uploaded to Amazon S3.");
}

From source file:org.akvo.flow.deploy.Deploy.java

License:Open Source License

private static void uploadS3(String accessKey, String secretKey, String s3Path, File file)
        throws AmazonServiceException, AmazonClientException {
    BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
    AmazonS3 s3 = new AmazonS3Client(credentials);

    PutObjectRequest putRequest = new PutObjectRequest(BUCKET_NAME, s3Path, file);
    ObjectMetadata metadata = new ObjectMetadata();

    // set content type as android package file
    metadata.setContentType("application/vnd.android.package-archive");

    // set content length to length of file
    metadata.setContentLength(file.length());

    // set access to public
    putRequest.setMetadata(metadata);//from w w  w . jav  a2 s  .c  o  m
    putRequest.setCannedAcl(CannedAccessControlList.PublicRead);

    // try to put the apk in S3
    PutObjectResult result = s3.putObject(putRequest);
    System.out.println("Apk uploaded successfully, with result ETag " + result.getETag());
}

From source file:org.alanwilliamson.amazon.s3.BackgroundUploader.java

License:Open Source License

private void uploadFile(Map<String, Object> jobFile) {

    File localFile = new File((String) jobFile.get("localpath"));
    if (!localFile.isFile()) {
        removeJobFile(jobFile);// ww  w  . ja v a2s . com
        callbackCfc(jobFile, false, "local file no longer exists");
        cfEngine.log("AmazonS3Write.BackgroundUploader: file no longer exists=" + localFile.getName());
        return;
    }

    // Setup the object data
    ObjectMetadata omd = new ObjectMetadata();
    if (jobFile.containsKey("metadata"))
        omd.setUserMetadata((Map<String, String>) jobFile.get("metadata"));

    TransferManager tm = null;
    AmazonS3 s3Client = null;
    try {
        AmazonKey amazonKey = (AmazonKey) jobFile.get("amazonkey");
        s3Client = new AmazonBase().getAmazonS3(amazonKey);

        PutObjectRequest por = new PutObjectRequest((String) jobFile.get("bucket"), (String) jobFile.get("key"),
                localFile);
        por.setMetadata(omd);
        por.setStorageClass((StorageClass) jobFile.get("storage"));

        if (jobFile.containsKey("acl"))
            por.setCannedAcl(amazonKey.getAmazonCannedAcl((String) jobFile.get("acl")));

        if (jobFile.containsKey("aes256key"))
            por.setSSECustomerKey(new SSECustomerKey((String) jobFile.get("aes256key")));

        if (jobFile.containsKey("customheaders")) {
            Map<String, String> customheaders = (Map) jobFile.get("customheaders");

            Iterator<String> it = customheaders.keySet().iterator();
            while (it.hasNext()) {
                String k = it.next();
                por.putCustomRequestHeader(k, customheaders.get(k));
            }
        }

        long startTime = System.currentTimeMillis();
        tm = new TransferManager(s3Client);
        Upload upload = tm.upload(por);
        upload.waitForCompletion();

        log(jobFile, "Uploaded; timems=" + (System.currentTimeMillis() - startTime));

        removeJobFile(jobFile);
        callbackCfc(jobFile, true, null);

        if ((Boolean) jobFile.get("deletefile"))
            localFile.delete();

    } catch (Exception e) {
        log(jobFile, "Failed=" + e.getMessage());

        callbackCfc(jobFile, false, e.getMessage());

        int retry = (Integer) jobFile.get("retry");
        int attempt = (Integer) jobFile.get("attempt") + 1;

        if (retry == attempt) {
            removeJobFile(jobFile);
        } else {
            jobFile.put("attempt", attempt);
            jobFile.put("attemptdate", System.currentTimeMillis() + (Long) jobFile.get("retryms"));
            acceptFile(jobFile);
        }

        if (s3Client != null)
            cleanupMultiPartUploads(s3Client, (String) jobFile.get("bucket"));

    } finally {
        if (tm != null)
            tm.shutdownNow(true);
    }

}