a451b3eeb1da654492667ee22c4569eff9387760
[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.onTransferProgress(readResult);
102 fos.write(bytes, 0, readResult);
103 }
104 fos.close();
105 ret = true;
106 } else {
107 exhaustResponse(get.getResponseBodyAsStream());
108 }
109 Log.e(TAG, "Download of " + remoteFilePath + " to " + targetFile + " finished with HTTP status " + status + (!ret?"(FAIL)":""));
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 * @param localFile Path to the local file to upload.
155 * @param remoteTarget Remote path to the file to create or update, URL DECODED
156 * @param contentType MIME type of the file.
157 * @return Status HTTP code returned by the server.
158 * @throws IOException When a transport error that could not be recovered occurred while uploading the file to the server.
159 * @throws HttpException When a violation of the HTTP protocol occurred.
160 */
161 public int putFile(String localFile, String remoteTarget, String contentType) throws HttpException, IOException {
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.addOnDatatransferProgressListener(mDataTransferListener);
169 put.setRequestEntity(entity);
170 status = executeMethod(put);
171
172 exhaustResponse(put.getResponseBodyAsStream());
173
174 } finally {
175 put.releaseConnection(); // let the connection available for other methods
176 }
177 return status;
178 }
179
180 /**
181 * Tries to log in to the current URI, with the current credentials
182 *
183 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
184 */
185 public int tryToLogin() {
186 int status = 0;
187 HeadMethod head = new HeadMethod(mUri.toString());
188 try {
189 status = executeMethod(head);
190 boolean result = status == HttpStatus.SC_OK;
191 Log.d(TAG, "HEAD for " + mUri + " finished with HTTP status " + status + (!result?"(FAIL)":""));
192 exhaustResponse(head.getResponseBodyAsStream());
193
194 } catch (Exception e) {
195 logException(e, "trying to login at " + mUri.toString());
196
197 } finally {
198 head.releaseConnection();
199 }
200 return status;
201 }
202
203 /**
204 * Creates a remote directory with the received path.
205 *
206 * @param path Path of the directory to create, URL DECODED
207 * @return 'True' when the directory is successfully created
208 */
209 public boolean createDirectory(String path) {
210 boolean result = false;
211 int status = -1;
212 MkColMethod mkcol = new MkColMethod(mUri.toString() + WebdavUtils.encodePath(path));
213 try {
214 Log.d(TAG, "Creating directory " + path);
215 status = executeMethod(mkcol);
216 Log.d(TAG, "Status returned: " + status);
217 result = mkcol.succeeded();
218
219 Log.d(TAG, "MKCOL to " + path + " finished with HTTP status " + status + (!result?"(FAIL)":""));
220 exhaustResponse(mkcol.getResponseBodyAsStream());
221
222 } catch (Exception e) {
223 logException(e, "creating directory " + path);
224
225 } finally {
226 mkcol.releaseConnection(); // let the connection available for other methods
227 }
228 return result;
229 }
230
231
232 /**
233 * Check if a file exists in the OC server
234 *
235 * @return 'true' if the file exists; 'false' it doesn't exist
236 * @throws Exception When the existence could not be determined
237 */
238 public boolean existsFile(String path) throws IOException, HttpException {
239 HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
240 try {
241 int status = executeMethod(head);
242 Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":""));
243 exhaustResponse(head.getResponseBodyAsStream());
244 return (status == HttpStatus.SC_OK);
245
246 } finally {
247 head.releaseConnection(); // let the connection available for other methods
248 }
249 }
250
251
252 /**
253 * Requests the received method with the received timeout (milliseconds).
254 *
255 * Executes the method through the inherited HttpClient.executedMethod(method).
256 *
257 * Sets the socket and connection timeouts only for the method received.
258 *
259 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
260 *
261 * @param method HTTP method request.
262 * @param readTimeout Timeout to set for data reception
263 * @param conntionTimout Timeout to set for connection establishment
264 */
265 public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException {
266 int oldSoTimeout = getParams().getSoTimeout();
267 int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout();
268 try {
269 if (readTimeout >= 0) {
270 method.getParams().setSoTimeout(readTimeout); // this should be enough...
271 getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS
272 }
273 if (connectionTimeout >= 0) {
274 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
275 }
276 return executeMethod(method);
277 } finally {
278 getParams().setSoTimeout(oldSoTimeout);
279 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout);
280 }
281 }
282
283 /**
284 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
285 *
286 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
287 */
288 public void exhaustResponse(InputStream responseBodyAsStream) {
289 if (responseBodyAsStream != null) {
290 try {
291 while (responseBodyAsStream.read(sExhaustBuffer) >= 0);
292 responseBodyAsStream.close();
293
294 } catch (IOException io) {
295 Log.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io);
296 }
297 }
298 }
299
300
301 /**
302 * Logs an exception triggered in a HTTP request.
303 *
304 * @param e Caught exception.
305 * @param doing Suffix to add at the end of the logged message.
306 */
307 private void logException(Exception e, String doing) {
308 if (e instanceof HttpException) {
309 Log.e(TAG, "HTTP violation while " + doing, e);
310
311 } else if (e instanceof IOException) {
312 Log.e(TAG, "Unrecovered transport exception while " + doing, e);
313
314 } else {
315 Log.e(TAG, "Unexpected exception while " + doing, e);
316 }
317 }
318
319
320 /**
321 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
322 */
323 public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) {
324 getParams().setSoTimeout(defaultDataTimeout);
325 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout);
326 }
327
328 /**
329 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
330 * @param uri
331 */
332 public void setBaseUri(Uri uri) {
333 mUri = uri;
334 }
335
336 public Uri getBaseUri() {
337 return mUri;
338 }
339
340 }