Adding cancellation to uploads (WIP)
[pub/Android/ownCloud.git] / src / com / owncloud / android / operations / DownloadFileOperation.java
index fbeedd8..a35a016 100644 (file)
@@ -25,11 +25,13 @@ import java.io.IOException;
 import java.util.HashSet;
 import java.util.Iterator;
 import java.util.Set;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.http.HttpStatus;
 
+import com.owncloud.android.datamodel.OCFile;
 import com.owncloud.android.files.services.FileDownloader;
 import com.owncloud.android.operations.RemoteOperation;
 import com.owncloud.android.operations.RemoteOperationResult;
@@ -51,74 +53,67 @@ public class DownloadFileOperation extends RemoteOperation {
     private static final String TAG = DownloadFileOperation.class.getCanonicalName();
 
     private Account mAccount = null;
-    private String mLocalPath = null;
-    private String mRemotePath = null;
-    private String mMimeType = null;
-    private long mSize = -1;
-    private Boolean mCancellationRequested = false;
-    
+    private OCFile mFile;
     private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
+    private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
 
     
-    public Account getAccount() {
-        return mAccount;
+    public DownloadFileOperation(Account account, OCFile file) {
+        if (account == null)
+            throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
+        if (file == null)
+            throw new IllegalArgumentException("Illegal null file in DownloadFileOperation creation");
+        
+        mAccount = account;
+        mFile = file;
     }
 
-    public String getLocalPath() {
-        return mLocalPath;
+
+    public Account getAccount() {
+        return mAccount;
     }
     
-    public String getRemotePath() {
-        return mRemotePath;
+    public OCFile getFile() {
+        return mFile;
     }
 
-    public String getMimeType() {
-        return mMimeType;
+    public String getSavePath() {
+        return FileDownloader.getSavePath(mAccount.name) + mFile.getRemotePath();
     }
     
-    public long getSize() {
-        return mSize;
+    public String getTmpPath() {
+        return FileDownloader.getTemporalPath(mAccount.name) + mFile.getRemotePath();
     }
     
-    
-    public DownloadFileOperation( Account account, 
-                                String localPath, 
-                                String remotePath, 
-                                String mimeType, 
-                                long size,
-                                boolean forceOverwrite) {
-        
-        if (account == null)
-            throw new IllegalArgumentException("Illegal null account in DownloadFileOperation creation");
-        if (localPath == null)
-            throw new IllegalArgumentException("Illegal null local path in DownloadFileOperation creation");
-        if (remotePath == null)
-            throw new IllegalArgumentException("Illegal null remote path in DownloadFileOperation creation");
-        
-        mAccount = account;
-        mLocalPath = localPath;
-        mRemotePath = remotePath;
-        mMimeType = mimeType;
-        if (mMimeType == null) {
+    public String getRemotePath() {
+        return mFile.getRemotePath();
+    }
+
+    public String getMimeType() {
+        String mimeType = mFile.getMimetype();
+        if (mimeType == null || mimeType.length() <= 0) {
             try {
-                mMimeType = MimeTypeMap.getSingleton()
+                mimeType = MimeTypeMap.getSingleton()
                     .getMimeTypeFromExtension(
-                            localPath.substring(localPath.lastIndexOf('.') + 1));
+                            mFile.getRemotePath().substring(mFile.getRemotePath().lastIndexOf('.') + 1));
             } catch (IndexOutOfBoundsException e) {
-                Log.e(TAG, "Trying to find out MIME type of a file without extension: " + localPath);
+                Log.e(TAG, "Trying to find out MIME type of a file without extension: " + mFile.getRemotePath());
             }
         }
-        if (mMimeType == null) {
-            mMimeType = "application/octet-stream";
+        if (mimeType == null) {
+            mimeType = "application/octet-stream";
         }
-        mSize = size;
+        return mimeType;
     }
     
-    public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
-        mDataTransferListeners.add(listener);
+    public long getSize() {
+        return mFile.getFileLength();
     }
     
     
+    public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
+        mDataTransferListeners.add(listener);
+    }
     
     @Override
     protected RemoteOperationResult run(WebdavClient client) {
@@ -126,15 +121,15 @@ public class DownloadFileOperation extends RemoteOperation {
         File newFile = null;
         boolean moved = false;
         
-        /// download will be in a temporal file
-        File tmpFile = new File(FileDownloader.getTemporalPath(mAccount.name) + mLocalPath);
+        /// download will be performed to a temporal file, then moved to the final location
+        File tmpFile = new File(getTmpPath());
         
         /// perform the download
         try {
             tmpFile.getParentFile().mkdirs();
             int status = downloadFile(client, tmpFile);
             if (isSuccess(status)) {
-                newFile = new File(FileDownloader.getSavePath(mAccount.name) + mLocalPath);
+                newFile = new File(getSavePath());
                 newFile.getParentFile().mkdirs();
                 moved = tmpFile.renameTo(newFile);
             }
@@ -142,11 +137,11 @@ public class DownloadFileOperation extends RemoteOperation {
                 result = new RemoteOperationResult(RemoteOperationResult.ResultCode.STORAGE_ERROR_MOVING_FROM_TMP);
             else
                 result = new RemoteOperationResult(isSuccess(status), status);
-            Log.i(TAG, "Download of " + mLocalPath + " to " + mRemotePath + ": " + result.getLogMessage());
+            Log.i(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage());
             
         } catch (Exception e) {
             result = new RemoteOperationResult(e);
-            Log.e(TAG, "Download of " + mRemotePath + " to " + mLocalPath + ": " + result.getLogMessage(), e);
+            Log.e(TAG, "Download of " + mFile.getRemotePath() + " to " + getSavePath() + ": " + result.getLogMessage(), e);
         }
         
         return result;
@@ -161,22 +156,24 @@ public class DownloadFileOperation extends RemoteOperation {
     protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
         int status = -1;
         boolean savedFile = false;
-        GetMethod get = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
+        GetMethod get = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mFile.getRemotePath()));
         Iterator<OnDatatransferProgressListener> it = null;
         
+        FileOutputStream fos = null;
         try {
             status = client.executeMethod(get);
             if (isSuccess(status)) {
                 targetFile.createNewFile();
                 BufferedInputStream bis = new BufferedInputStream(get.getResponseBodyAsStream());
-                FileOutputStream fos = new FileOutputStream(targetFile);
+                fos = new FileOutputStream(targetFile);
                 long transferred = 0;
 
                 byte[] bytes = new byte[4096];
                 int readResult = 0;
                 while ((readResult = bis.read(bytes)) != -1) {
                     synchronized(mCancellationRequested) {
-                        if (mCancellationRequested) {
+                        if (mCancellationRequested.get()) {
+                            get.abort();
                             throw new OperationCancelledException();
                         }
                     }
@@ -184,10 +181,9 @@ public class DownloadFileOperation extends RemoteOperation {
                     transferred += readResult;
                     it = mDataTransferListeners.iterator();
                     while (it.hasNext()) {
-                        it.next().onTransferProgress(readResult, transferred, mSize, targetFile.getName());
+                        it.next().onTransferProgress(readResult, transferred, mFile.getFileLength(), targetFile.getName());
                     }
                 }
-                fos.close();
                 savedFile = true;
                 
             } else {
@@ -195,6 +191,7 @@ public class DownloadFileOperation extends RemoteOperation {
             }
                 
         } finally {
+            if (fos != null) fos.close();
             if (!savedFile && targetFile.exists()) {
                 targetFile.delete();
             }
@@ -205,9 +202,7 @@ public class DownloadFileOperation extends RemoteOperation {
 
     
     public void cancel() {
-        synchronized(mCancellationRequested) {
-            mCancellationRequested = true;
-        }
+        mCancellationRequested.set(true);   // atomic set; there is no need of synchronizing it
     }
-    
+
 }