There are several good ways to upload content to an S3 bucket in the Java world - in this article we'll look at what the jclouds library provides for this purpose.
To use jclouds - specifically the APIs discussed in this article, this simple Maven dependency should be added to the pom of the project:
<dependency> <groupId>org.jclouds</groupId><artifactId>jclouds-allblobstore</artifactId> <version>1.5.9</version> </dependency>
1. Uploading to Amazon S3
The first step, in order to access any of these APIs, is to create a BlobStoreContext:
BlobStoreContext context = ContextBuilder.newBuilder("aws-s3").credentials(identity, credentials) .buildView(BlobStoreContext.class);
This represents the entry-point to a general key-value storage service, such as Amazon S3 - but not limited to it.
For the more specific S3 only implementation, the context can be created similarly:
BlobStoreContext context = ContextBuilder.newBuilder("aws-s3").credentials(identity, credentials) .buildView(S3BlobStoreContext.class);
And even more specifically:
BlobStoreContext context = ContextBuilder.newBuilder("aws-s3").credentials(identity, credentials) .buildView(AWSS3BlobStoreContext.class);
When the authenticated context is no longer needed, closing it is required to release all resources - threads and connections - associated to it.
2. The four S3 APIs of jclouds
The jclouds library provides four different APIs to upload content to S3 bucket, ranging from simple but inflexible to complex and powerful, all obtained via the BlobStoreContext. Let's start with the simplest.
2.1. Upload via the Map API
The easiest way jclouds can be used to interact with an S3 bucket is by representing that bucket as a Map. The API is obtained from the context:
InputStreamMap bucket = context.createInputStreamMap("bucketName");
Then, to upload a simple HTML file:
bucket.putString("index1.html", "<html><body>hello world1</body></html>");
The InputStreamMap API exposes several other types of PUT operations - files, raw bytes - both for single and bulk.