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