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