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