Example usage for com.amazonaws.services.s3.model ObjectMetadata setContentLength

List of usage examples for com.amazonaws.services.s3.model ObjectMetadata setContentLength

Introduction

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

Prototype

public void setContentLength(long contentLength) 

Source Link

Document

<p> Sets the Content-Length HTTP header indicating the size of the associated object in bytes.

Usage

From source file:com.lithium.flow.filer.S3Filer.java

License:Apache License

@Override
public void createDirs(@Nonnull String path) throws IOException {
    InputStream in = new ByteArrayInputStream(new byte[0]);
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(0);
    s3.putObject(bucket, path.substring(1) + "/", in, metadata);
}

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);// www . ja va 2  s . co  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 {/*from ww w .  jav a2  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));
 }

From source file:com.metamug.mtg.s3.uploader.S3Uploader.java

public static String upload(InputStream inputStream, long fileSize, String URI) {
    String publicURL;//from   www  .  j  av  a 2s. c om
    //ClientConfiguration max retry
    ObjectMetadata objectMetaData = new ObjectMetadata();
    objectMetaData.setContentLength(fileSize);
    //        objectMetaData.setContentType(IMAGE_CONTENT_TYPE);
    objectMetaData.setCacheControl("public");
    Calendar c = Calendar.getInstance();
    c.setTime(c.getTime());
    c.add(Calendar.MONTH, 6);
    String sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz").format(c.getTime());
    objectMetaData.setHeader("Expires", sdf);//Thu, 21 Mar 2042 08:16:32 GMT

    PutObjectResult por = s3Client
            .putObject(new PutObjectRequest(AWS_S3_BUCKET, URI, inputStream, objectMetaData)
                    .withCannedAcl(CannedAccessControlList.PublicRead));

    publicURL = "http://metamug.net/" + URI;
    return publicURL;
}

From source file:com.meteotester.util.S3Util.java

License:Open Source License

public static void saveFileToS3(File file) {
    try {/*from w  ww  .j  av  a2  s  . c om*/
        AWSCredentials myCredentials = new BasicAWSCredentials(Config.AWS_ACCESS_KEY, Config.AWS_SECRET_KEY);
        AmazonS3 s3client = new AmazonS3Client(myCredentials);

        s3client.setRegion(Region.getRegion(Regions.EU_WEST_1));
        String filename = file.getName();
        String path = file.getPath();

        PutObjectRequest req = new PutObjectRequest(Config.S3_BUCKETNAME, path, file);
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.length());
        String contentType = (filename.contains("json")) ? "application/json" : "text/csv";
        metadata.setContentType(contentType);
        req.setMetadata(metadata);

        s3client.putObject(req);

        log.info(filename + " stored in S3");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.moxtra.S3StorageManager.java

License:Open Source License

/**
 * Stores a given item on S3//  w w w . j av a 2s .  c  om
 * @param bucketname
 * @param key
 * @param data
 * @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(String bucketname, String key, byte[] data, CannedAccessControlList acl, String type) {

    // Make sure the bucket exists before we try to use it
    checkForAndCreateBucket(bucketname);

    ObjectMetadata omd = new ObjectMetadata();
    //omd.setContentType("text/html");
    omd.setContentType(type);
    omd.setContentLength(data.length);

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

    try {
        is.close();
    } catch (Exception e) {
        logger.log(Level.SEVERE, "Cannot close store AWS connection");
    }

}

From source file:com.mweagle.tereus.aws.S3Resource.java

License:Open Source License

public Optional<String> upload() {
    try {/*from  ww  w.j  av  a 2s  .co m*/
        DefaultAWSCredentialsProviderChain credentialProviderChain = new DefaultAWSCredentialsProviderChain();
        final TransferManager transferManager = new TransferManager(credentialProviderChain.getCredentials());

        final ObjectMetadata metadata = new ObjectMetadata();
        if (this.inputStreamLength.isPresent()) {
            metadata.setContentLength(this.inputStreamLength.get());
        }
        final PutObjectRequest uploadRequest = new PutObjectRequest(bucketName, keyName, this.inputStream,
                metadata);
        final Upload templateUpload = transferManager.upload(uploadRequest);

        templateUpload.waitForUploadResult();
        this.resourceURL = Optional.of(getS3Path());
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    return this.resourceURL;
}

From source file:com.netflix.exhibitor.core.backup.s3.MockS3Client.java

License:Apache License

@Override
public synchronized PutObjectResult putObject(PutObjectRequest request) throws Exception {
    Map<String, String> userData = Maps.newHashMap();
    userData.put(BYTES_HEADER, Integer.toString(uploadedBytes.size()));

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteStreams.copy(request.getInputStream(), out);
    byte[] bytes = out.toByteArray();
    uploadedBytes.add(bytes);//from w  w  w .ja v a  2  s  .c  o  m

    byte[] md5bytes = S3Utils.md5(bytes, out.size());

    S3Object object = new S3Object();
    object.setKey(request.getKey());
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(bytes.length);
    metadata.setUserMetadata(userData);
    object.setObjectMetadata(metadata);
    uploads.put(request.getKey(), object);

    PutObjectResult result = new PutObjectResult();
    result.setETag(S3Utils.toHex(md5bytes));
    return result;
}

From source file:com.netflix.exhibitor.core.config.s3.S3PseudoLock.java

License:Apache License

@Override
protected void createFile(String key, byte[] contents) throws Exception {
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(contents.length);
    PutObjectRequest request = new PutObjectRequest(bucket, key, new ByteArrayInputStream(contents), metadata);
    client.putObject(request);/*from  www .  j av  a 2  s.  co  m*/
}