/*
 * Licensed to the University of California, Berkeley under one or more contributor license
 * agreements. See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership. The ASF licenses this file to You 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 tachyon.underfs.s3;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import com.google.common.base.Preconditions;

import org.jets3t.service.S3Service;
import org.jets3t.service.ServiceException;
import org.jets3t.service.model.S3Object;
import org.jets3t.service.utils.Mimetypes;

import tachyon.util.CommonUtils;

/**
 * This class creates a streaming interface for writing a file in s3. The data will be persisted
 * to a temporary directory on local disk and copied as a complete file when the close() method is
 * called.
 */
public class S3OutputStream extends OutputStream {
  private final String mBucketName;
  private final String mKey;
  private final OutputStream mLocalOutputStream;
  private final File mFile;
  private final S3Service mClient;

  public S3OutputStream(String bucketName, String key, S3Service client) throws IOException {
    Preconditions.checkArgument(bucketName != null && !bucketName.isEmpty(), "Bucket name must "
        + "not be null or empty.");
    mBucketName = bucketName;
    mKey = key;
    mClient = client;
    mFile = new File(CommonUtils.concatPath("/tmp", UUID.randomUUID()));
    mLocalOutputStream = new BufferedOutputStream(new FileOutputStream(mFile));
  }

  @Override
  public void write(int b) throws IOException {
    mLocalOutputStream.write(b);
  }

  @Override
  public void write(byte[] b) throws IOException {
    mLocalOutputStream.write(b, 0, b.length);
  }

  @Override
  public void write(byte[] b, int off, int len) throws IOException {
    mLocalOutputStream.write(b, off, len);
  }

  @Override
  public void flush() throws IOException {
    mLocalOutputStream.flush();
  }

  @Override
  public void close() throws IOException {
    mLocalOutputStream.close();
    S3Object obj = new S3Object(mKey);
    obj.setDataInputFile(mFile);
    obj.setContentLength(mFile.length());
    obj.setContentEncoding(Mimetypes.MIMETYPE_BINARY_OCTET_STREAM);
    try {
      mClient.putObject(mBucketName, obj);
    } catch (ServiceException se) {
      throw new IOException(se);
    }
  }
}

@@ -955,32 +955,79 @@
 o.OutputStream;%0A
+import java.security.NoSuchAlgorithmException;%0A
 import java.util
@@ -1246,16 +1246,99 @@
 etypes;%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0Aimport tachyon.Constants;
 %0Aimport 
@@ -1630,16 +1630,101 @@
 tream %7B%0A
+  private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);%0A%0A
   privat
@@ -1893,16 +1893,44 @@
 lient;%0A%0A
+  private boolean mClosed;%0A%0A
   public
@@ -2369,16 +2369,37 @@
 File));%0A
+    mClosed = false;%0A
   %7D%0A%0A  @
@@ -2875,32 +2875,91 @@
 s IOException %7B%0A
+    if (mClosed) %7B%0A      return;%0A    %7D%0A    mClosed = true;%0A
     mLocalOutput
@@ -2974,16 +2974,28 @@
 lose();%0A
+    try %7B%0A  
     S3Ob
@@ -3023,14 +3023,17 @@
 ct(m
-Key
+File
 );%0A
+  
     
@@ -3043,30 +3043,35 @@
 .set
-DataInputFile(mFil
+BucketName(mBucketNam
 e);%0A
+  
     
@@ -3081,39 +3081,21 @@
 .set
-ContentLength(mFile.length()
+Key(mKey
 );%0A
+  
     
@@ -3158,26 +3158,16 @@
 TREAM);%0A
-    try %7B%0A
       mC
@@ -3201,16 +3201,38 @@
 , obj);%0A
+      mFile.delete();%0A
     %7D ca
@@ -3269,31 +3269,199 @@
     
-throw new IOException(s
+LOG.error(%22Failed to upload %22 + mKey + %22. Temporary file @ %22 + mFile.getPath());%0A      throw new IOException(se);%0A    %7D catch (NoSuchAlgorithmException nsae) %7B%0A      throw new IOException(nsa
 e);%0A

Delete tmp file after closing.