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