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
;
25 import org
.apache
.commons
.httpclient
.Credentials
;
26 import org
.apache
.commons
.httpclient
.HttpClient
;
27 import org
.apache
.commons
.httpclient
.HttpException
;
28 import org
.apache
.commons
.httpclient
.HttpMethodBase
;
29 import org
.apache
.commons
.httpclient
.HttpVersion
;
30 import org
.apache
.commons
.httpclient
.MultiThreadedHttpConnectionManager
;
31 import org
.apache
.commons
.httpclient
.UsernamePasswordCredentials
;
32 import org
.apache
.commons
.httpclient
.auth
.AuthScope
;
33 import org
.apache
.commons
.httpclient
.methods
.GetMethod
;
34 import org
.apache
.commons
.httpclient
.methods
.HeadMethod
;
35 import org
.apache
.commons
.httpclient
.methods
.PutMethod
;
36 import org
.apache
.commons
.httpclient
.params
.HttpMethodParams
;
37 import org
.apache
.commons
.httpclient
.protocol
.Protocol
;
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 com
.owncloud
.android
.AccountUtils
;
45 import com
.owncloud
.android
.authenticator
.AccountAuthenticator
;
46 import com
.owncloud
.android
.authenticator
.EasySSLSocketFactory
;
47 import com
.owncloud
.android
.files
.interfaces
.OnDatatransferProgressListener
;
48 import com
.owncloud
.android
.utils
.OwnCloudVersion
;
50 import android
.accounts
.Account
;
51 import android
.accounts
.AccountManager
;
52 import android
.content
.Context
;
53 import android
.net
.Uri
;
54 import android
.util
.Log
;
56 public class WebdavClient
extends HttpClient
{
58 private Credentials mCredentials
;
59 final private static String TAG
= "WebdavClient";
60 private static final String USER_AGENT
= "Android-ownCloud";
62 /** Default timeout for waiting data from the server: 10 seconds */
63 public static final int DEFAULT_DATA_TIMEOUT
= 10000;
65 /** Default timeout for establishing a connection: infinite */
66 public static final int DEFAULT_CONNECTION_TIMEOUT
= 0;
68 private OnDatatransferProgressListener mDataTransferListener
;
69 static private MultiThreadedHttpConnectionManager mConnManager
= null
;
71 static public MultiThreadedHttpConnectionManager
getMultiThreadedConnManager() {
72 if (mConnManager
== null
) {
73 mConnManager
= new MultiThreadedHttpConnectionManager();
74 mConnManager
.setMaxConnectionsPerHost(5);
75 mConnManager
.setMaxTotalConnections(5);
81 * Creates a WebdavClient setup for the current account
82 * @param account The client accout
83 * @param context The application context
86 public WebdavClient (Account account
, Context context
) {
87 Log
.d(TAG
, "Creating WebdavClient associated to " + account
.name
);
91 OwnCloudVersion ownCloudVersion
= new OwnCloudVersion(AccountManager
.get(context
).getUserData(account
,
92 AccountAuthenticator
.KEY_OC_VERSION
));
93 String baseUrl
= AccountManager
.get(context
).getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
);
94 String webDavPath
= AccountUtils
.getWebdavPath(ownCloudVersion
);
95 String username
= account
.name
.substring(0, account
.name
.lastIndexOf('@'));
96 String password
= AccountManager
.get(context
).getPassword(account
);
98 mUri
= Uri
.parse(baseUrl
+ webDavPath
);
99 Log
.e("ASD", ""+username
);
100 setCredentials(username
, password
);
103 public WebdavClient() {
104 super(getMultiThreadedConnManager());
105 Log
.d(TAG
, "Creating WebdavClient");
107 setDefaultTimeouts();
109 getParams().setParameter(HttpMethodParams
.USER_AGENT
, USER_AGENT
);
110 getParams().setParameter(CoreProtocolPNames
.PROTOCOL_VERSION
, HttpVersion
.HTTP_1_1
);
111 allowSelfsignedCertificates();
114 public void setCredentials(String username
, String password
) {
115 getParams().setAuthenticationPreemptive(true
);
116 getState().setCredentials(AuthScope
.ANY
,
117 getCredentials(username
, password
));
120 private Credentials
getCredentials(String username
, String password
) {
121 if (mCredentials
== null
)
122 mCredentials
= new UsernamePasswordCredentials(username
, password
);
127 * Sets the connection and wait-for-data timeouts to be applied by default.
129 private void setDefaultTimeouts() {
130 getParams().setSoTimeout(DEFAULT_DATA_TIMEOUT
);
131 getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT
);
134 public void allowSelfsignedCertificates() {
136 Protocol
.registerProtocol("https", new Protocol("https",
137 new EasySSLSocketFactory(), 443));
141 * Downloads a file in remoteFilepath to the local targetPath.
143 * @param remoteFilepath Path to the file in the remote server, URL DECODED.
144 * @param targetFile Local path to save the downloaded file.
145 * @return 'True' when the file is successfully downloaded.
147 public boolean downloadFile(String remoteFilepath
, File targetFile
) {
149 GetMethod get
= new GetMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteFilepath
));
153 status
= executeMethod(get
);
154 if (status
== HttpStatus
.SC_OK
) {
155 targetFile
.createNewFile();
156 BufferedInputStream bis
= new BufferedInputStream(
157 get
.getResponseBodyAsStream());
158 FileOutputStream fos
= new FileOutputStream(targetFile
);
160 byte[] bytes
= new byte[4096];
162 while ((readResult
= bis
.read(bytes
)) != -1) {
163 if (mDataTransferListener
!= null
)
164 mDataTransferListener
.transferProgress(readResult
);
165 fos
.write(bytes
, 0, readResult
);
170 } catch (HttpException e
) {
171 Log
.e(TAG
, "HTTP exception downloading " + remoteFilepath
, e
);
173 } catch (IOException e
) {
174 Log
.e(TAG
, "I/O exception downloading " + remoteFilepath
, e
);
176 } catch (Exception e
) {
177 Log
.e(TAG
, "Unexpected exception downloading " + remoteFilepath
, e
);
182 Log
.e(TAG
, "Download of " + remoteFilepath
+ " to " + targetFile
+ " failed with HTTP status " + status
);
184 if (targetFile
.exists()) {
193 * Deletes a remote file via webdav
194 * @param remoteFilePath Remote file path of the file to delete, in URL DECODED format.
197 public boolean deleteFile(String remoteFilePath
){
198 DavMethod delete
= new DeleteMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteFilePath
));
200 executeMethod(delete
);
201 } catch (Throwable e
) {
202 Log
.e(TAG
, "Deleting failed with error: " + e
.getMessage(), e
);
208 public void setDataTransferProgressListener(OnDatatransferProgressListener listener
) {
209 mDataTransferListener
= listener
;
213 * Creates or update a file in the remote server with the contents of a local file.
216 * @param localFile Path to the local file to upload.
217 * @param remoteTarget Remote path to the file to create or update, URL DECODED
218 * @param contentType MIME type of the file.
219 * @return 'True' then the upload was successfully completed
221 public boolean putFile(String localFile
, String remoteTarget
, String contentType
) {
222 boolean result
= false
;
226 File f
= new File(localFile
);
227 FileRequestEntity entity
= new FileRequestEntity(f
, contentType
);
228 entity
.setOnDatatransferProgressListener(mDataTransferListener
);
229 PutMethod put
= new PutMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteTarget
));
230 put
.setRequestEntity(entity
);
231 status
= executeMethod(put
);
233 result
= (status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
);
235 Log
.d(TAG
, "PUT response for " + remoteTarget
+ " finished with HTTP status " + status
);
237 } catch (HttpException e
) {
238 Log
.e(TAG
, "HTTP exception uploading " + localFile
+ " to " + remoteTarget
, e
);
240 } catch (IOException e
) {
241 Log
.e(TAG
, "I/O exception uploading " + localFile
+ " to " + remoteTarget
, e
);
243 } catch (Exception e
) {
244 Log
.e(TAG
, "Unexpected exception uploading " + localFile
+ " to " + remoteTarget
, e
);
247 if (!result
&& status
>= 0) Log
.e(TAG
, "Upload of " + localFile
+ " to " + remoteTarget
+ " FAILED with HTTP status " + status
);
253 * Tries to log in to the given WedDavURI, with the given credentials
255 * @param username Username to check
256 * @param password Password to verify
257 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
259 public static int tryToLogin(Uri uri
, String username
, String password
) {
262 WebdavClient client
= new WebdavClient();
263 client
.setCredentials(username
, password
);
264 HeadMethod head
= new HeadMethod(uri
.toString());
265 returnCode
= client
.executeMethod(head
);
266 } catch (HttpException e
) {
267 Log
.e(TAG
, "HTTP exception trying to login at " + uri
.getEncodedPath(), e
);
268 } catch (IOException e
) {
269 Log
.e(TAG
, "I/O exception trying to login at " + uri
.getEncodedPath(), e
);
270 } catch (Exception e
) {
271 Log
.e(TAG
, "Unexpected exception trying to login at " + uri
.getEncodedPath(), e
);
277 * Creates a remote directory with the received path.
279 * @param path Path of the directory to create, URL DECODED
280 * @return 'True' when the directory is successfully created
282 public boolean createDirectory(String path
) {
283 boolean result
= false
;
286 MkColMethod mkcol
= new MkColMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
287 Log
.d(TAG
, "Creating directory " + path
);
288 status
= executeMethod(mkcol
);
289 Log
.d(TAG
, "Status returned: " + status
);
290 result
= mkcol
.succeeded();
292 } catch (HttpException e
) {
293 Log
.e(TAG
, "HTTP exception creating directory " + path
, e
);
295 } catch (IOException e
) {
296 Log
.e(TAG
, "I/O exception creating directory " + path
, e
);
298 } catch (Exception e
) {
299 Log
.e(TAG
, "Unexpected exception creating directory " + path
, e
);
302 if (!result
&& status
>= 0) {
303 Log
.e(TAG
, "Creation of directory " + path
+ " failed with HTTP status " + status
);
310 * Check if a file exists in the OC server
312 * @return 'Boolean.TRUE' if the file exists; 'Boolean.FALSE' it doesn't exist; NULL if couldn't be checked
314 public Boolean
existsFile(String path
) {
316 HeadMethod head
= new HeadMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
317 int status
= executeMethod(head
);
318 return (status
== HttpStatus
.SC_OK
);
319 } catch (Exception e
) {
327 * Requests the received method with the received timeout (milliseconds).
329 * Executes the method through the inherited HttpClient.executedMethod(method).
331 * Sets the socket timeout for the HttpMethodBase method received.
333 * @param method HTTP method request.
334 * @param timeout Timeout to set, in milliseconds; <= 0 means infinite.
336 public int executeMethod(HttpMethodBase method
, int readTimeout
) throws HttpException
, IOException
{
337 int oldSoTimeout
= getParams().getSoTimeout();
339 if (readTimeout
< 0) {
342 HttpMethodParams params
= method
.getParams();
343 params
.setSoTimeout(readTimeout
);
344 method
.setParams(params
); // this should be enough...
345 getParams().setSoTimeout(readTimeout
); // ... but this is necessary for HTTPS
346 return executeMethod(method
);
348 getParams().setSoTimeout(oldSoTimeout
);