1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
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.
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.
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/>.
18 package eu
.alefzero
.webdav
;
20 import java
.io
.BufferedInputStream
;
22 import java
.io
.FileOutputStream
;
23 import java
.io
.IOException
;
24 import java
.io
.InputStream
;
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
;
44 import android
.net
.Uri
;
45 import android
.util
.Log
;
47 public class WebdavClient
extends HttpClient
{
49 private Credentials mCredentials
;
50 final private static String TAG
= "WebdavClient";
51 private static final String USER_AGENT
= "Android-ownCloud";
53 private OnDatatransferProgressListener mDataTransferListener
;
54 static private byte[] sExhaustBuffer
= new byte[1024];
59 public WebdavClient(HttpConnectionManager 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
);
66 public void setCredentials(String username
, String password
) {
67 getParams().setAuthenticationPreemptive(true
);
68 getState().setCredentials(AuthScope
.ANY
,
69 getCredentials(username
, password
));
72 private Credentials
getCredentials(String username
, String password
) {
73 if (mCredentials
== null
)
74 mCredentials
= new UsernamePasswordCredentials(username
, password
);
79 * Downloads a file in remoteFilepath to the local targetPath.
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.
85 public boolean downloadFile(String remoteFilePath
, File targetFile
) {
87 GetMethod get
= new GetMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteFilePath
));
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
);
97 byte[] bytes
= new byte[4096];
99 while ((readResult
= bis
.read(bytes
)) != -1) {
100 if (mDataTransferListener
!= null
)
101 mDataTransferListener
.transferProgress(readResult
);
102 fos
.write(bytes
, 0, readResult
);
106 exhaustResponse(get
.getResponseBodyAsStream());
108 Log
.e(TAG
, "Download of " + remoteFilePath
+ " to " + targetFile
+ " finished with HTTP status " + status
+ (!ret?
"(FAIL)":""));
110 } catch (Exception e
) {
111 logException(e
, "dowloading " + remoteFilePath
);
114 if (!ret
&& targetFile
.exists()) {
117 get
.releaseConnection(); // let the connection available for other methods
123 * Deletes a remote file via webdav
124 * @param remoteFilePath Remote file path of the file to delete, in URL DECODED format.
127 public boolean deleteFile(String remoteFilePath
) {
129 DavMethod delete
= new DeleteMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteFilePath
));
131 int status
= executeMethod(delete
);
132 ret
= (status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_ACCEPTED
|| status
== HttpStatus
.SC_NO_CONTENT
);
133 exhaustResponse(delete
.getResponseBodyAsStream());
135 Log
.e(TAG
, "DELETE of " + remoteFilePath
+ " finished with HTTP status " + status
+ (!ret?
"(FAIL)":""));
137 } catch (Exception e
) {
138 logException(e
, "deleting " + remoteFilePath
);
141 delete
.releaseConnection(); // let the connection available for other methods
147 public void setDataTransferProgressListener(OnDatatransferProgressListener listener
) {
148 mDataTransferListener
= listener
;
152 * Creates or update a file in the remote server with the contents of a local file.
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 'True' then the upload was successfully completed
160 public boolean putFile(String localFile
, String remoteTarget
, String contentType
) {
161 boolean result
= false
;
163 PutMethod put
= new PutMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteTarget
));
166 File f
= new File(localFile
);
167 FileRequestEntity entity
= new FileRequestEntity(f
, contentType
);
168 entity
.setOnDatatransferProgressListener(mDataTransferListener
);
169 put
.setRequestEntity(entity
);
170 status
= executeMethod(put
);
172 result
= (status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
);
174 Log
.d(TAG
, "PUT to " + remoteTarget
+ " finished with HTTP status " + status
+ (!result?
"(FAIL)":""));
176 exhaustResponse(put
.getResponseBodyAsStream());
178 } catch (Exception e
) {
179 logException(e
, "uploading " + localFile
+ " to " + remoteTarget
);
182 put
.releaseConnection(); // let the connection available for other methods
188 * Tries to log in to the current URI, with the current credentials
190 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
192 public int tryToLogin() {
194 HeadMethod head
= new HeadMethod(mUri
.toString());
196 status
= executeMethod(head
);
197 boolean result
= status
== HttpStatus
.SC_OK
;
198 Log
.d(TAG
, "HEAD for " + mUri
+ " finished with HTTP status " + status
+ (!result?
"(FAIL)":""));
199 exhaustResponse(head
.getResponseBodyAsStream());
201 } catch (Exception e
) {
202 logException(e
, "trying to login at " + mUri
.toString());
205 head
.releaseConnection();
211 * Creates a remote directory with the received path.
213 * @param path Path of the directory to create, URL DECODED
214 * @return 'True' when the directory is successfully created
216 public boolean createDirectory(String path
) {
217 boolean result
= false
;
219 MkColMethod mkcol
= new MkColMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
221 Log
.d(TAG
, "Creating directory " + path
);
222 status
= executeMethod(mkcol
);
223 Log
.d(TAG
, "Status returned: " + status
);
224 result
= mkcol
.succeeded();
226 Log
.d(TAG
, "MKCOL to " + path
+ " finished with HTTP status " + status
+ (!result?
"(FAIL)":""));
227 exhaustResponse(mkcol
.getResponseBodyAsStream());
229 } catch (Exception e
) {
230 logException(e
, "creating directory " + path
);
233 mkcol
.releaseConnection(); // let the connection available for other methods
240 * Check if a file exists in the OC server
242 * @return 'Boolean.TRUE' if the file exists; 'Boolean.FALSE' it doesn't exist; NULL if couldn't be checked
244 public Boolean
existsFile(String path
) {
245 HeadMethod head
= new HeadMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
247 int status
= executeMethod(head
);
248 Log
.d(TAG
, "HEAD to " + path
+ " finished with HTTP status " + status
+ ((status
!= HttpStatus
.SC_OK
)?
"(FAIL)":""));
249 exhaustResponse(head
.getResponseBodyAsStream());
250 return (status
== HttpStatus
.SC_OK
);
252 } catch (Exception e
) {
253 logException(e
, "checking existence of " + path
);
257 head
.releaseConnection(); // let the connection available for other methods
263 * Requests the received method with the received timeout (milliseconds).
265 * Executes the method through the inherited HttpClient.executedMethod(method).
267 * Sets the socket and connection timeouts only for the method received.
269 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
271 * @param method HTTP method request.
272 * @param readTimeout Timeout to set for data reception
273 * @param conntionTimout Timeout to set for connection establishment
275 public int executeMethod(HttpMethodBase method
, int readTimeout
, int connectionTimeout
) throws HttpException
, IOException
{
276 int oldSoTimeout
= getParams().getSoTimeout();
277 int oldConnectionTimeout
= getHttpConnectionManager().getParams().getConnectionTimeout();
279 if (readTimeout
>= 0) {
280 method
.getParams().setSoTimeout(readTimeout
); // this should be enough...
281 getParams().setSoTimeout(readTimeout
); // ... but this looks like necessary for HTTPS
283 if (connectionTimeout
>= 0) {
284 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout
);
286 return executeMethod(method
);
288 getParams().setSoTimeout(oldSoTimeout
);
289 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout
);
294 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
296 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
298 private static void exhaustResponse(InputStream responseBodyAsStream
) {
299 if (responseBodyAsStream
!= null
) {
301 while (responseBodyAsStream
.read(sExhaustBuffer
) >= 0);
302 responseBodyAsStream
.close();
304 } catch (IOException io
) {
305 Log
.e(TAG
, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io
);
312 * Logs an exception triggered in a HTTP request.
314 * @param e Caught exception.
315 * @param doing Suffix to add at the end of the logged message.
317 private void logException(Exception e
, String doing
) {
318 if (e
instanceof HttpException
) {
319 Log
.e(TAG
, "HTTP violation while " + doing
, e
);
321 } else if (e
instanceof IOException
) {
322 Log
.e(TAG
, "Unrecovered transport exception while " + doing
, e
);
325 Log
.e(TAG
, "Unexpected exception while " + doing
, e
);
331 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
333 public void setDefaultTimeouts(int defaultDataTimeout
, int defaultConnectionTimeout
) {
334 getParams().setSoTimeout(defaultDataTimeout
);
335 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout
);
339 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
342 public void setBaseUri(Uri uri
) {