Java tutorial
/* * Copyright 2011 Oliver B. Fischer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.fischer.thotti.s3.clients; import com.amazonaws.services.s3.AmazonS3Client; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.s3.model.PutObjectResult; import com.amazonaws.services.s3.model.S3ObjectSummary; import de.fischer.thotti.awscommon.AWSAccessCredentials; import de.fischer.thotti.core.logging.LoggingSupport; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; /** * Uploads one or more files to a given bucket on Amazon S3. * * @author Oliver B. Fischer */ public class S3FileUploader extends S3InternalClient { // @todo Add logging private static Logger logger = LoggerFactory.getLogger(S3FileUploader.class); private ObjectListing objectsInBucket; public S3FileUploader(AWSAccessCredentials credentials) { super(credentials, null); } public S3FileUploader(AWSAccessCredentials credentials, LoggingSupport loggingSupport) { super(credentials, loggingSupport); } public void put(String bucket, File... files) { preparePut(bucket); for (File file : files) { putObjectInternal(bucket, file); } } private void preparePut(String bucketName) { AmazonS3Client client = getAmazonS3Client(); /* * Obtain the list of already existing objects in the * bucket to check if the object already exists. */ ObjectListing bucketObjects = client.listObjects(bucketName); setObjectsInBucket(bucketObjects); } private void setObjectsInBucket(ObjectListing objects) { objectsInBucket = objects; } public ObjectListing getObjectsInBucket() { return objectsInBucket; } protected boolean isKeyKnownInBucket(String key) { // @todo This is a brute force search! May use binary search? Is it sorted? for (S3ObjectSummary summary : getObjectsInBucket().getObjectSummaries()) { if (key.equals(summary.getKey())) { return true; } } return false; } private void putObjectInternal(String bucket, File file) { boolean keyAlreadyInUse = isKeyKnownInBucket(file.getName()); if (!keyAlreadyInUse) { AmazonS3Client client = getAmazonS3Client(); PutObjectResult result = client.putObject(bucket, file.getName(), file); getLoggingSupport().info("Uploaded %s to S3 as %s/%s.", file.getName(), bucket, file.getName()); } else { getLoggingSupport().warn("Key %s is already in use for bucket %s.", file.getName(), bucket); } } }