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

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

Introduction

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

Prototype

public ObjectMetadata() 

Source Link

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);//  w  w  w. ja  v a2s  .  c  o  m
    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);//from   w ww . j  ava 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 {//from   w  w  w . java  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));
 }

From source file:com.mesosphere.dcos.cassandra.executor.backup.S3StorageDriver.java

License:Apache License

@Override
public void uploadSchema(BackupRestoreContext ctx, String schema) throws Exception {
    final String nodeId = ctx.getNodeId();
    final AmazonS3Client amazonS3Client = getAmazonS3Client(ctx);
    final String key = getPrefixKey(ctx) + "/" + nodeId + "/" + StorageUtil.SCHEMA_FILE;
    final InputStream stream = new ByteArrayInputStream(schema.getBytes(StandardCharsets.UTF_8));

    amazonS3Client.putObject(getBucketName(ctx), key, stream, new ObjectMetadata());
}

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

public static String upload(InputStream inputStream, long fileSize, String URI) {
    String publicURL;/*from   w w w.j ava  2 s .  com*/
    //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  w  w .  j a  va2s.  c o  m
        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/*from w  w w  . j  a v  a2  s.c o m*/
 * @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.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.mweagle.tereus.aws.S3Resource.java

License:Open Source License

public Optional<String> upload() {
    try {/*from www.j  ava2 s  .c om*/
        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;
}