Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save skingsland/d2341cd52cd36c6cbb6f to your computer and use it in GitHub Desktop.
Save skingsland/d2341cd52cd36c6cbb6f to your computer and use it in GitHub Desktop.
import java.io.IOException;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.UncheckedExecutionException;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.jclouds.blobstore.BlobStore;
import org.jclouds.blobstore.domain.Blob;
/**
* An OutputStream that buffers the contents in memory, and writes them to an object store when the stream is closed.
*/
public class JcloudsObjectWritingByteArrayOutputStream extends ByteArrayOutputStream {
// prevents the blob from being written to the blob store multiple times, if close() is called more than once
private boolean isBlobWritten;
private final BlobStore blobStore;
private final String containerName;
private final String blobName;
public JcloudsObjectWritingByteArrayOutputStream(BlobStore blobStore, String containerName, String blobName) {
this.blobStore = Preconditions.checkNotNull(blobStore);
this.containerName = Preconditions.checkNotNull(containerName);
this.blobName = Preconditions.checkNotNull(blobName);
}
// the client will have to call this when he's finished writing, so this is our chance to upload the blob,
// now that we have the full payload in memory
@Override
public void close() throws IOException {
if (!this.isBlobWritten) {
writeBytesToBlob();
}
super.close();
}
private void writeBytesToBlob() throws IOException {
byte[] payload = toByteArray();
try {
Blob blob = this.blobStore.blobBuilder(this.blobName)
.payload(payload)
.contentLength(payload.length)
.build();
this.blobStore.putBlob(this.containerName, blob);
}
catch (UncheckedExecutionException e) { // this exception is not useful, so grab the cause
throw new IOException(getExceptionMessage(), e.getCause());
}
catch (Exception e) {
throw new IOException(getExceptionMessage(), e);
}
this.isBlobWritten = true;
}
private String getExceptionMessage() {
return String.format("Failed to write the resource! object store: %s, container: %s, resource: %s",
this.blobStore.toString(), this.containerName, this.blobName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment