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
.onTransferProgress(readResult
);
102 fos
.write(bytes
, 0, readResult
);
107 exhaustResponse(get
.getResponseBodyAsStream());
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
);
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.
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.
161 public int putFile(String localFile
, String remoteTarget
, String contentType
) throws HttpException
, IOException
{
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
.addOnDatatransferProgressListener(mDataTransferListener
);
169 put
.setRequestEntity(entity
);
170 status
= executeMethod(put
);
172 exhaustResponse(put
.getResponseBodyAsStream());
175 put
.releaseConnection(); // let the connection available for other methods
181 * Tries to log in to the current URI, with the current credentials
183 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
185 public int tryToLogin() {
187 HeadMethod head
= new HeadMethod(mUri
.toString());
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());
194 } catch (Exception e
) {
195 logException(e
, "trying to login at " + mUri
.toString());
198 head
.releaseConnection();
204 * Creates a remote directory with the received path.
206 * @param path Path of the directory to create, URL DECODED
207 * @return 'True' when the directory is successfully created
209 public boolean createDirectory(String path
) {
210 boolean result
= false
;
212 MkColMethod mkcol
= new MkColMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
214 Log
.d(TAG
, "Creating directory " + path
);
215 status
= executeMethod(mkcol
);
216 Log
.d(TAG
, "Status returned: " + status
);
217 result
= mkcol
.succeeded();
219 Log
.d(TAG
, "MKCOL to " + path
+ " finished with HTTP status " + status
+ (!result?
"(FAIL)":""));
220 exhaustResponse(mkcol
.getResponseBodyAsStream());
222 } catch (Exception e
) {
223 logException(e
, "creating directory " + path
);
226 mkcol
.releaseConnection(); // let the connection available for other methods
233 * Check if a file exists in the OC server
235 * @return 'true' if the file exists; 'false' it doesn't exist
236 * @throws Exception When the existence could not be determined
238 public boolean existsFile(String path
) throws IOException
, HttpException
{
239 HeadMethod head
= new HeadMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
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
);
247 head
.releaseConnection(); // let the connection available for other methods
253 * Requests the received method with the received timeout (milliseconds).
255 * Executes the method through the inherited HttpClient.executedMethod(method).
257 * Sets the socket and connection timeouts only for the method received.
259 * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default'
261 * @param method HTTP method request.
262 * @param readTimeout Timeout to set for data reception
263 * @param conntionTimout Timeout to set for connection establishment
265 public int executeMethod(HttpMethodBase method
, int readTimeout
, int connectionTimeout
) throws HttpException
, IOException
{
266 int oldSoTimeout
= getParams().getSoTimeout();
267 int oldConnectionTimeout
= getHttpConnectionManager().getParams().getConnectionTimeout();
269 if (readTimeout
>= 0) {
270 method
.getParams().setSoTimeout(readTimeout
); // this should be enough...
271 getParams().setSoTimeout(readTimeout
); // ... but this looks like necessary for HTTPS
273 if (connectionTimeout
>= 0) {
274 getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout
);
276 return executeMethod(method
);
278 getParams().setSoTimeout(oldSoTimeout
);
279 getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout
);
284 * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation.
286 * @param responseBodyAsStream InputStream with the HTTP response to exhaust.
288 public void exhaustResponse(InputStream responseBodyAsStream
) {
289 if (responseBodyAsStream
!= null
) {
291 while (responseBodyAsStream
.read(sExhaustBuffer
) >= 0);
292 responseBodyAsStream
.close();
294 } catch (IOException io
) {
295 Log
.e(TAG
, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io
);
302 * Logs an exception triggered in a HTTP request.
304 * @param e Caught exception.
305 * @param doing Suffix to add at the end of the logged message.
307 private void logException(Exception e
, String doing
) {
308 if (e
instanceof HttpException
) {
309 Log
.e(TAG
, "HTTP violation while " + doing
, e
);
311 } else if (e
instanceof IOException
) {
312 Log
.e(TAG
, "Unrecovered transport exception while " + doing
, e
);
315 Log
.e(TAG
, "Unexpected exception while " + doing
, e
);
321 * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client.
323 public void setDefaultTimeouts(int defaultDataTimeout
, int defaultConnectionTimeout
) {
324 getParams().setSoTimeout(defaultDataTimeout
);
325 getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout
);
329 * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs
332 public void setBaseUri(Uri uri
) {
336 public Uri
getBaseUri() {