35f99f516b21df99ba43fd329d3ec65ee53ad155
[pub/Android/ownCloud.git] / oc_framework / src / com / owncloud / android / lib / operations / remote / DownloadRemoteFileOperation.java
1 /* ownCloud Android Library is available under MIT license
2 * Copyright (C) 2014 ownCloud (http://www.owncloud.org/)
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a copy
5 * of this software and associated documentation files (the "Software"), to deal
6 * in the Software without restriction, including without limitation the rights
7 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 * copies of the Software, and to permit persons to whom the Software is
9 * furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
18 * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
19 * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 * THE SOFTWARE.
22 *
23 */
24
25 package com.owncloud.android.lib.operations.remote;
26
27 import java.io.BufferedInputStream;
28 import java.io.File;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.util.HashSet;
32 import java.util.Iterator;
33 import java.util.Set;
34 import java.util.concurrent.atomic.AtomicBoolean;
35
36 import org.apache.commons.httpclient.Header;
37 import org.apache.commons.httpclient.HttpException;
38 import org.apache.commons.httpclient.methods.GetMethod;
39 import org.apache.http.HttpStatus;
40
41 import android.util.Log;
42
43 import com.owncloud.android.lib.network.OnDatatransferProgressListener;
44 import com.owncloud.android.lib.network.OwnCloudClient;
45 import com.owncloud.android.lib.network.webdav.WebdavUtils;
46 import com.owncloud.android.lib.operations.common.OperationCancelledException;
47 import com.owncloud.android.lib.operations.common.RemoteOperation;
48 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
49
50 /**
51 * Remote operation performing the download of a remote file in the ownCloud server.
52 *
53 * @author David A. Velasco
54 * @author masensio
55 */
56
57 public class DownloadRemoteFileOperation extends RemoteOperation {
58
59 private static final String TAG = DownloadRemoteFileOperation.class.getSimpleName();
60
61 private Set<OnDatatransferProgressListener> mDataTransferListeners = new HashSet<OnDatatransferProgressListener>();
62 private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false);
63 //private long mModificationTimestamp = 0;
64 private GetMethod mGet;
65
66 private String mRemotePath;
67 private String mDownloadFolderPath;
68
69 public DownloadRemoteFileOperation(String remotePath, String downloadFolderPath) {
70 mRemotePath = remotePath;
71 mDownloadFolderPath = downloadFolderPath;
72 }
73
74 @Override
75 protected RemoteOperationResult run(OwnCloudClient client) {
76 RemoteOperationResult result = null;
77
78 /// download will be performed to a temporal file, then moved to the final location
79 File tmpFile = new File(getTmpPath());
80
81 /// perform the download
82 try {
83 tmpFile.getParentFile().mkdirs();
84 int status = downloadFile(client, tmpFile);
85 result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null));
86 Log.i(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage());
87
88 } catch (Exception e) {
89 result = new RemoteOperationResult(e);
90 Log.e(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage(), e);
91 }
92
93 return result;
94 }
95
96
97 protected int downloadFile(OwnCloudClient client, File targetFile) throws HttpException, IOException, OperationCancelledException {
98 int status = -1;
99 boolean savedFile = false;
100 mGet = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
101 Iterator<OnDatatransferProgressListener> it = null;
102
103 FileOutputStream fos = null;
104 try {
105 status = client.executeMethod(mGet);
106 if (isSuccess(status)) {
107 targetFile.createNewFile();
108 BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream());
109 fos = new FileOutputStream(targetFile);
110 long transferred = 0;
111
112 Header contentLength = mGet.getResponseHeader("Content-Length");
113 long totalToTransfer = (contentLength != null && contentLength.getValue().length() >0) ? Long.parseLong(contentLength.getValue()) : 0;
114
115 byte[] bytes = new byte[4096];
116 int readResult = 0;
117 while ((readResult = bis.read(bytes)) != -1) {
118 synchronized(mCancellationRequested) {
119 if (mCancellationRequested.get()) {
120 mGet.abort();
121 throw new OperationCancelledException();
122 }
123 }
124 fos.write(bytes, 0, readResult);
125 transferred += readResult;
126 synchronized (mDataTransferListeners) {
127 it = mDataTransferListeners.iterator();
128 while (it.hasNext()) {
129 it.next().onTransferProgress(readResult, transferred, totalToTransfer, targetFile.getName());
130 }
131 }
132 }
133 savedFile = true;
134 /*
135 Header modificationTime = mGet.getResponseHeader("Last-Modified");
136 if (modificationTime != null) {
137 Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue());
138 mModificationTimestamp = (d != null) ? d.getTime() : 0;
139 }
140 */
141
142 } else {
143 client.exhaustResponse(mGet.getResponseBodyAsStream());
144 }
145
146 } finally {
147 if (fos != null) fos.close();
148 if (!savedFile && targetFile.exists()) {
149 targetFile.delete();
150 }
151 mGet.releaseConnection(); // let the connection available for other methods
152 }
153 return status;
154 }
155
156 private boolean isSuccess(int status) {
157 return (status == HttpStatus.SC_OK);
158 }
159
160 private String getTmpPath() {
161 return mDownloadFolderPath + mRemotePath;
162 }
163
164 public void addDatatransferProgressListener (OnDatatransferProgressListener listener) {
165 synchronized (mDataTransferListeners) {
166 mDataTransferListeners.add(listener);
167 }
168 }
169
170 public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) {
171 synchronized (mDataTransferListeners) {
172 mDataTransferListeners.remove(listener);
173 }
174 }
175
176 public void cancel() {
177 mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it
178 }
179 }