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

License:Open Source License

@Override
public boolean hasWritePermissionOnBucket(final String bucketName) {
    LOGGER.info("Checking bucket write permission..");
    boolean hasWritePermissions = false;
    final ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(0);/*from ww w  . j a  v a  2s  . c  o m*/
    // Create empty content
    final InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
    // Create a PutObjectRequest with test object
    final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,
            AWSUtilConstants.SAMPLE_FILE_NAME, emptyContent, metadata);
    try {
        if (s3client.putObject(putObjectRequest) != null) {
            LOGGER.info("Permissions validated!");
            //User has write permissions, TestPassed. 
            hasWritePermissions = true;
            //Delete the test object
            deleteObject(bucketName, AWSUtilConstants.SAMPLE_FILE_NAME);
        }
    } catch (AmazonClientException s3Ex) {
        LOGGER.warn("Write permissions not available!", s3Ex.getMessage());
    }
    return hasWritePermissions;
}

From source file:com.gst.infrastructure.documentmanagement.contentrepository.S3ContentRepository.java

License:Apache License

private void uploadDocument(final String filename, final InputStream inputStream, final String s3UploadLocation)
        throws ContentManagementException {
    try {/*from w w w.  jav  a2 s  .  c  o m*/
        logger.info("Uploading a new object to S3 from a file to " + s3UploadLocation);
        this.s3Client.putObject(
                new PutObjectRequest(this.s3BucketName, s3UploadLocation, inputStream, new ObjectMetadata()));
    } catch (final AmazonClientException ace) {
        final String message = ace.getMessage();
        throw new ContentManagementException(filename, message);
    }
}

From source file:com.ibm.stocator.fs.cos.COSAPIClient.java

License:Apache License

@Override
public FSDataOutputStream createObject(String objName, String contentType, Map<String, String> metadata,
        Statistics statistics) throws IOException {
    try {/*  w w  w  .  j a v  a  2 s  .  co m*/
        String objNameWithoutBuket = objName;
        if (objName.startsWith(mBucket + "/")) {
            objNameWithoutBuket = objName.substring(mBucket.length() + 1);
        }
        if (blockUploadEnabled) {
            return new FSDataOutputStream(new COSBlockOutputStream(this, objNameWithoutBuket,
                    new SemaphoredDelegatingExecutor(threadPoolExecutor, blockOutputActiveBlocks, true),
                    partSize, blockFactory, contentType, new WriteOperationHelper(objNameWithoutBuket),
                    metadata), null);
        }

        if (!contentType.equals(Constants.APPLICATION_DIRECTORY)) {
            return new FSDataOutputStream(
                    new COSOutputStream(mBucket, objName, mClient, contentType, metadata, transfers, this),
                    statistics);
        } else {
            final InputStream im = new InputStream() {
                @Override
                public int read() throws IOException {
                    return -1;
                }
            };
            final ObjectMetadata om = new ObjectMetadata();
            om.setContentLength(0L);
            om.setContentType(contentType);
            om.setUserMetadata(metadata);
            // Remove the bucket name prefix from key path
            if (objName.startsWith(mBucket + "/")) {
                objName = objName.substring(mBucket.length() + 1);
            }
            /*
            if (!objName.endsWith("/")) {
              objName = objName + "/";
            }*/
            LOG.debug("bucket: {}, key {}", mBucket, objName);
            PutObjectRequest putObjectRequest = new PutObjectRequest(mBucket, objName, im, om);
            Upload upload = transfers.upload(putObjectRequest);
            upload.waitForUploadResult();
            OutputStream fakeStream = new OutputStream() {

                @Override
                public void write(int b) throws IOException {
                }

                @Override
                public void close() throws IOException {
                    super.close();
                }
            };
            return new FSDataOutputStream(fakeStream, statistics);
        }
    } catch (InterruptedException e) {
        throw new InterruptedIOException("Interrupted creating " + objName);
    } catch (IOException e) {
        LOG.error(e.getMessage());
        throw e;
    }
}

From source file:com.ibm.stocator.fs.cos.COSAPIClient.java

License:Apache License

/**
 * Create a {@link PutObjectRequest} request.
 * The metadata is assumed to have been configured with the size of the
 * operation./*from  w w  w. j a  v  a  2  s.  c o  m*/
 * @param key key of object
 * @param metadata metadata header
 * @param inputStream source data
 * @return the request
 */
private PutObjectRequest newPutObjectRequest(String key, ObjectMetadata metadata, InputStream inputStream) {
    PutObjectRequest putObjectRequest = new PutObjectRequest(mBucket, key, inputStream, metadata);
    return putObjectRequest;
}

From source file:com.jeet.s3.AmazonS3ClientWrapper.java

License:Open Source License

public boolean uploadFile(String path, InputStream is, String hash, Long fileLength) {
    boolean isFileUploaded = false;
    try {//from   w w w  .  j a  va2 s  .  c om
        ObjectMetadata objectMetadata = new ObjectMetadata();
        Map userMetadata = new HashMap();
        userMetadata.put(Constants.FILE_LENGTH_KEY, fileLength.toString());
        userMetadata.put(Constants.HASH_KEY, hash);
        userMetadata.put(Constants.LAST_MODIFIED_KEY, String.valueOf(new Date().getTime()));
        objectMetadata.setUserMetadata(userMetadata);
        PutObjectResult objectResult = s3Client
                .putObject(new PutObjectRequest(Constants.BUCKET_NAME, path, is, objectMetadata));
        if (!StringUtils.isEmpty(objectResult.getContentMd5())) {
            isFileUploaded = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return isFileUploaded;
}

From source file:com.johnstok.blobs.s3.S3ByteStore.java

License:Open Source License

/** {@inheritDoc}  */
@Override//  w ww.ja v  a 2s .c  o m
public void update(final UUID id, final InputStream in) throws ByteStoreException {
    Objects.requireNonNull(in);
    Objects.requireNonNull(id);
    try {
        /*
        FIXME: In general, when your object size reaches 100 MB, you should consider
        using multipart uploads instead of uploading the object in a single operation.
                
        http://docs.aws.amazon.com/AmazonS3/latest/dev/uploadobjusingmpu.html
         */
        _s3Client.putObject(new PutObjectRequest(_bucket, id.toString(), in, new ObjectMetadata()));
    } catch (final AmazonClientException e) {
        throw new ByteStoreException(e);
    }
}

From source file:com.kittypad.music.game.util.S3StorageManager.java

License:Open Source License

/**
 * Stores a given item on S3/*from ww w . ja  v a  2s .  c  om*/
 * @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(MusicItem obj, byte[] data, boolean reducedRedundancy, CannedAccessControlList acl) {
    // Make sure the bucket exists before we try to use it
    //checkForAndCreateBucket(this.bucketName);
    String key = obj.getUUID() + obj.getMusicName() + "." + obj.getType();
    ObjectMetadata omd = new ObjectMetadata();
    omd.setContentType(mimeType);
    omd.setContentLength(obj.getSize());
    ByteArrayInputStream is = new ByteArrayInputStream(data);
    PutObjectRequest request = new PutObjectRequest(bucketName, key, 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(bucketName, key, acl);
    }
}

From source file:com.mateusz.mateuszsqs.SQSConfig.java

public static void processFile(String key, AmazonS3 s3, String bucketName) throws IOException {
    System.out.println("Downloading an object");
    S3Object object = s3.getObject(new GetObjectRequest(bucketName, key));
    System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
    System.out.println("Deleting an object\n");
    s3.deleteObject(bucketName, key);/*  ww  w  .  j a v a  2 s . c o  m*/
    System.out.println("Processing...");
    System.out.println("Uploading a new object to S3 from a file\n");
    InputStream changedStream = procesIamge(object.getObjectContent());
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(changedStream.available());
    metadata.setLastModified(new Date(System.currentTimeMillis()));
    s3.putObject(new PutObjectRequest(bucketName, key, changedStream, metadata));
}

From source file:com.maya.portAuthority.util.ImageUploader.java

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

     AWSCredentials credentials = new BasicAWSCredentials("AKIAJBFSMHRTIQQ7BKYA",
             "AdHgeP4dyWInWwPn9YlfxFCm3qP1lHjdxOxeJqDa");

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

     String folderName = "image"; //folder name
     //    String bucketName = "ppas-image-upload"; //must be unique

     try {//ww w.  j a  v 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.maya.portAuthority.util.ImageUploader.java

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

     AWSCredentials credentials = new BasicAWSCredentials("<Your access key id>", "<Your secret access key>");

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

     String folderName = "image";
     String bucketName = "ppas-image-upload";
     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));
 }