Added notification for failures in manual synchronizations; some improvements in...
[pub/Android/ownCloud.git] / src / eu / alefzero / webdav / WebdavClient.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18 package eu.alefzero.webdav;
19
20 import java.io.BufferedInputStream;
21 import java.io.File;
22 import java.io.FileOutputStream;
23 import java.io.IOException;
24 import java.io.InputStream;
25
26 import org.apache.commons.httpclient.Credentials;
27 import org.apache.commons.httpclient.HttpClient;
28 import org.apache.commons.httpclient.HttpConnectionManager;
29 import org.apache.commons.httpclient.HttpException;
30 import org.apache.commons.httpclient.HttpMethodBase;
31 import org.apache.commons.httpclient.HttpVersion;
32 import org.apache.commons.httpclient.UsernamePasswordCredentials;
33 import org.apache.commons.httpclient.auth.AuthScope;
34 import org.apache.commons.httpclient.methods.GetMethod;
35 import org.apache.commons.httpclient.methods.HeadMethod;
36 import org.apache.commons.httpclient.methods.PutMethod;
37 import org.apache.commons.httpclient.params.HttpMethodParams;
38 import org.apache.http.HttpStatus;
39 import org.apache.http.params.CoreProtocolPNames;
40 import org.apache.jackrabbit.webdav.client.methods.DavMethod;
41 import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
42 import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
43
44 import android.net.Uri;
45 import android.util.Log;
46
47 public class WebdavClient extends HttpClient {
48 private Uri mUri;
49 private Credentials mCredentials;
50 final private static String TAG = "WebdavClient";
51 private static final String USER_AGENT = "Android-ownCloud";
52
53 private OnDatatransferProgressListener mDataTransferListener;
54 static private byte[] sExhaustBuffer = new byte[1024];
55
56 /**
57 * Constructor
58 */
59 public WebdavClient(HttpConnectionManager connectionMgr) {
60 super(connectionMgr);
61 Log.d(TAG, "Creating WebdavClient");
62 getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
63 getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
64 }
65
66 public void setCredentials(String username, String password) {
67 getParams().setAuthenticationPreemptive(true);
68 getState().setCredentials(AuthScope.ANY,
69 getCredentials(username, password));
70 }
71
72 private Credentials getCredentials(String username, String password) {
73 if (mCredentials == null)
74 mCredentials = new UsernamePasswordCredentials(username, password);
75 return mCredentials;
76 }
77
78 /**
79 * Downloads a file in remoteFilepath to the local targetPath.
80 *
81 * @param remoteFilepath Path to the file in the remote server, URL DECODED.
82 * @param targetFile Local path to save the downloaded file.
83 * @return 'True' when the file is successfully downloaded.
84 */
85 public boolean downloadFile(String remoteFilePath, File targetFile) {
86 boolean ret = false;
87 GetMethod get = new GetMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilePath));
88
89 try {
90 int status = executeMethod(get);
91 if (status == HttpStatus.SC_OK) {
92 targetFile.createNewFile();
93 BufferedInputStream bis = new BufferedInputStream(
94 get.getResponseBodyAsStream());
95 FileOutputStream fos = new FileOutputStream(targetFile);
96
97 byte[] bytes = new byte[4096];
98 int readResult;
99 while ((readResult = bis.read(bytes)) != -1) {
100 if (mDataTransferListener != null)
101 mDataTransferListener.transferProgress(readResult);
102 fos.write(bytes, 0, readResult);
103 }
104 ret = true;
105 } else {
106 exhaustResponse(get.getResponseBodyAsStream());
107 }
108 Log.e(TAG, "Download of " + remoteFilePath + " to " + targetFile + " finished with HTTP status " + status + (!ret?"(FAIL)":""));
109
110 } catch (Exception e) {
111 logException(e, "dowloading " + remoteFilePath);
112
113 } finally {
114 if (!ret && targetFile.exists()) {
115 targetFile.delete();
116 }
117 get.releaseConnection(); // let the connection available for other methods
118 }
119 return ret;
120 }
121
122 /**
123 * Deletes a remote file via webdav
124 * @param remoteFilePath Remote file path of the file to delete, in URL DECODED format.
125 * @return
126 */
127 public boolean deleteFile(String remoteFilePath) {
128 boolean ret = false;
129 DavMethod delete = new DeleteMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilePath));
130 try {
131 int status = executeMethod(delete);
132 ret = (status == HttpStatus.SC_OK || status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_NO_CONTENT);
133 exhaustResponse(delete.getResponseBodyAsStream());
134
135 Log.e(TAG, "DELETE of " + remoteFilePath + " finished with HTTP status " + status + (!ret?"(FAIL)":""));
136
137 } catch (Exception e) {
138 logException(e, "deleting " + remoteFilePath);
139
140 } finally {
141 delete.releaseConnection(); // let the connection available for other methods
142 }
143 return ret;
144 }
145
146
147 public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
148 mDataTransferListener = listener;
149 }
150
151 /**
152 * Creates or update a file in the remote server with the contents of a local file.
153 *
154 *
155 * @param localFile Path to the local file to upload.
156 * @param remoteTarget Remote path to the file to create or update, URL DECODED
157 * @param contentType MIME type of the file.
158 * @return 'True' then the upload was successfully completed
159 */
160 public boolean putFile(String localFile, String remoteTarget, String contentType) {
161 boolean result = false;
162 int status = -1;
163 PutMethod put = new PutMethod(mUri.toString() + WebdavUtils.encodePath(remoteTarget));
164
165 try {
166 File f = new File(localFile);
167 FileRequestEntity entity = new FileRequestEntity(f, contentType);
168 entity.setOnDatatransferProgressListener(mDataTransferListener);
169 put.setRequestEntity(entity);
170 status = executeMethod(put);
171
172 result = (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT);
173
174 Log.d(TAG, "PUT to " + remoteTarget + " finished with HTTP status " + status + (!result?"(FAIL)":""));
175
176 exhaustResponse(put.getResponseBodyAsStream());
177
178 } catch (Exception e) {
179 logException(e, "uploading " + localFile + " to " + remoteTarget);
180
181 } finally {
182 put.releaseConnection(); // let the connection available for other methods
183 }
184 return result;
185 }
186
187 /**
188 * Tries to log in to the current URI, with the current credentials
189 *
190 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
191 */
192 public int tryToLogin() {
193 int status = 0;
194 HeadMethod head = new HeadMethod(mUri.toString());
195 try {
196 status = executeMethod(head);
197 boolean result = status == HttpStatus.SC_OK;
198 Log.d(TAG, "HEAD for " + mUri + " finished with HTTP status " + status + (!result?"(FAIL)":""));
199 exhaustResponse(head.getResponseBodyAsStream());
200
201 } catch (Exception e) {
202 logException(e, "trying to login at " + mUri.toString());
203
204 } finally {
205 head.releaseConnection();
206 }
207 return status;
208 }
209
210 /**
211 * Creates a remote directory with the received path.
212 *
213 * @param path Path of the directory to create, URL DECODED
214 * @return 'True' when the directory is successfully created
215 */
216 public boolean createDirectory(String path) {
217 boolean result = false;
218 int status = -1;
219 MkColMethod mkcol = new MkColMethod(mUri.toString() + WebdavUtils.encodePath(path));
220 try {
221 Log.d(TAG, "Creating directory " + path);
222 status = executeMethod(mkcol);
223 Log.d(TAG, "Status returned: " + status);
224 result = mkcol.succeeded();
225
226 Log.d(TAG, "MKCOL to " + path + " finished with HTTP status " + status + (!result?"(FAIL)":""));
227 exhaustResponse(mkcol.getResponseBodyAsStream());
228
229 } catch (Exception e) {
230 logException(e, "creating directory " + path);
231
232 } finally {
233 mkcol.releaseConnection(); // let the connection available for other methods
234 }
235 return result;
236 }
237
238
239 /**
240 * Check if a file exists in the OC server
241 *
242 * @return 'Boolean.TRUE' if the file exists; 'Boolean.FALSE' it doesn't exist; NULL if couldn't be checked
243 */
244 public Boolean existsFile(String path) {
245 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
246 try {
247 int status = executeMethod(head);
248 Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
249 exhaustResponse(head.getResponseBodyAsStream());
250 return (status == HttpStatus.SC_OK);
251
252 } catch (Exception e) {
253 logException(e, "checking existence of " + path);
254 return null;
255
256 } finally {
257 head.releaseConnection(); // let the connection available for other methods
258 }
259 }
260
261
262 /**
263 * Requests the received method with the received timeout (milliseconds).
264 *
265 * Executes the method through the inherited HttpClient.executedMethod(method).
266 *
267 * Sets the socket and connection timeouts only for the method received.
268 *
269 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
270 *
271 * @param method HTTP method request.
272 * @param readTimeout Timeout to set for data reception
273 * @param conntionTimout Timeout to set for connection establishment
274 */
275 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
276 int oldSoTimeout = getParams().getSoTimeout();
277 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
278 try {
279 if (readTimeout >= 0) {
280 method.getParams().setSoTimeout(readTimeout); // this should be enough...
281 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
282 }
283 if (connectionTimeout >= 0) {
284 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
285 }
286 return executeMethod(method);
287 } finally {
288 getParams().setSoTimeout(oldSoTimeout);
289 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
290 }
291 }
292
293 /**
294 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
295 *
296 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
297 */
298 private static void exhaustResponse(InputStream responseBodyAsStream) {
299 if (responseBodyAsStream != null) {
300 try {
301 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
302 responseBodyAsStream.close();
303
304 } catch (IOException io) {
305 Log.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
306 }
307 }
308 }
309
310
311 /**
312 * Logs an exception triggered in a HTTP request.
313 *
314 * @param e Caught exception.
315 * @param doing Suffix to add at the end of the logged message.
316 */
317 private void logException(Exception e, String doing) {
318 if (e instanceof HttpException) {
319 Log.e(TAG, "HTTP violation while " + doing, e);
320
321 } else if (e instanceof IOException) {
322 Log.e(TAG, "Unrecovered transport exception while " + doing, e);
323
324 } else {
325 Log.e(TAG, "Unexpected exception while " + doing, e);
326 }
327 }
328
329
330 /**
331 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
332 */
333 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
334 getParams().setSoTimeout(defaultDataTimeout);
335 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
336 }
337
338 /**
339 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
340 * @param uri
341 */
342 public void setBaseUri(Uri uri) {
343 mUri = uri;
344 }
345
346 }