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
) {
89 OwnCloudVersion ownCloudVersion
= new OwnCloudVersion(AccountManager
.get(context
).getUserData(account
,
90 AccountAuthenticator
.KEY_OC_VERSION
));
91 String baseUrl
= AccountManager
.get(context
).getUserData(account
, AccountAuthenticator
.KEY_OC_BASE_URL
);
92 String webDavPath
= AccountUtils
.getWebdavPath(ownCloudVersion
);
93 String username
= account
.name
.substring(0, account
.name
.lastIndexOf('@'));
94 String password
= AccountManager
.get(context
).getPassword(account
);
96 mUri
= Uri
.parse(baseUrl
+ webDavPath
);
97 Log
.e("ASD", ""+username
);
98 setCredentials(username
, password
);
101 public WebdavClient() {
102 super(getMultiThreadedConnManager());
104 setDefaultTimeouts();
106 getParams().setParameter(HttpMethodParams
.USER_AGENT
, USER_AGENT
);
107 getParams().setParameter(CoreProtocolPNames
.PROTOCOL_VERSION
, HttpVersion
.HTTP_1_1
);
108 allowSelfsignedCertificates();
111 public void setCredentials(String username
, String password
) {
112 getParams().setAuthenticationPreemptive(true
);
113 getState().setCredentials(AuthScope
.ANY
,
114 getCredentials(username
, password
));
117 private Credentials
getCredentials(String username
, String password
) {
118 if (mCredentials
== null
)
119 mCredentials
= new UsernamePasswordCredentials(username
, password
);
124 * Sets the connection and wait-for-data timeouts to be applied by default.
126 private void setDefaultTimeouts() {
127 getParams().setSoTimeout(DEFAULT_DATA_TIMEOUT
);
128 getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT
);
131 public void allowSelfsignedCertificates() {
133 Protocol
.registerProtocol("https", new Protocol("https",
134 new EasySSLSocketFactory(), 443));
138 * Downloads a file in remoteFilepath to the local targetPath.
140 * @param remoteFilepath Path to the file in the remote server, URL DECODED.
141 * @param targetFile Local path to save the downloaded file.
142 * @return 'True' when the file is successfully downloaded.
144 public boolean downloadFile(String remoteFilepath
, File targetFile
) {
146 GetMethod get
= new GetMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteFilepath
));
150 status
= executeMethod(get
);
151 if (status
== HttpStatus
.SC_OK
) {
152 targetFile
.createNewFile();
153 BufferedInputStream bis
= new BufferedInputStream(
154 get
.getResponseBodyAsStream());
155 FileOutputStream fos
= new FileOutputStream(targetFile
);
157 byte[] bytes
= new byte[4096];
159 while ((readResult
= bis
.read(bytes
)) != -1) {
160 if (mDataTransferListener
!= null
)
161 mDataTransferListener
.transferProgress(readResult
);
162 fos
.write(bytes
, 0, readResult
);
167 } catch (HttpException e
) {
168 Log
.e(TAG
, "HTTP exception downloading " + remoteFilepath
, e
);
170 } catch (IOException e
) {
171 Log
.e(TAG
, "I/O exception downloading " + remoteFilepath
, e
);
173 } catch (Exception e
) {
174 Log
.e(TAG
, "Unexpected exception downloading " + remoteFilepath
, e
);
179 Log
.e(TAG
, "Download of " + remoteFilepath
+ " to " + targetFile
+ " failed with HTTP status " + status
);
181 if (targetFile
.exists()) {
190 * Deletes a remote file via webdav
191 * @param remoteFilePath Remote file path of the file to delete, in URL DECODED format.
194 public boolean deleteFile(String remoteFilePath
){
195 DavMethod delete
= new DeleteMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteFilePath
));
197 executeMethod(delete
);
198 } catch (Throwable e
) {
199 Log
.e(TAG
, "Deleting failed with error: " + e
.getMessage(), e
);
205 public void setDataTransferProgressListener(OnDatatransferProgressListener listener
) {
206 mDataTransferListener
= listener
;
210 * Creates or update a file in the remote server with the contents of a local file.
213 * @param localFile Path to the local file to upload.
214 * @param remoteTarget Remote path to the file to create or update, URL DECODED
215 * @param contentType MIME type of the file.
216 * @return 'True' then the upload was successfully completed
218 public boolean putFile(String localFile
, String remoteTarget
, String contentType
) {
219 boolean result
= false
;
223 File f
= new File(localFile
);
224 FileRequestEntity entity
= new FileRequestEntity(f
, contentType
);
225 entity
.setOnDatatransferProgressListener(mDataTransferListener
);
226 PutMethod put
= new PutMethod(mUri
.toString() + WebdavUtils
.encodePath(remoteTarget
));
227 put
.setRequestEntity(entity
);
228 status
= executeMethod(put
);
230 result
= (status
== HttpStatus
.SC_OK
|| status
== HttpStatus
.SC_CREATED
|| status
== HttpStatus
.SC_NO_CONTENT
);
232 Log
.d(TAG
, "PUT response for " + remoteTarget
+ " finished with HTTP status " + status
);
234 } catch (HttpException e
) {
235 Log
.e(TAG
, "HTTP exception uploading " + localFile
+ " to " + remoteTarget
, e
);
237 } catch (IOException e
) {
238 Log
.e(TAG
, "I/O exception uploading " + localFile
+ " to " + remoteTarget
, e
);
240 } catch (Exception e
) {
241 Log
.e(TAG
, "Unexpected exception uploading " + localFile
+ " to " + remoteTarget
, e
);
244 if (!result
&& status
>= 0) Log
.e(TAG
, "Upload of " + localFile
+ " to " + remoteTarget
+ " FAILED with HTTP status " + status
);
250 * Tries to log in to the given WedDavURI, with the given credentials
252 * @param username Username to check
253 * @param password Password to verify
254 * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
256 public static int tryToLogin(Uri uri
, String username
, String password
) {
259 WebdavClient client
= new WebdavClient();
260 client
.setCredentials(username
, password
);
261 HeadMethod head
= new HeadMethod(uri
.toString());
262 returnCode
= client
.executeMethod(head
);
263 } catch (HttpException e
) {
264 Log
.e(TAG
, "HTTP exception trying to login at " + uri
.getEncodedPath(), e
);
265 } catch (IOException e
) {
266 Log
.e(TAG
, "I/O exception trying to login at " + uri
.getEncodedPath(), e
);
267 } catch (Exception e
) {
268 Log
.e(TAG
, "Unexpected exception trying to login at " + uri
.getEncodedPath(), e
);
274 * Creates a remote directory with the received path.
276 * @param path Path of the directory to create, URL DECODED
277 * @return 'True' when the directory is successfully created
279 public boolean createDirectory(String path
) {
280 boolean result
= false
;
283 MkColMethod mkcol
= new MkColMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
284 Log
.d(TAG
, "Creating directory " + path
);
285 status
= executeMethod(mkcol
);
286 Log
.d(TAG
, "Status returned: " + status
);
287 result
= mkcol
.succeeded();
289 } catch (HttpException e
) {
290 Log
.e(TAG
, "HTTP exception creating directory " + path
, e
);
292 } catch (IOException e
) {
293 Log
.e(TAG
, "I/O exception creating directory " + path
, e
);
295 } catch (Exception e
) {
296 Log
.e(TAG
, "Unexpected exception creating directory " + path
, e
);
299 if (!result
&& status
>= 0) {
300 Log
.e(TAG
, "Creation of directory " + path
+ " failed with HTTP status " + status
);
307 * Check if a file exists in the OC server
309 * @return 'Boolean.TRUE' if the file exists; 'Boolean.FALSE' it doesn't exist; NULL if couldn't be checked
311 public Boolean
existsFile(String path
) {
313 HeadMethod head
= new HeadMethod(mUri
.toString() + WebdavUtils
.encodePath(path
));
314 int status
= executeMethod(head
);
315 return (status
== HttpStatus
.SC_OK
);
316 } catch (Exception e
) {
324 * Requests the received method with the received timeout (milliseconds).
326 * Executes the method through the inherited HttpClient.executedMethod(method).
328 * Sets the socket timeout for the HttpMethodBase method received.
330 * @param method HTTP method request.
331 * @param timeout Timeout to set, in milliseconds; <= 0 means infinite.
333 public int executeMethod(HttpMethodBase method
, int readTimeout
) throws HttpException
, IOException
{
334 int oldSoTimeout
= getParams().getSoTimeout();
336 if (readTimeout
< 0) {
339 HttpMethodParams params
= method
.getParams();
340 params
.setSoTimeout(readTimeout
);
341 method
.setParams(params
); // this should be enough...
342 getParams().setSoTimeout(readTimeout
); // ... but this is necessary for HTTPS
343 return executeMethod(method
);
345 getParams().setSoTimeout(oldSoTimeout
);