surrey.repository.impl.S3RepositoryFile.java Source code

Java tutorial

Introduction

Here is the source code for surrey.repository.impl.S3RepositoryFile.java

Source

/**
 * 
 */
package surrey.repository.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

import org.apache.log4j.Logger;

import surrey.repository.RepositoryFile;

import com.amazonaws.services.s3.model.GetObjectRequest;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;

/*
Copyright (c) 2014 Surrey Hughes
    
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
    
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
    
The Software shall be used for Good, not Evil.
    
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
 * Stores files in S3.
 * 
 * Uses the Amazon TransferManager to manage multipart upload as required.
 * 
 * @author Surrey
 * 
 */
public class S3RepositoryFile implements RepositoryFile {

    private static Logger logger = Logger.getLogger(S3RepositoryFile.class);

    private String key; // path to file
    private String bucketName;
    private TransferManager transferManager;
    private ObjectMetadata metadata;

    public S3RepositoryFile(String bucketName, String key, TransferManager transferManager) {
        this.key = key;
        this.bucketName = bucketName;
        this.transferManager = transferManager;
    }

    /**
     * @see surrey.repository.RepositoryFile#delete()
     */
    @Override
    public boolean delete() {
        try {
            transferManager.getAmazonS3Client().deleteObject(bucketName, key);
            return true;
        } catch (Exception e) {
            logger.error("Failed to delete object from S3.  Bucket: " + bucketName + " key: " + key, e);
            return false;
        }
    }

    @Override
    public boolean exists() {

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.withBucketName(bucketName).withPrefix(key);
        listObjectsRequest.setMaxKeys(1);
        ObjectListing listing = transferManager.getAmazonS3Client().listObjects(listObjectsRequest);

        return listing.getObjectSummaries() != null && listing.getObjectSummaries().size() > 0;
    }

    /**
     * @see surrey.repository.RepositoryFile#getRepositoryPath()
     */
    @Override
    public String getRepositoryPath() {
        return key;
    }

    /**
     * @see surrey.repository.RepositoryFile#write(java.io.InputStream)
     */
    @Override
    public void write(InputStream source) throws IOException {
        transferManager.upload(bucketName, key, source, null);
    }

    @Override
    public void write(InputStream source, long size) throws IOException {
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(size);

        Upload upload = transferManager.upload(bucketName, key, source, meta);
        logger.info("Uploading to S3: " + upload.getDescription());
        try {
            upload.waitForUploadResult();
        } catch (Exception e) {
            logger.error("Failed to upload: " + upload.getDescription() + "\n" + e, e);
        }
    }

    @Override
    public void write(File source) throws IOException {
        Upload upload = transferManager.upload(bucketName, key, source);
        logger.info("Uploading to S3: " + upload.getDescription());
        try {
            upload.waitForUploadResult();
        } catch (Exception e) {
            logger.error("Failed to upload: " + upload.getDescription() + "\n" + e, e);
        }
    }

    /**
     * @see surrey.repository.RepositoryFile#getInputStream()
     */
    @Override
    public InputStream getInputStream() throws IOException {
        S3Object object = transferManager.getAmazonS3Client().getObject(bucketName, key);
        long contentLength = object.getObjectMetadata().getContentLength();
        S3AbortingInputStream in = new S3AbortingInputStream(object.getObjectContent(), contentLength);
        return in;
    }

    /**
     * @see surrey.repository.RepositoryFile#getInputStream(long, long)
     */
    @Override
    public InputStream getInputStream(long start, long length) throws IOException {
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        getObjectRequest.setRange(start, start + length - 1);
        S3Object object = transferManager.getAmazonS3Client().getObject(getObjectRequest);
        return new S3AbortingInputStream(object.getObjectContent(), length);
    }

    @Override
    public Date getLastModified() {
        loadMetaData();
        return metadata.getLastModified();
    }

    private void loadMetaData() {
        if (metadata == null) {
            metadata = transferManager.getAmazonS3Client().getObjectMetadata(bucketName, key);
        }
    }

    @Override
    public String getFileName() {
        String fileName = key;
        if (fileName.indexOf("/") > -1) {
            fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
        }
        return fileName;
    }

    @Override
    public long getLength() {
        loadMetaData();
        return metadata.getContentLength();
    }

    @Override
    public String getETag() {
        loadMetaData();
        return metadata.getETag();
    }

}