WebdavClient.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /* ownCloud Android client application
  2. * Copyright (C) 2011 Bartek Przybylski
  3. *
  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.
  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. import java.io.BufferedInputStream;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import org.apache.commons.httpclient.Credentials;
  24. import org.apache.commons.httpclient.HttpClient;
  25. import org.apache.commons.httpclient.HttpException;
  26. import org.apache.commons.httpclient.HttpMethodBase;
  27. import org.apache.commons.httpclient.HttpVersion;
  28. import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
  29. import org.apache.commons.httpclient.UsernamePasswordCredentials;
  30. import org.apache.commons.httpclient.auth.AuthScope;
  31. import org.apache.commons.httpclient.methods.GetMethod;
  32. import org.apache.commons.httpclient.methods.HeadMethod;
  33. import org.apache.commons.httpclient.methods.PutMethod;
  34. import org.apache.commons.httpclient.params.HttpMethodParams;
  35. import org.apache.commons.httpclient.protocol.Protocol;
  36. import org.apache.http.HttpStatus;
  37. import org.apache.http.params.CoreProtocolPNames;
  38. import org.apache.jackrabbit.webdav.client.methods.DavMethod;
  39. import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
  40. import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
  41. import com.owncloud.android.AccountUtils;
  42. import com.owncloud.android.authenticator.AccountAuthenticator;
  43. import com.owncloud.android.authenticator.EasySSLSocketFactory;
  44. import com.owncloud.android.files.interfaces.OnDatatransferProgressListener;
  45. import com.owncloud.android.utils.OwnCloudVersion;
  46. import android.accounts.Account;
  47. import android.accounts.AccountManager;
  48. import android.content.Context;
  49. import android.net.Uri;
  50. import android.util.Log;
  51. public class WebdavClient extends HttpClient {
  52. private Uri mUri;
  53. private Credentials mCredentials;
  54. final private static String TAG = "WebdavClient";
  55. private static final String USER_AGENT = "Android-ownCloud";
  56. /** Default timeout for waiting data from the server: 10 seconds */
  57. public static final int DEFAULT_DATA_TIMEOUT = 10000;
  58. /** Default timeout for establishing a connection: infinite */
  59. public static final int DEFAULT_CONNECTION_TIMEOUT = 0;
  60. private OnDatatransferProgressListener mDataTransferListener;
  61. static private MultiThreadedHttpConnectionManager mConnManager = null;
  62. static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() {
  63. if (mConnManager == null) {
  64. mConnManager = new MultiThreadedHttpConnectionManager();
  65. mConnManager.setMaxConnectionsPerHost(5);
  66. mConnManager.setMaxTotalConnections(5);
  67. }
  68. return mConnManager;
  69. }
  70. /**
  71. * Creates a WebdavClient setup for the current account
  72. * @param account The client accout
  73. * @param context The application context
  74. * @return
  75. */
  76. public WebdavClient (Account account, Context context) {
  77. setDefaultTimeouts();
  78. OwnCloudVersion ownCloudVersion = new OwnCloudVersion(AccountManager.get(context).getUserData(account,
  79. AccountAuthenticator.KEY_OC_VERSION));
  80. String baseUrl = AccountManager.get(context).getUserData(account, AccountAuthenticator.KEY_OC_BASE_URL);
  81. String webDavPath = AccountUtils.getWebdavPath(ownCloudVersion);
  82. String username = account.name.substring(0, account.name.lastIndexOf('@'));
  83. String password = AccountManager.get(context).getPassword(account);
  84. mUri = Uri.parse(baseUrl + webDavPath);
  85. Log.e("ASD", ""+username);
  86. setCredentials(username, password);
  87. }
  88. public WebdavClient() {
  89. super(getMultiThreadedConnManager());
  90. setDefaultTimeouts();
  91. getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
  92. getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
  93. allowSelfsignedCertificates();
  94. }
  95. public void setCredentials(String username, String password) {
  96. getParams().setAuthenticationPreemptive(true);
  97. getState().setCredentials(AuthScope.ANY,
  98. getCredentials(username, password));
  99. }
  100. private Credentials getCredentials(String username, String password) {
  101. if (mCredentials == null)
  102. mCredentials = new UsernamePasswordCredentials(username, password);
  103. return mCredentials;
  104. }
  105. /**
  106. * Sets the connection and wait-for-data timeouts to be applied by default.
  107. */
  108. private void setDefaultTimeouts() {
  109. getParams().setSoTimeout(DEFAULT_DATA_TIMEOUT);
  110. getHttpConnectionManager().getParams().setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
  111. }
  112. public void allowSelfsignedCertificates() {
  113. // https
  114. Protocol.registerProtocol("https", new Protocol("https",
  115. new EasySSLSocketFactory(), 443));
  116. }
  117. /**
  118. * Downloads a file in remoteFilepath to the local targetPath.
  119. *
  120. * @param remoteFilepath Path to the file in the remote server, URL DECODED.
  121. * @param targetFile Local path to save the downloaded file.
  122. * @return 'True' when the file is successfully downloaded.
  123. */
  124. public boolean downloadFile(String remoteFilepath, File targetFile) {
  125. boolean ret = false;
  126. GetMethod get = new GetMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilepath));
  127. int status = -1;
  128. try {
  129. status = executeMethod(get);
  130. if (status == HttpStatus.SC_OK) {
  131. targetFile.createNewFile();
  132. BufferedInputStream bis = new BufferedInputStream(
  133. get.getResponseBodyAsStream());
  134. FileOutputStream fos = new FileOutputStream(targetFile);
  135. byte[] bytes = new byte[4096];
  136. int readResult;
  137. while ((readResult = bis.read(bytes)) != -1) {
  138. if (mDataTransferListener != null)
  139. mDataTransferListener.transferProgress(readResult);
  140. fos.write(bytes, 0, readResult);
  141. }
  142. ret = true;
  143. }
  144. } catch (HttpException e) {
  145. Log.e(TAG, "HTTP exception downloading " + remoteFilepath, e);
  146. } catch (IOException e) {
  147. Log.e(TAG, "I/O exception downloading " + remoteFilepath, e);
  148. } catch (Exception e) {
  149. Log.e(TAG, "Unexpected exception downloading " + remoteFilepath, e);
  150. } finally {
  151. if (!ret) {
  152. if (status >= 0) {
  153. Log.e(TAG, "Download of " + remoteFilepath + " to " + targetFile + " failed with HTTP status " + status);
  154. }
  155. if (targetFile.exists()) {
  156. targetFile.delete();
  157. }
  158. }
  159. }
  160. return ret;
  161. }
  162. /**
  163. * Deletes a remote file via webdav
  164. * @param remoteFilePath Remote file path of the file to delete, in URL DECODED format.
  165. * @return
  166. */
  167. public boolean deleteFile(String remoteFilePath){
  168. DavMethod delete = new DeleteMethod(mUri.toString() + WebdavUtils.encodePath(remoteFilePath));
  169. try {
  170. executeMethod(delete);
  171. } catch (Throwable e) {
  172. Log.e(TAG, "Deleting failed with error: " + e.getMessage(), e);
  173. return false;
  174. }
  175. return true;
  176. }
  177. public void setDataTransferProgressListener(OnDatatransferProgressListener listener) {
  178. mDataTransferListener = listener;
  179. }
  180. /**
  181. * Creates or update a file in the remote server with the contents of a local file.
  182. *
  183. *
  184. * @param localFile Path to the local file to upload.
  185. * @param remoteTarget Remote path to the file to create or update, URL DECODED
  186. * @param contentType MIME type of the file.
  187. * @return 'True' then the upload was successfully completed
  188. */
  189. public boolean putFile(String localFile, String remoteTarget, String contentType) {
  190. boolean result = false;
  191. int status = -1;
  192. try {
  193. File f = new File(localFile);
  194. FileRequestEntity entity = new FileRequestEntity(f, contentType);
  195. entity.setOnDatatransferProgressListener(mDataTransferListener);
  196. PutMethod put = new PutMethod(mUri.toString() + WebdavUtils.encodePath(remoteTarget));
  197. put.setRequestEntity(entity);
  198. status = executeMethod(put);
  199. result = (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT);
  200. Log.d(TAG, "PUT response for " + remoteTarget + " finished with HTTP status " + status);
  201. } catch (HttpException e) {
  202. Log.e(TAG, "HTTP exception uploading " + localFile + " to " + remoteTarget, e);
  203. } catch (IOException e) {
  204. Log.e(TAG, "I/O exception uploading " + localFile + " to " + remoteTarget, e);
  205. } catch (Exception e) {
  206. Log.e(TAG, "Unexpected exception uploading " + localFile + " to " + remoteTarget, e);
  207. }
  208. if (!result && status >= 0) Log.e(TAG, "Upload of " + localFile + " to " + remoteTarget + " FAILED with HTTP status " + status);
  209. return result;
  210. }
  211. /**
  212. * Tries to log in to the given WedDavURI, with the given credentials
  213. * @param uri To test
  214. * @param username Username to check
  215. * @param password Password to verify
  216. * @return A {@link HttpStatus}-Code of the result. SC_OK is good.
  217. */
  218. public static int tryToLogin(Uri uri, String username, String password) {
  219. int returnCode = 0;
  220. try {
  221. WebdavClient client = new WebdavClient();
  222. client.setCredentials(username, password);
  223. HeadMethod head = new HeadMethod(uri.toString());
  224. returnCode = client.executeMethod(head);
  225. } catch (HttpException e) {
  226. Log.e(TAG, "HTTP exception trying to login at " + uri.getEncodedPath(), e);
  227. } catch (IOException e) {
  228. Log.e(TAG, "I/O exception trying to login at " + uri.getEncodedPath(), e);
  229. } catch (Exception e) {
  230. Log.e(TAG, "Unexpected exception trying to login at " + uri.getEncodedPath(), e);
  231. }
  232. return returnCode;
  233. }
  234. /**
  235. * Creates a remote directory with the received path.
  236. *
  237. * @param path Path of the directory to create, URL DECODED
  238. * @return 'True' when the directory is successfully created
  239. */
  240. public boolean createDirectory(String path) {
  241. boolean result = false;
  242. int status = -1;
  243. try {
  244. MkColMethod mkcol = new MkColMethod(mUri.toString() + WebdavUtils.encodePath(path));
  245. Log.d(TAG, "Creating directory " + path);
  246. status = executeMethod(mkcol);
  247. Log.d(TAG, "Status returned: " + status);
  248. result = mkcol.succeeded();
  249. } catch (HttpException e) {
  250. Log.e(TAG, "HTTP exception creating directory " + path, e);
  251. } catch (IOException e) {
  252. Log.e(TAG, "I/O exception creating directory " + path, e);
  253. } catch (Exception e) {
  254. Log.e(TAG, "Unexpected exception creating directory " + path, e);
  255. }
  256. if (!result && status >= 0) {
  257. Log.e(TAG, "Creation of directory " + path + " failed with HTTP status " + status);
  258. }
  259. return result;
  260. }
  261. /**
  262. * Check if a file exists in the OC server
  263. *
  264. * @return 'Boolean.TRUE' if the file exists; 'Boolean.FALSE' it doesn't exist; NULL if couldn't be checked
  265. */
  266. public Boolean existsFile(String path) {
  267. try {
  268. HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path));
  269. int status = executeMethod(head);
  270. return (status == HttpStatus.SC_OK);
  271. } catch (Exception e) {
  272. e.printStackTrace();
  273. return null;
  274. }
  275. }
  276. /**
  277. * Requests the received method with the received timeout (milliseconds).
  278. *
  279. * Executes the method through the inherited HttpClient.executedMethod(method).
  280. *
  281. * Sets the socket timeout for the HttpMethodBase method received.
  282. *
  283. * @param method HTTP method request.
  284. * @param timeout Timeout to set, in milliseconds; <= 0 means infinite.
  285. */
  286. public int executeMethod(HttpMethodBase method, int readTimeout) throws HttpException, IOException {
  287. int oldSoTimeout = getParams().getSoTimeout();
  288. try {
  289. if (readTimeout < 0) {
  290. readTimeout = 0;
  291. }
  292. HttpMethodParams params = method.getParams();
  293. params.setSoTimeout(readTimeout);
  294. method.setParams(params); // this should be enough...
  295. getParams().setSoTimeout(readTimeout); // ... but this is necessary for HTTPS
  296. return executeMethod(method);
  297. } finally {
  298. getParams().setSoTimeout(oldSoTimeout);
  299. }
  300. }
  301. }