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

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

Introduction

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

Prototype

public PutObjectRequest(String bucketName, String key, InputStream input, ObjectMetadata metadata) 

Source Link

Document

Constructs a new PutObjectRequest object to upload a stream of data to the specified bucket and key.

Usage

From source file:com.ALC.SC2BOAserver.aws.S3StorageManager.java

License:Open Source License

/**
 * Stores a given item on S3// ww  w .  j a v  a  2 s  .  co m
 * @param obj the data to be stored
 * @param reducedRedundancy whether or not to use reduced redundancy storage
 * @param acl a canned access control list indicating what permissions to store this object with (can be null to leave it set to default)
 */
public void store(SC2BOAStorageObject obj, boolean reducedRedundancy, CannedAccessControlList acl) {
    // Make sure the bucket exists before we try to use it
    checkForAndCreateBucket(obj.getBucketName());

    ObjectMetadata omd = new ObjectMetadata();
    omd.setContentType(obj.getMimeType());
    omd.setContentLength(obj.getData().length);

    ByteArrayInputStream is = new ByteArrayInputStream(obj.getData());
    PutObjectRequest request = new PutObjectRequest(obj.getBucketName(), obj.getStoragePath(), is, omd);

    // Check if reduced redundancy is enabled
    if (reducedRedundancy) {
        request.setStorageClass(StorageClass.ReducedRedundancy);
    }

    s3Client.putObject(request);

    // If we have an ACL set access permissions for the the data on S3
    if (acl != null) {
        s3Client.setObjectAcl(obj.getBucketName(), obj.getStoragePath(), acl);
    }

}

From source file:com.amazon.aws.samplecode.travellog.aws.S3StorageManager.java

License:Open Source License

/**
 * Stores a given item on S3//  w  ww .  jav  a  2  s . c o m
 * @param obj the data to be stored
 * @param reducedRedundancy whether or not to use reduced redundancy storage
 * @param acl a canned access control list indicating what permissions to store this object with (can be null to leave it set to default)
 */
public void store(TravelLogStorageObject obj, boolean reducedRedundancy, CannedAccessControlList acl) {
    //Make sure the bucket exists before we try to use it
    checkForAndCreateBucket(obj.getBucketName());

    ObjectMetadata omd = new ObjectMetadata();
    omd.setContentType(obj.getMimeType());
    omd.setContentLength(obj.getData().length);

    ByteArrayInputStream is = new ByteArrayInputStream(obj.getData());
    PutObjectRequest request = new PutObjectRequest(obj.getBucketName(), obj.getStoragePath(), is, omd);

    //Check if reduced redundancy is enabled
    if (reducedRedundancy) {
        request.setStorageClass(StorageClass.ReducedRedundancy);
    }

    s3client.putObject(request);

    //If we have an ACL set access permissions for the the data on S3
    if (acl != null) {
        s3client.setObjectAcl(obj.getBucketName(), obj.getStoragePath(), acl);
    }

}

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 .  j a  va2  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.amazon.sqs.javamessaging.AmazonSQSExtendedClient.java

License:Open Source License

private void storeTextInS3(String s3Key, String messageContentStr, Long messageContentSize) {
    InputStream messageContentStream = new ByteArrayInputStream(
            messageContentStr.getBytes(StandardCharsets.UTF_8));
    ObjectMetadata messageContentStreamMetadata = new ObjectMetadata();
    messageContentStreamMetadata.setContentLength(messageContentSize);
    PutObjectRequest putObjectRequest = new PutObjectRequest(clientConfiguration.getS3BucketName(), s3Key,
            messageContentStream, messageContentStreamMetadata);
    try {/*  w ww  .ja  v a2  s.c  om*/
        clientConfiguration.getAmazonS3Client().putObject(putObjectRequest);
    } catch (AmazonServiceException e) {
        String errorMessage = "Failed to store the message content in an S3 object. SQS message was not sent.";
        LOG.error(errorMessage, e);
        throw new AmazonServiceException(errorMessage, e);
    } catch (AmazonClientException e) {
        String errorMessage = "Failed to store the message content in an S3 object. SQS message was not sent.";
        LOG.error(errorMessage, e);
        throw new AmazonClientException(errorMessage, e);
    }
}

From source file:com.amazon.util.ImageUploader.java

public static void uploadImage(String imageURL, String imageName, String folderName, String bucketName)
        throws MalformedURLException, IOException {
    // credentials object identifying user for authentication

    AWSCredentials credentials = new BasicAWSCredentials(System.getenv("AWS_S3_ACCESS_KEY"),
            System.getenv("AWS_S3_SECRET_ACCESS_KEY"));

    // create a client connection based on credentials
    AmazonS3 s3client = new AmazonS3Client(credentials);

    try {/*from   www  . j av a 2  s .  c o  m*/
        if (!(s3client.doesBucketExist(bucketName))) {
            s3client.setRegion(Region.getRegion(Regions.US_EAST_1));
            // Note that CreateBucketRequest does not specify region. So bucket is 
            // created in the region specified in the client.
            s3client.createBucket(new CreateBucketRequest(bucketName));
        }

        //Enabe CORS:
        //     <?xml version="1.0" encoding="UTF-8"?>
        //<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
        //    <CORSRule>
        //        <AllowedOrigin>http://ask-ifr-download.s3.amazonaws.com</AllowedOrigin>
        //        <AllowedMethod>GET</AllowedMethod>
        //    </CORSRule>
        //</CORSConfiguration>
        BucketCrossOriginConfiguration configuration = new BucketCrossOriginConfiguration();

        CORSRule corsRule = new CORSRule()
                .withAllowedMethods(
                        Arrays.asList(new CORSRule.AllowedMethods[] { CORSRule.AllowedMethods.GET }))
                .withAllowedOrigins(Arrays.asList(new String[] { "http://ask-ifr-download.s3.amazonaws.com" }));
        configuration.setRules(Arrays.asList(new CORSRule[] { corsRule }));
        s3client.setBucketCrossOriginConfiguration(bucketName, configuration);

    } 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());
    }

    String fileName = folderName + SUFFIX + imageName + ".png";
    URL url = new URL(imageURL);

    ObjectMetadata omd = new ObjectMetadata();
    omd.setContentType("image/png");
    omd.setContentLength(url.openConnection().getContentLength());
    // upload file to folder and set it to public
    s3client.putObject(new PutObjectRequest(bucketName, fileName, url.openStream(), omd)
            .withCannedAcl(CannedAccessControlList.PublicRead));
}

From source file:com.amediamanager.dao.DynamoDbUserDaoImpl.java

License:Apache License

/**
 * Upload the profile pic to S3 and return it's URL
 * @param profilePic//w  w w .  j  ava 2  s. c o  m
 * @return The fully-qualified URL of the photo in S3
 * @throws IOException
 */
public String uploadFileToS3(CommonsMultipartFile profilePic) throws IOException {

    // Profile pic prefix
    String prefix = config.getProperty(ConfigProps.S3_PROFILE_PIC_PREFIX);

    // Date string
    String dateString = new SimpleDateFormat("ddMMyyyy").format(new java.util.Date());
    String s3Key = prefix + "/" + dateString + "/" + UUID.randomUUID().toString() + "_"
            + profilePic.getOriginalFilename();

    // Get bucket
    String s3bucket = config.getProperty(ConfigProps.S3_UPLOAD_BUCKET);

    // Create a ObjectMetadata instance to set the ACL, content type and length
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentType(profilePic.getContentType());
    metadata.setContentLength(profilePic.getSize());

    // Create a PutRequest to upload the image
    PutObjectRequest putObject = new PutObjectRequest(s3bucket, s3Key, profilePic.getInputStream(), metadata);

    // Put the image into S3
    s3Client.putObject(putObject);
    s3Client.setObjectAcl(s3bucket, s3Key, CannedAccessControlList.PublicRead);

    return "http://" + s3bucket + ".s3.amazonaws.com/" + s3Key;
}

From source file:com.awscrud.aws.S3StorageManager.java

License:Open Source License

/**
 * Stores a given item on S3// ww w.  j a  va 2  s .c o  m
 * @param obj the data to be stored
 * @param reducedRedundancy whether or not to use reduced redundancy storage
 * @param acl a canned access control list indicating what permissions to store this object with (can be null to leave it set to default)
 */
public void store(AwscrudStorageObject obj, boolean reducedRedundancy, CannedAccessControlList acl) {
    // Make sure the bucket exists before we try to use it
    checkForAndCreateBucket(obj.getBucketName());

    ObjectMetadata omd = new ObjectMetadata();
    omd.setContentType(obj.getMimeType());
    omd.setContentLength(obj.getData().length);

    ByteArrayInputStream is = new ByteArrayInputStream(obj.getData());
    PutObjectRequest request = new PutObjectRequest(obj.getBucketName(), obj.getStoragePath(), is, omd);

    // Check if reduced redundancy is enabled
    if (reducedRedundancy) {
        request.setStorageClass(StorageClass.ReducedRedundancy);
    }

    s3client.putObject(request);

    // If we have an ACL set access permissions for the the data on S3
    if (acl != null) {
        s3client.setObjectAcl(obj.getBucketName(), obj.getStoragePath(), acl);
    }

}

From source file:com.casadocodigo.ecommerce.infra.AmazonFileSaver.java

public String write(String baseFolder, Part multipartFile) throws IOException {

    String fileName = extractFilename(multipartFile.getHeader(CONTENT_DISPOSITION));

    String path = baseFolder + File.separator + fileName;

    AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());

    ObjectMetadata metaData = new ObjectMetadata();
    byte[] bytes = IOUtils.toByteArray(multipartFile.getInputStream());
    metaData.setContentLength(bytes.length);
    /*ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, byteArrayInputStream, metadata);
    client.putObject(putObjectRequest);*/

    s3client.putObject(new PutObjectRequest(BUCKET_NAME, path, multipartFile.getInputStream(), metaData)
            .withCannedAcl(CannedAccessControlList.PublicRead));

    /*s3client.putObject(BUCKET_NAME,fileName, 
        multipartFile.getInputStream(), metaData);*/
    return END_POINT + File.separator + BUCKET_NAME + File.separator + path;

}

From source file:com.cirrus.server.osgi.service.amazon.s3.AmazonS3StorageService.java

License:Apache License

@Override
public CirrusFolderData createDirectory(final String path) throws ServiceRequestFailedException {
    final ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(0);//from  ww  w  . jav a2  s.co m
    final InputStream emptyContent = new ByteArrayInputStream(new byte[0]);

    final String key = path + SEPARATOR;
    final PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, key, emptyContent, metadata);

    // Send request to S3 to create folder
    this.amazonS3Client.putObject(putObjectRequest);

    return new CirrusFolderData(key);
}

From source file:com.clicktravel.infrastructure.persistence.aws.s3.S3FileStore.java

License:Apache License

@Override
public void write(final FilePath filePath, final FileItem fileItem) {
    checkInitialization();/*  w  ww  . j ava2 s.co m*/

    final ObjectMetadata metadata = new ObjectMetadata();
    metadata.addUserMetadata(USER_METADATA_FILENAME, fileItem.filename());
    metadata.addUserMetadata(USER_METADATA_LAST_UPDATED_TIME, formatter.print(fileItem.lastUpdatedTime()));
    metadata.setContentLength(fileItem.getBytes().length);
    final InputStream is = new ByteArrayInputStream(fileItem.getBytes());
    final String bucketName = bucketNameForFilePath(filePath);
    if (!amazonS3Client.doesBucketExist(bucketName)) {
        createBucket(bucketName);
    }
    final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePath.filename(), is,
            metadata);
    amazonS3Client.putObject(putObjectRequest);
}