surrey.repository.impl.S3Repository.java Source code

Java tutorial

Introduction

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

Source

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

import java.io.ByteArrayInputStream;
import java.io.IOException;

import surrey.repository.RepositoryFile;

import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.InstanceProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ListObjectsRequest;
import com.amazonaws.services.s3.model.ObjectListing;
import com.amazonaws.services.s3.model.S3ObjectSummary;
import com.amazonaws.services.s3.transfer.TransferManager;

/*
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.
*/
/**
 * Uses S3 as a repository. baseURL is the bucketName for this repository
 * 
 * @author Surrey
 * 
 */
public class S3Repository extends BaseRepository {

    private AWSCredentialsProvider credentialsProvider = new InstanceProfileCredentialsProvider();
    private AmazonS3 s3;
    private boolean initialised = false;
    private TransferManager transferManager;

    /**
     * Can be called by ahead of time to speed initial file processing.
     * Otherwise this will be called by the first call to this repository
     */
    public void initialise() {
        if (!initialised) {
            if (credentialsProvider != null) {
                s3 = new AmazonS3Client(credentialsProvider);
            } else {
                s3 = new AmazonS3Client();
            }
            if (!s3.doesBucketExist(baseURL)) {
                throw new IllegalArgumentException(
                        "baseURL must specify an existing bucket.  The repository does not create buckets.");
            }

            transferManager = new TransferManager(s3);
            initialised = true;
        }
    }

    /**
     * @see surrey.repository.Repository#getFile(java.lang.String)
     */
    @Override
    public RepositoryFile getFile(String url) {
        initialise();
        String cleanUrl = url != null ? url.replaceAll("\\\\", "/") : "";
        if (cleanUrl.startsWith("/")) {
            cleanUrl = cleanUrl.substring(1);
        }
        String key = cleanUrl;
        return new S3RepositoryFile(baseURL, key, transferManager);
    }

    /**
     * @throws IOException
     * @see surrey.repository.Repository#createUniqueFile(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public RepositoryFile createUniqueFile(String prefix, String name) throws IOException {
        initialise();
        String cleanPrefix = prefix != null ? prefix.replaceAll("\\\\", "/") : "empty";
        if (cleanPrefix.startsWith("/")) {
            cleanPrefix = cleanPrefix.substring(1);
        }
        // create name, get list of files with that name
        String finalUri = cleanPrefix + getEnd(cleanPrefix);

        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        String result = finalUri + name;
        listObjectsRequest.withBucketName(baseURL).withPrefix(result);
        listObjectsRequest.setMaxKeys(20);
        ObjectListing listing = s3.listObjects(listObjectsRequest);
        int counter = 0;
        while (listing.getObjectSummaries() != null && listing.getObjectSummaries().size() > 0) {
            boolean found = false;
            boolean firstCall = true;
            do {
                if (!firstCall) {
                    listing = s3.listNextBatchOfObjects(listing);
                }
                for (S3ObjectSummary summary : listing.getObjectSummaries()) {
                    if (summary.getKey().equals(result)) {
                        result = finalUri + counter++ + name;
                        found = true;
                        break;
                    }
                }
                if (found) {
                    break;
                }
                firstCall = false;
            } while (listing.isTruncated());
            if (!found) {
                break;
            }
            listObjectsRequest.setPrefix(result);
            listing = s3.listObjects(listObjectsRequest);
        }
        // result is now what should be used so create a zero byte file to lock
        // that name to us

        S3RepositoryFile repoFile = new S3RepositoryFile(baseURL, result, transferManager);
        ByteArrayInputStream source = new ByteArrayInputStream(new byte[] { (byte) 0 });
        repoFile.write(source, 1);
        return repoFile;
    }

    /**
     * @return the transferManager
     */
    public TransferManager getTransferManager() {
        return transferManager;
    }

    /**
     * @param transferManager
     *            the transferManager to set
     */
    public void setTransferManager(TransferManager transferManager) {
        this.transferManager = transferManager;
    }

    /**
     * @return the credentialsProvider
     */
    public AWSCredentialsProvider getCredentialsProvider() {
        return credentialsProvider;
    }

    /**
     * @param credentialsProvider
     *            the credentialsProvider to set
     */
    public void setCredentialsProvider(AWSCredentialsProvider credentialsProvider) {
        this.credentialsProvider = credentialsProvider;
    }

}