From: David A. Velasco Date: Mon, 20 Jan 2014 10:59:41 +0000 (+0100) Subject: Library updated with final names (project and packages) X-Git-Tag: oc-android-1.5.5~69^2~11 X-Git-Url: http://git.linex4red.de/pub/Android/ownCloud.git/commitdiff_plain/1e68dccd8b3efa28e1ebc5d12d5c9ce4a3260a9f?ds=inline Library updated with final names (project and packages) --- diff --git a/oc_framework-test-project/.classpath b/oc_framework-test-project/.classpath index 394360f0..51769745 100644 --- a/oc_framework-test-project/.classpath +++ b/oc_framework-test-project/.classpath @@ -3,7 +3,6 @@ - diff --git a/oc_framework-test-project/.project b/oc_framework-test-project/.project index 8c7df640..66824491 100644 --- a/oc_framework-test-project/.project +++ b/oc_framework-test-project/.project @@ -1,6 +1,6 @@ - oc_framework-test-project + ownCloud Android Library Test Project diff --git a/oc_framework-test-project/AndroidManifest.xml b/oc_framework-test-project/AndroidManifest.xml index f09a605d..1ce1eb2f 100644 --- a/oc_framework-test-project/AndroidManifest.xml +++ b/oc_framework-test-project/AndroidManifest.xml @@ -24,7 +24,7 @@ --> @@ -47,7 +47,7 @@ android:label="@string/app_name" android:theme="@style/AppTheme" > diff --git a/oc_framework-test-project/oc_framework-test-test/.classpath b/oc_framework-test-project/oc_framework-test-test/.classpath index 6c54c1c9..c1044509 100644 --- a/oc_framework-test-project/oc_framework-test-test/.classpath +++ b/oc_framework-test-project/oc_framework-test-test/.classpath @@ -3,8 +3,8 @@ - + diff --git a/oc_framework-test-project/oc_framework-test-test/.project b/oc_framework-test-project/oc_framework-test-test/.project index c490827b..60be749d 100644 --- a/oc_framework-test-project/oc_framework-test-test/.project +++ b/oc_framework-test-project/oc_framework-test-test/.project @@ -1,6 +1,6 @@ - oc_framework-test + ownCloud Android Library Tests oc_framework-test-project diff --git a/oc_framework-test-project/oc_framework-test-test/AndroidManifest.xml b/oc_framework-test-project/oc_framework-test-test/AndroidManifest.xml index b29d32e0..f71a9502 100644 --- a/oc_framework-test-project/oc_framework-test-test/AndroidManifest.xml +++ b/oc_framework-test-project/oc_framework-test-test/AndroidManifest.xml @@ -24,7 +24,7 @@ --> @@ -35,7 +35,7 @@ + android:label="Tests for com.owncloud.android.lib.test_project" + android:targetPackage="com.owncloud.android.lib.test_project" /> \ No newline at end of file diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/CreateFolderTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/CreateFolderTest.java new file mode 100644 index 00000000..af9677f9 --- /dev/null +++ b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/CreateFolderTest.java @@ -0,0 +1,119 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +package com.owncloud.android.lib.test_project.test; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.test_project.TestActivity; + +import android.test.ActivityInstrumentationTestCase2; + +/** + * Class to test Create Folder Operation + * @author masensio + * + */ +public class CreateFolderTest extends ActivityInstrumentationTestCase2 { + + private TestActivity mActivity; + private String mCurrentDate; + + public CreateFolderTest() { + super(TestActivity.class); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); + mCurrentDate = sdf.format(new Date()); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + } + + /** + * Test Create Folder + */ + public void testCreateFolder() { + + String remotePath = "/testCreateFolder" + mCurrentDate; + boolean createFullPath = true; + + RemoteOperationResult result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.isSuccess() || result.getCode() == ResultCode.TIMEOUT); + + // Create Subfolder + remotePath = "/testCreateFolder" + mCurrentDate + "/" + "testCreateFolder" + mCurrentDate; + createFullPath = true; + + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.isSuccess() || result.getCode() == ResultCode.TIMEOUT); + } + + + /** + * Test to Create Folder with special characters: / \ < > : " | ? * + */ + public void testCreateFolderSpecialCharacters() { + boolean createFullPath = true; + + String remotePath = "/testSpecialCharacters_\\" + mCurrentDate; + RemoteOperationResult result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + remotePath = "/testSpecialCharacters_<" + mCurrentDate; + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + remotePath = "/testSpecialCharacters_>" + mCurrentDate; + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + remotePath = "/testSpecialCharacters_:" + mCurrentDate; + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + remotePath = "/testSpecialCharacters_\"" + mCurrentDate; + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + remotePath = "/testSpecialCharacters_|" + mCurrentDate; + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + remotePath = "/testSpecialCharacters_?" + mCurrentDate; + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + remotePath = "/testSpecialCharacters_*" + mCurrentDate; + result = mActivity.createFolder(remotePath, createFullPath); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + } + + +} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/DeleteFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/DeleteFileTest.java new file mode 100644 index 00000000..5edab941 --- /dev/null +++ b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/DeleteFileTest.java @@ -0,0 +1,87 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.test_project.test; + +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.test_project.TestActivity; + +import android.test.ActivityInstrumentationTestCase2; + +/** + * Class to test Delete a File Operation + * @author masensio + * + */ + +public class DeleteFileTest extends ActivityInstrumentationTestCase2 { + + /* Folder data to delete. */ + private final String mFolderPath = "/folderToDelete"; + + /* File to delete. */ + private final String mFilePath = "fileToDelete.png"; + + private TestActivity mActivity; + + public DeleteFileTest() { + super(TestActivity.class); + + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + } + + /** + * Test Remove Folder + */ + public void testRemoveFolder() { + + RemoteOperationResult result = mActivity.removeFile(mFolderPath); + assertTrue(result.isSuccess() || result.getCode() == ResultCode.FILE_NOT_FOUND); + } + + /** + * Test Remove File + */ + public void testRemoveFile() { + + RemoteOperationResult result = mActivity.removeFile(mFilePath); + assertTrue(result.isSuccess() || result.getCode() == ResultCode.FILE_NOT_FOUND); + } + + /** + * Restore initial conditions + */ + public void testRestoreInitialConditions() { + RemoteOperationResult result = mActivity.createFolder(mFolderPath, true); + assertTrue(result.isSuccess()); + + } +} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/DownloadFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/DownloadFileTest.java new file mode 100644 index 00000000..2eb523a2 --- /dev/null +++ b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/DownloadFileTest.java @@ -0,0 +1,130 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.test_project.test; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import com.owncloud.android.lib.operations.common.RemoteFile; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.test_project.TestActivity; + +import android.test.ActivityInstrumentationTestCase2; + +/** + * Class to test Download File Operation + * @author masensio + * + */ + +public class DownloadFileTest extends ActivityInstrumentationTestCase2 { + + + /* Files to download. These files must exist on the account */ + private final String mRemoteFilePng = "/fileToDownload.png"; + private final String mRemoteFileChunks = "/fileToDownload.mp4"; + private final String mRemoteFileSpecialChars = "/@file@download.png"; + private final String mRemoteFileSpecialCharsChunks = "/@file@download.mp4"; + private final String mRemoteFileNotFound = "/fileNotFound.png"; /* This file mustn't exist on the account */ + + private String mCurrentDate; + + + private TestActivity mActivity; + + public DownloadFileTest() { + super(TestActivity.class); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); + mCurrentDate = sdf.format(new Date()); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + } + + /** + * Test Download a File + */ + public void testDownloadFile() { + String temporalFolder = "/download" + mCurrentDate; + + RemoteFile remoteFile= new RemoteFile(mRemoteFilePng); + + RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); + assertTrue(result.isSuccess()); + } + + /** + * Test Download a File with chunks + */ + public void testDownloadFileChunks() { + String temporalFolder = "/download" + mCurrentDate; + + RemoteFile remoteFile= new RemoteFile(mRemoteFileChunks); + + RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); + assertTrue(result.isSuccess()); + } + + /** + * Test Download a File with special chars + */ + public void testDownloadFileSpecialChars() { + String temporalFolder = "/download" + mCurrentDate; + + RemoteFile remoteFile= new RemoteFile(mRemoteFileSpecialChars); + + RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); + assertTrue(result.isSuccess()); + } + + /** + * Test Download a File with special chars and chunks + */ + public void testDownloadFileSpecialCharsChunks() { + String temporalFolder = "/download" + mCurrentDate; + + RemoteFile remoteFile= new RemoteFile(mRemoteFileSpecialCharsChunks); + + RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); + assertTrue(result.isSuccess()); + } + + /** + * Test Download a Not Found File + */ + public void testDownloadFileNotFound() { + String temporalFolder = "/download" + mCurrentDate; + + RemoteFile remoteFile = new RemoteFile(mRemoteFileNotFound); + + RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); + assertFalse(result.isSuccess()); + } +} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/ReadFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/ReadFileTest.java new file mode 100644 index 00000000..0c9bd5a3 --- /dev/null +++ b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/ReadFileTest.java @@ -0,0 +1,67 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +package com.owncloud.android.lib.test_project.test; + +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.test_project.TestActivity; + +import android.test.ActivityInstrumentationTestCase2; + +/** + * Class to test Read File Operation + * @author masensio + * + */ + +public class ReadFileTest extends ActivityInstrumentationTestCase2 { + + /* File data to read. This file must exist on the account */ + private final String mRemoteFolderPath = "/fileToRead.txt"; + + + private TestActivity mActivity; + + public ReadFileTest() { + super(TestActivity.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + } + + /** + * Test Read File + */ + public void testReadFile() { + + RemoteOperationResult result = mActivity.readFile(mRemoteFolderPath); + assertTrue(result.getData().size() == 1); + assertTrue(result.isSuccess()); + } + + +} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/ReadFolderTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/ReadFolderTest.java new file mode 100644 index 00000000..496ea2c5 --- /dev/null +++ b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/ReadFolderTest.java @@ -0,0 +1,69 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.test_project.test; + +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.test_project.TestActivity; + +import android.test.ActivityInstrumentationTestCase2; + +/** + * Class to test Read Folder Operation + * @author masensio + * + */ + +public class ReadFolderTest extends ActivityInstrumentationTestCase2 { + + + /* Folder data to read. This folder must exist on the account */ + private final String mRemoteFolderPath = "/folderToRead"; + + + private TestActivity mActivity; + + public ReadFolderTest() { + super(TestActivity.class); + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + } + + /** + * Test Read Folder + */ + public void testReadFolder() { + + RemoteOperationResult result = mActivity.readFile(mRemoteFolderPath); + assertTrue(result.getData().size() > 1); + assertTrue(result.getData().size() == 4); + assertTrue(result.isSuccess()); + } + +} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/RenameFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/RenameFileTest.java new file mode 100644 index 00000000..523f3d9b --- /dev/null +++ b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/RenameFileTest.java @@ -0,0 +1,177 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.test_project.test; + +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.test_project.TestActivity; + +import android.test.ActivityInstrumentationTestCase2; + +/** + * Class to test Rename File Operation + * @author masensio + * + */ + +public class RenameFileTest extends ActivityInstrumentationTestCase2 { + + /* Folder data to rename. This folder must exist on the account */ + private final String mOldFolderName = "folderToRename"; + private final String mOldFolderPath = "/folderToRename"; + private final String mNewFolderName = "renamedFolder"; + private final String mNewFolderPath = "/renamedFolder"; + + /* File data to rename. This file must exist on the account */ + private final String mOldFileName = "fileToRename.png"; + private final String mOldFilePath = "/fileToRename.png"; + private final String mNewFileName = "renamedFile"; + private final String mFileExtension = ".png"; + private final String mNewFilePath ="/renamedFile.png"; + + + private TestActivity mActivity; + + public RenameFileTest() { + super(TestActivity.class); + + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + } + + /** + * Test Rename Folder + */ + public void testRenameFolder() { + + RemoteOperationResult result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName, true); + assertTrue(result.isSuccess()); + } + + /** + * Test Rename Folder with forbidden characters : \ < > : " | ? * + */ + public void testRenameFolderForbiddenChars() { + + RemoteOperationResult result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + "\\", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + "<", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + ">", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + ":", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + "\"", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + "|", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + "?", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFolderName, mOldFolderPath, + mNewFolderName + "*", true); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + } + + /** + * Test Rename File + */ + public void testRenameFile() { + RemoteOperationResult result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + mFileExtension, false); + assertTrue(result.isSuccess()); + } + + + /** + * Test Rename Folder with forbidden characters: \ < > : " | ? * + */ + public void testRenameFileForbiddenChars() { + RemoteOperationResult result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + "\\" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + "<" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + ">" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + ":" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + "\"" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + "|" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + "?" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + result = mActivity.renameFile(mOldFileName, mOldFilePath, + mNewFileName + "*" + mFileExtension, false); + assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); + + } + + + /** + * Restore initial conditions + */ + public void testRestoreInitialConditions() { + RemoteOperationResult result = mActivity.renameFile(mNewFolderName, mNewFolderPath, mOldFolderName, true); + assertTrue(result.isSuccess()); + + result = mActivity.renameFile(mNewFileName + mFileExtension, mNewFilePath, mOldFileName, false); + assertTrue(result.isSuccess()); + } + +} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/UploadFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/UploadFileTest.java new file mode 100644 index 00000000..4c862556 --- /dev/null +++ b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/lib/test_project/test/UploadFileTest.java @@ -0,0 +1,168 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.test_project.test; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.text.SimpleDateFormat; +import java.util.Date; + +import android.content.res.AssetManager; +import android.os.Environment; +import android.test.ActivityInstrumentationTestCase2; +import android.util.Log; + +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.test_project.TestActivity; + +/** + * Class to test Update File Operation + * @author masensio + * + */ + +public class UploadFileTest extends ActivityInstrumentationTestCase2 { + + /* Files to upload. These files must exists on the device */ + private final String mFileToUpload = "fileToUpload.png"; + private final String mMimeType = "image/png"; + + private final String mFileToUploadWithChunks = "fileToUploadChunks.MP4"; + private final String mMimeTypeWithChunks = "video/mp4"; + + private final String mFileNotFound = "fileNotFound.png"; + + private final String mStoragePath = "/owncloud/tmp/uploadTest"; + private String mPath; + + private String mCurrentDate; + + private TestActivity mActivity; + + public UploadFileTest() { + super(TestActivity.class); + + } + + @Override + protected void setUp() throws Exception { + super.setUp(); + setActivityInitialTouchMode(false); + mActivity = getActivity(); + + SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); + mCurrentDate = sdf.format(new Date()); + + File sdCard = Environment.getExternalStorageDirectory(); + mPath = sdCard.getAbsolutePath() + "/" + mStoragePath + mCurrentDate; + + //mActivity.createFolder(mPath, true); + + copyAssets(); + } + + /** + * Copy Files to ulpload to SdCard + */ + private void copyAssets() { + AssetManager assetManager = getActivity().getAssets(); + String[] files = { mFileToUpload, mFileToUploadWithChunks }; + + // Folder with contents + File folder = new File(mPath); + folder.mkdirs(); + + + for(String filename : files) { + InputStream in = null; + OutputStream out = null; + try { + in = assetManager.open(filename); + File outFile = new File(folder, filename); + out = new FileOutputStream(outFile); + copyFile(in, out); + in.close(); + in = null; + out.flush(); + out.close(); + out = null; + } catch(IOException e) { + Log.e("tag", "Failed to copy asset file: " + filename, e); + } + } + } + + private void copyFile(InputStream in, OutputStream out) throws IOException { + byte[] buffer = new byte[1024]; + int read; + while((read = in.read(buffer)) != -1){ + out.write(buffer, 0, read); + } + } + + + /** + * Test Upload File without chunks + */ + public void testUploadFile() { + + String storagePath = mPath + "/" + mFileToUpload; + //String remotePath = "/uploadTest" + mCurrentDate + "/" + mFileToUpload; + String remotePath = "/" + mFileToUpload; + + RemoteOperationResult result = mActivity.uploadFile(storagePath, remotePath, mMimeType); + assertTrue(result.isSuccess()); + } + + /** + * Test Upload File with chunks + */ + public void testUploadFileWithChunks() { + + String storagePath = mPath + "/" + mFileToUploadWithChunks; + //String remotePath = "/uploadTest" + mCurrentDate + "/" +mFileToUploadWithChunks; + String remotePath = "/" + mFileToUploadWithChunks; + + RemoteOperationResult result = mActivity.uploadFile(storagePath, remotePath, mMimeTypeWithChunks); + assertTrue(result.isSuccess()); + } + + /** + * Test Upload Not Found File + */ + public void testUploadFileNotFound() { + + String storagePath = mPath + "/" + mFileNotFound; + //String remotePath = "/uploadTest" + mCurrentDate + "/" + mFileToUpload; + String remotePath = "/" + mFileNotFound; + + RemoteOperationResult result = mActivity.uploadFile(storagePath, remotePath, mMimeType); + assertFalse(result.isSuccess()); + } + +} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/CreateFolderTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/CreateFolderTest.java deleted file mode 100644 index 06608821..00000000 --- a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/CreateFolderTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -package com.owncloud.android.oc_framework_test_project.test; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework_test_project.TestActivity; - -import android.test.ActivityInstrumentationTestCase2; - -/** - * Class to test Create Folder Operation - * @author masensio - * - */ -public class CreateFolderTest extends ActivityInstrumentationTestCase2 { - - private TestActivity mActivity; - private String mCurrentDate; - - public CreateFolderTest() { - super(TestActivity.class); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); - mCurrentDate = sdf.format(new Date()); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - setActivityInitialTouchMode(false); - mActivity = getActivity(); - } - - /** - * Test Create Folder - */ - public void testCreateFolder() { - - String remotePath = "/testCreateFolder" + mCurrentDate; - boolean createFullPath = true; - - RemoteOperationResult result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.isSuccess() || result.getCode() == ResultCode.TIMEOUT); - - // Create Subfolder - remotePath = "/testCreateFolder" + mCurrentDate + "/" + "testCreateFolder" + mCurrentDate; - createFullPath = true; - - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.isSuccess() || result.getCode() == ResultCode.TIMEOUT); - } - - - /** - * Test to Create Folder with special characters: / \ < > : " | ? * - */ - public void testCreateFolderSpecialCharacters() { - boolean createFullPath = true; - - String remotePath = "/testSpecialCharacters_\\" + mCurrentDate; - RemoteOperationResult result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - remotePath = "/testSpecialCharacters_<" + mCurrentDate; - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - remotePath = "/testSpecialCharacters_>" + mCurrentDate; - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - remotePath = "/testSpecialCharacters_:" + mCurrentDate; - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - remotePath = "/testSpecialCharacters_\"" + mCurrentDate; - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - remotePath = "/testSpecialCharacters_|" + mCurrentDate; - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - remotePath = "/testSpecialCharacters_?" + mCurrentDate; - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - remotePath = "/testSpecialCharacters_*" + mCurrentDate; - result = mActivity.createFolder(remotePath, createFullPath); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - } - - -} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/DeleteFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/DeleteFileTest.java deleted file mode 100644 index b3b7c376..00000000 --- a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/DeleteFileTest.java +++ /dev/null @@ -1,87 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework_test_project.test; - -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework_test_project.TestActivity; - -import android.test.ActivityInstrumentationTestCase2; - -/** - * Class to test Delete a File Operation - * @author masensio - * - */ - -public class DeleteFileTest extends ActivityInstrumentationTestCase2 { - - /* Folder data to delete. */ - private final String mFolderPath = "/folderToDelete"; - - /* File to delete. */ - private final String mFilePath = "fileToDelete.png"; - - private TestActivity mActivity; - - public DeleteFileTest() { - super(TestActivity.class); - - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - setActivityInitialTouchMode(false); - mActivity = getActivity(); - } - - /** - * Test Remove Folder - */ - public void testRemoveFolder() { - - RemoteOperationResult result = mActivity.removeFile(mFolderPath); - assertTrue(result.isSuccess() || result.getCode() == ResultCode.FILE_NOT_FOUND); - } - - /** - * Test Remove File - */ - public void testRemoveFile() { - - RemoteOperationResult result = mActivity.removeFile(mFilePath); - assertTrue(result.isSuccess() || result.getCode() == ResultCode.FILE_NOT_FOUND); - } - - /** - * Restore initial conditions - */ - public void testRestoreInitialConditions() { - RemoteOperationResult result = mActivity.createFolder(mFolderPath, true); - assertTrue(result.isSuccess()); - - } -} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/DownloadFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/DownloadFileTest.java deleted file mode 100644 index 8c52eab7..00000000 --- a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/DownloadFileTest.java +++ /dev/null @@ -1,130 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework_test_project.test; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import com.owncloud.android.oc_framework.operations.RemoteFile; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework_test_project.TestActivity; - -import android.test.ActivityInstrumentationTestCase2; - -/** - * Class to test Download File Operation - * @author masensio - * - */ - -public class DownloadFileTest extends ActivityInstrumentationTestCase2 { - - - /* Files to download. These files must exist on the account */ - private final String mRemoteFilePng = "/fileToDownload.png"; - private final String mRemoteFileChunks = "/fileToDownload.mp4"; - private final String mRemoteFileSpecialChars = "/@file@download.png"; - private final String mRemoteFileSpecialCharsChunks = "/@file@download.mp4"; - private final String mRemoteFileNotFound = "/fileNotFound.png"; /* This file mustn't exist on the account */ - - private String mCurrentDate; - - - private TestActivity mActivity; - - public DownloadFileTest() { - super(TestActivity.class); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); - mCurrentDate = sdf.format(new Date()); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - setActivityInitialTouchMode(false); - mActivity = getActivity(); - } - - /** - * Test Download a File - */ - public void testDownloadFile() { - String temporalFolder = "/download" + mCurrentDate; - - RemoteFile remoteFile= new RemoteFile(mRemoteFilePng); - - RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); - assertTrue(result.isSuccess()); - } - - /** - * Test Download a File with chunks - */ - public void testDownloadFileChunks() { - String temporalFolder = "/download" + mCurrentDate; - - RemoteFile remoteFile= new RemoteFile(mRemoteFileChunks); - - RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); - assertTrue(result.isSuccess()); - } - - /** - * Test Download a File with special chars - */ - public void testDownloadFileSpecialChars() { - String temporalFolder = "/download" + mCurrentDate; - - RemoteFile remoteFile= new RemoteFile(mRemoteFileSpecialChars); - - RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); - assertTrue(result.isSuccess()); - } - - /** - * Test Download a File with special chars and chunks - */ - public void testDownloadFileSpecialCharsChunks() { - String temporalFolder = "/download" + mCurrentDate; - - RemoteFile remoteFile= new RemoteFile(mRemoteFileSpecialCharsChunks); - - RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); - assertTrue(result.isSuccess()); - } - - /** - * Test Download a Not Found File - */ - public void testDownloadFileNotFound() { - String temporalFolder = "/download" + mCurrentDate; - - RemoteFile remoteFile = new RemoteFile(mRemoteFileNotFound); - - RemoteOperationResult result = mActivity.downloadFile(remoteFile, temporalFolder); - assertFalse(result.isSuccess()); - } -} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/ReadFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/ReadFileTest.java deleted file mode 100644 index e6887ac5..00000000 --- a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/ReadFileTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -package com.owncloud.android.oc_framework_test_project.test; - -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework_test_project.TestActivity; - -import android.test.ActivityInstrumentationTestCase2; - -/** - * Class to test Read File Operation - * @author masensio - * - */ - -public class ReadFileTest extends ActivityInstrumentationTestCase2 { - - /* File data to read. This file must exist on the account */ - private final String mRemoteFolderPath = "/fileToRead.txt"; - - - private TestActivity mActivity; - - public ReadFileTest() { - super(TestActivity.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - setActivityInitialTouchMode(false); - mActivity = getActivity(); - } - - /** - * Test Read File - */ - public void testReadFile() { - - RemoteOperationResult result = mActivity.readFile(mRemoteFolderPath); - assertTrue(result.getData().size() == 1); - assertTrue(result.isSuccess()); - } - - -} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/ReadFolderTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/ReadFolderTest.java deleted file mode 100644 index 29aae10d..00000000 --- a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/ReadFolderTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework_test_project.test; - -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework_test_project.TestActivity; - -import android.test.ActivityInstrumentationTestCase2; - -/** - * Class to test Read Folder Operation - * @author masensio - * - */ - -public class ReadFolderTest extends ActivityInstrumentationTestCase2 { - - - /* Folder data to read. This folder must exist on the account */ - private final String mRemoteFolderPath = "/folderToRead"; - - - private TestActivity mActivity; - - public ReadFolderTest() { - super(TestActivity.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - setActivityInitialTouchMode(false); - mActivity = getActivity(); - } - - /** - * Test Read Folder - */ - public void testReadFolder() { - - RemoteOperationResult result = mActivity.readFile(mRemoteFolderPath); - assertTrue(result.getData().size() > 1); - assertTrue(result.getData().size() == 4); - assertTrue(result.isSuccess()); - } - -} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/RenameFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/RenameFileTest.java deleted file mode 100644 index 55637ec6..00000000 --- a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/RenameFileTest.java +++ /dev/null @@ -1,177 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework_test_project.test; - -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework_test_project.TestActivity; - -import android.test.ActivityInstrumentationTestCase2; - -/** - * Class to test Rename File Operation - * @author masensio - * - */ - -public class RenameFileTest extends ActivityInstrumentationTestCase2 { - - /* Folder data to rename. This folder must exist on the account */ - private final String mOldFolderName = "folderToRename"; - private final String mOldFolderPath = "/folderToRename"; - private final String mNewFolderName = "renamedFolder"; - private final String mNewFolderPath = "/renamedFolder"; - - /* File data to rename. This file must exist on the account */ - private final String mOldFileName = "fileToRename.png"; - private final String mOldFilePath = "/fileToRename.png"; - private final String mNewFileName = "renamedFile"; - private final String mFileExtension = ".png"; - private final String mNewFilePath ="/renamedFile.png"; - - - private TestActivity mActivity; - - public RenameFileTest() { - super(TestActivity.class); - - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - setActivityInitialTouchMode(false); - mActivity = getActivity(); - } - - /** - * Test Rename Folder - */ - public void testRenameFolder() { - - RemoteOperationResult result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName, true); - assertTrue(result.isSuccess()); - } - - /** - * Test Rename Folder with forbidden characters : \ < > : " | ? * - */ - public void testRenameFolderForbiddenChars() { - - RemoteOperationResult result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + "\\", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + "<", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + ">", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + ":", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + "\"", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + "|", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + "?", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFolderName, mOldFolderPath, - mNewFolderName + "*", true); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - } - - /** - * Test Rename File - */ - public void testRenameFile() { - RemoteOperationResult result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + mFileExtension, false); - assertTrue(result.isSuccess()); - } - - - /** - * Test Rename Folder with forbidden characters: \ < > : " | ? * - */ - public void testRenameFileForbiddenChars() { - RemoteOperationResult result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + "\\" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + "<" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + ">" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + ":" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + "\"" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + "|" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + "?" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - result = mActivity.renameFile(mOldFileName, mOldFilePath, - mNewFileName + "*" + mFileExtension, false); - assertTrue(result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME); - - } - - - /** - * Restore initial conditions - */ - public void testRestoreInitialConditions() { - RemoteOperationResult result = mActivity.renameFile(mNewFolderName, mNewFolderPath, mOldFolderName, true); - assertTrue(result.isSuccess()); - - result = mActivity.renameFile(mNewFileName + mFileExtension, mNewFilePath, mOldFileName, false); - assertTrue(result.isSuccess()); - } - -} diff --git a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/UploadFileTest.java b/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/UploadFileTest.java deleted file mode 100644 index 1406a580..00000000 --- a/oc_framework-test-project/oc_framework-test-test/src/com/owncloud/android/oc_framework_test_project/test/UploadFileTest.java +++ /dev/null @@ -1,168 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework_test_project.test; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.text.SimpleDateFormat; -import java.util.Date; - -import android.content.res.AssetManager; -import android.os.Environment; -import android.test.ActivityInstrumentationTestCase2; -import android.util.Log; - -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework_test_project.TestActivity; - -/** - * Class to test Update File Operation - * @author masensio - * - */ - -public class UploadFileTest extends ActivityInstrumentationTestCase2 { - - /* Files to upload. These files must exists on the device */ - private final String mFileToUpload = "fileToUpload.png"; - private final String mMimeType = "image/png"; - - private final String mFileToUploadWithChunks = "fileToUploadChunks.MP4"; - private final String mMimeTypeWithChunks = "video/mp4"; - - private final String mFileNotFound = "fileNotFound.png"; - - private final String mStoragePath = "/owncloud/tmp/uploadTest"; - private String mPath; - - private String mCurrentDate; - - private TestActivity mActivity; - - public UploadFileTest() { - super(TestActivity.class); - - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - setActivityInitialTouchMode(false); - mActivity = getActivity(); - - SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); - mCurrentDate = sdf.format(new Date()); - - File sdCard = Environment.getExternalStorageDirectory(); - mPath = sdCard.getAbsolutePath() + "/" + mStoragePath + mCurrentDate; - - //mActivity.createFolder(mPath, true); - - copyAssets(); - } - - /** - * Copy Files to ulpload to SdCard - */ - private void copyAssets() { - AssetManager assetManager = getActivity().getAssets(); - String[] files = { mFileToUpload, mFileToUploadWithChunks }; - - // Folder with contents - File folder = new File(mPath); - folder.mkdirs(); - - - for(String filename : files) { - InputStream in = null; - OutputStream out = null; - try { - in = assetManager.open(filename); - File outFile = new File(folder, filename); - out = new FileOutputStream(outFile); - copyFile(in, out); - in.close(); - in = null; - out.flush(); - out.close(); - out = null; - } catch(IOException e) { - Log.e("tag", "Failed to copy asset file: " + filename, e); - } - } - } - - private void copyFile(InputStream in, OutputStream out) throws IOException { - byte[] buffer = new byte[1024]; - int read; - while((read = in.read(buffer)) != -1){ - out.write(buffer, 0, read); - } - } - - - /** - * Test Upload File without chunks - */ - public void testUploadFile() { - - String storagePath = mPath + "/" + mFileToUpload; - //String remotePath = "/uploadTest" + mCurrentDate + "/" + mFileToUpload; - String remotePath = "/" + mFileToUpload; - - RemoteOperationResult result = mActivity.uploadFile(storagePath, remotePath, mMimeType); - assertTrue(result.isSuccess()); - } - - /** - * Test Upload File with chunks - */ - public void testUploadFileWithChunks() { - - String storagePath = mPath + "/" + mFileToUploadWithChunks; - //String remotePath = "/uploadTest" + mCurrentDate + "/" +mFileToUploadWithChunks; - String remotePath = "/" + mFileToUploadWithChunks; - - RemoteOperationResult result = mActivity.uploadFile(storagePath, remotePath, mMimeTypeWithChunks); - assertTrue(result.isSuccess()); - } - - /** - * Test Upload Not Found File - */ - public void testUploadFileNotFound() { - - String storagePath = mPath + "/" + mFileNotFound; - //String remotePath = "/uploadTest" + mCurrentDate + "/" + mFileToUpload; - String remotePath = "/" + mFileNotFound; - - RemoteOperationResult result = mActivity.uploadFile(storagePath, remotePath, mMimeType); - assertFalse(result.isSuccess()); - } - -} diff --git a/oc_framework-test-project/src/com/owncloud/android/lib/test_project/TestActivity.java b/oc_framework-test-project/src/com/owncloud/android/lib/test_project/TestActivity.java new file mode 100644 index 00000000..d6caf3c6 --- /dev/null +++ b/oc_framework-test-project/src/com/owncloud/android/lib/test_project/TestActivity.java @@ -0,0 +1,174 @@ +/* ownCloud Android client application + * Copyright (C) 2012-2013 ownCloud Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ + +package com.owncloud.android.lib.test_project; + +import java.io.File; + +import com.owncloud.android.lib.network.OwnCloudClientFactory; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteFile; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.remote.ChunkedUploadRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.CreateRemoteFolderOperation; +import com.owncloud.android.lib.operations.remote.DownloadRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.ReadRemoteFolderOperation; +import com.owncloud.android.lib.operations.remote.RemoveRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.RenameRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.UploadRemoteFileOperation; +import com.owncloud.android.lib.test_project.R; + +import android.net.Uri; +import android.os.Bundle; +import android.os.Environment; +import android.app.Activity; +import android.view.Menu; + +/** + * Activity to test OC framework + * @author masensio + * @author David A. Velasco + */ + +public class TestActivity extends Activity { + + // This account must exists on the simulator / device + private static final String mServerUri = "https://beta.owncloud.com/owncloud/remote.php/webdav"; + private static final String mUser = "testandroid"; + private static final String mPass = "testandroid"; + private static final boolean mChunked = true; + + //private Account mAccount = null; + private OwnCloudClient mClient; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_test); + Uri uri = Uri.parse(mServerUri); + mClient = OwnCloudClientFactory.createOwnCloudClient(uri ,getApplicationContext(), true); + mClient.setBasicCredentials(mUser, mPass); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.test, menu); + return true; + } + + /** + * Access to the library method to Create a Folder + * @param remotePath Full path to the new directory to create in the remote server. + * @param createFullPath 'True' means that all the ancestor folders should be created if don't exist yet. + * + * @return + */ + public RemoteOperationResult createFolder(String remotePath, boolean createFullPath) { + + CreateRemoteFolderOperation createOperation = new CreateRemoteFolderOperation(remotePath, createFullPath); + RemoteOperationResult result = createOperation.execute(mClient); + + return result; + } + + /** + * Access to the library method to Rename a File or Folder + * @param oldName Old name of the file. + * @param oldRemotePath Old remote path of the file. For folders it starts and ends by "/" + * @param newName New name to set as the name of file. + * @param isFolder 'true' for folder and 'false' for files + * + * @return + */ + + public RemoteOperationResult renameFile(String oldName, String oldRemotePath, String newName, boolean isFolder) { + + RenameRemoteFileOperation renameOperation = new RenameRemoteFileOperation(oldName, oldRemotePath, newName, isFolder); + RemoteOperationResult result = renameOperation.execute(mClient); + + return result; + } + + /** + * Access to the library method to Remove a File or Folder + * + * @param remotePath Remote path of the file or folder in the server. + * @return + */ + public RemoteOperationResult removeFile(String remotePath) { + + RemoveRemoteFileOperation removeOperation = new RemoveRemoteFileOperation(remotePath); + RemoteOperationResult result = removeOperation.execute(mClient); + + return result; + } + + /** + * Access to the library method to Read a Folder (PROPFIND DEPTH 1) + * @param remotePath + * + * @return + */ + public RemoteOperationResult readFile(String remotePath) { + + ReadRemoteFolderOperation readOperation= new ReadRemoteFolderOperation(remotePath); + RemoteOperationResult result = readOperation.execute(mClient); + + return result; + } + + /** + * Access to the library method to Download a File + * @param remotePath + * + * @return + */ + public RemoteOperationResult downloadFile(RemoteFile remoteFile, String temporalFolder) { + // Create folder + String path = "/owncloud/tmp/" + temporalFolder; + File sdCard = Environment.getExternalStorageDirectory(); + File folder = new File(sdCard.getAbsolutePath() + "/" + path); + folder.mkdirs(); + + DownloadRemoteFileOperation downloadOperation = new DownloadRemoteFileOperation(remoteFile.getRemotePath(), folder.getAbsolutePath()); + RemoteOperationResult result = downloadOperation.execute(mClient); + + return result; + } + + /** Access to the library method to Upload a File + * @param storagePath + * @param remotePath + * @param mimeType + * + * @return + */ + public RemoteOperationResult uploadFile(String storagePath, String remotePath, String mimeType) { + + UploadRemoteFileOperation uploadOperation; + if ( mChunked && (new File(storagePath)).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) { + uploadOperation = new ChunkedUploadRemoteFileOperation(storagePath, remotePath, mimeType); + } else { + uploadOperation = new UploadRemoteFileOperation(storagePath, remotePath, mimeType); + } + + RemoteOperationResult result = uploadOperation.execute(mClient); + + return result; + } +} diff --git a/oc_framework-test-project/src/com/owncloud/android/oc_framework_test_project/TestActivity.java b/oc_framework-test-project/src/com/owncloud/android/oc_framework_test_project/TestActivity.java deleted file mode 100644 index 8270fad8..00000000 --- a/oc_framework-test-project/src/com/owncloud/android/oc_framework_test_project/TestActivity.java +++ /dev/null @@ -1,173 +0,0 @@ -/* ownCloud Android client application - * Copyright (C) 2012-2013 ownCloud Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ - -package com.owncloud.android.oc_framework_test_project; - -import java.io.File; - -import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteFile; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.remote.ChunkedUploadRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.CreateRemoteFolderOperation; -import com.owncloud.android.oc_framework.operations.remote.DownloadRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.ReadRemoteFolderOperation; -import com.owncloud.android.oc_framework.operations.remote.RemoveRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.RenameRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.UploadRemoteFileOperation; - -import android.net.Uri; -import android.os.Bundle; -import android.os.Environment; -import android.app.Activity; -import android.view.Menu; - -/** - * Activity to test OC framework - * @author masensio - * @author David A. Velasco - */ - -public class TestActivity extends Activity { - - // This account must exists on the simulator / device - private static final String mServerUri = "https://beta.owncloud.com/owncloud/remote.php/webdav"; - private static final String mUser = "testandroid"; - private static final String mPass = "testandroid"; - private static final boolean mChunked = true; - - //private Account mAccount = null; - private WebdavClient mClient; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_test); - Uri uri = Uri.parse(mServerUri); - mClient = OwnCloudClientFactory.createOwnCloudClient(uri ,getApplicationContext(), true); - mClient.setBasicCredentials(mUser, mPass); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - getMenuInflater().inflate(R.menu.test, menu); - return true; - } - - /** - * Access to the library method to Create a Folder - * @param remotePath Full path to the new directory to create in the remote server. - * @param createFullPath 'True' means that all the ancestor folders should be created if don't exist yet. - * - * @return - */ - public RemoteOperationResult createFolder(String remotePath, boolean createFullPath) { - - CreateRemoteFolderOperation createOperation = new CreateRemoteFolderOperation(remotePath, createFullPath); - RemoteOperationResult result = createOperation.execute(mClient); - - return result; - } - - /** - * Access to the library method to Rename a File or Folder - * @param oldName Old name of the file. - * @param oldRemotePath Old remote path of the file. For folders it starts and ends by "/" - * @param newName New name to set as the name of file. - * @param isFolder 'true' for folder and 'false' for files - * - * @return - */ - - public RemoteOperationResult renameFile(String oldName, String oldRemotePath, String newName, boolean isFolder) { - - RenameRemoteFileOperation renameOperation = new RenameRemoteFileOperation(oldName, oldRemotePath, newName, isFolder); - RemoteOperationResult result = renameOperation.execute(mClient); - - return result; - } - - /** - * Access to the library method to Remove a File or Folder - * - * @param remotePath Remote path of the file or folder in the server. - * @return - */ - public RemoteOperationResult removeFile(String remotePath) { - - RemoveRemoteFileOperation removeOperation = new RemoveRemoteFileOperation(remotePath); - RemoteOperationResult result = removeOperation.execute(mClient); - - return result; - } - - /** - * Access to the library method to Read a Folder (PROPFIND DEPTH 1) - * @param remotePath - * - * @return - */ - public RemoteOperationResult readFile(String remotePath) { - - ReadRemoteFolderOperation readOperation= new ReadRemoteFolderOperation(remotePath); - RemoteOperationResult result = readOperation.execute(mClient); - - return result; - } - - /** - * Access to the library method to Download a File - * @param remotePath - * - * @return - */ - public RemoteOperationResult downloadFile(RemoteFile remoteFile, String temporalFolder) { - // Create folder - String path = "/owncloud/tmp/" + temporalFolder; - File sdCard = Environment.getExternalStorageDirectory(); - File folder = new File(sdCard.getAbsolutePath() + "/" + path); - folder.mkdirs(); - - DownloadRemoteFileOperation downloadOperation = new DownloadRemoteFileOperation(remoteFile.getRemotePath(), folder.getAbsolutePath()); - RemoteOperationResult result = downloadOperation.execute(mClient); - - return result; - } - - /** Access to the library method to Upload a File - * @param storagePath - * @param remotePath - * @param mimeType - * - * @return - */ - public RemoteOperationResult uploadFile(String storagePath, String remotePath, String mimeType) { - - UploadRemoteFileOperation uploadOperation; - if ( mChunked && (new File(storagePath)).length() > ChunkedUploadRemoteFileOperation.CHUNK_SIZE ) { - uploadOperation = new ChunkedUploadRemoteFileOperation(storagePath, remotePath, mimeType); - } else { - uploadOperation = new UploadRemoteFileOperation(storagePath, remotePath, mimeType); - } - - RemoteOperationResult result = uploadOperation.execute(mClient); - - return result; - } -} diff --git a/oc_framework/.project b/oc_framework/.project index 18812a0d..4b5c2951 100644 --- a/oc_framework/.project +++ b/oc_framework/.project @@ -1,6 +1,6 @@ - oc_framework + ownCloud Android Library diff --git a/oc_framework/AndroidManifest.xml b/oc_framework/AndroidManifest.xml index 7c391cd6..30dda12f 100644 --- a/oc_framework/AndroidManifest.xml +++ b/oc_framework/AndroidManifest.xml @@ -24,7 +24,7 @@ --> diff --git a/oc_framework/sample_client/AndroidManifest.xml b/oc_framework/sample_client/AndroidManifest.xml index 4e1ff7a0..6b406176 100644 --- a/oc_framework/sample_client/AndroidManifest.xml +++ b/oc_framework/sample_client/AndroidManifest.xml @@ -24,7 +24,7 @@ --> diff --git a/oc_framework/sample_client/src/com/owncloud/android/lib/sampleclient/FilesArrayAdapter.java b/oc_framework/sample_client/src/com/owncloud/android/lib/sampleclient/FilesArrayAdapter.java new file mode 100644 index 00000000..f7f4bda7 --- /dev/null +++ b/oc_framework/sample_client/src/com/owncloud/android/lib/sampleclient/FilesArrayAdapter.java @@ -0,0 +1,46 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +package com.owncloud.android.lib.sampleclient; + +import android.content.Context; +import android.view.View; +import android.view.ViewGroup; +import android.widget.ArrayAdapter; +import android.widget.TextView; + +import com.owncloud.android.lib.operations.common.RemoteFile; + +public class FilesArrayAdapter extends ArrayAdapter { + + public FilesArrayAdapter(Context context, int resource) { + super(context, resource); + } + + public View getView(int position, View convertView, ViewGroup parent) { + TextView textView = (TextView)super.getView(position, convertView, parent); + textView.setText(getItem(position).getRemotePath()); + return textView; + } +} + diff --git a/oc_framework/sample_client/src/com/owncloud/android/lib/sampleclient/MainActivity.java b/oc_framework/sample_client/src/com/owncloud/android/lib/sampleclient/MainActivity.java new file mode 100644 index 00000000..0ae446b6 --- /dev/null +++ b/oc_framework/sample_client/src/com/owncloud/android/lib/sampleclient/MainActivity.java @@ -0,0 +1,267 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.sampleclient; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.Iterator; +import java.util.List; + +import com.owncloud.android.lib.accounts.AccountUtils; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.network.OwnCloudClientFactory; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.RemoteFile; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.remote.DownloadRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.ReadRemoteFolderOperation; +import com.owncloud.android.lib.operations.remote.RemoveRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.UploadRemoteFileOperation; +import com.owncloud.android.lib.utils.FileUtils; + +import android.app.Activity; +import android.content.res.AssetManager; +import android.graphics.drawable.BitmapDrawable; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.util.Log; +import android.view.View; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; + +public class MainActivity extends Activity implements OnRemoteOperationListener, OnDatatransferProgressListener { + + private static String LOG_TAG = MainActivity.class.getCanonicalName(); + + private Handler mHandler; + + private OwnCloudClient mClient; + + private FilesArrayAdapter mFilesAdapter; + + private View mFrame; + + /** Called when the activity is first created. */ + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.main); + + mHandler = new Handler(); + + Uri serverUri = Uri.parse(getString(R.string.server_base_url) + AccountUtils.WEBDAV_PATH_4_0); + mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, this, true); + mClient.setBasicCredentials(getString(R.string.username), getString(R.string.password)); + + mFilesAdapter = new FilesArrayAdapter(this, R.layout.file_in_list); + ((ListView)findViewById(R.id.list_view)).setAdapter(mFilesAdapter); + + // TODO move to background thread or task + AssetManager assets = getAssets(); + try { + String sampleFileName = getString(R.string.sample_file_name); + File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); + upFolder.mkdir(); + File upFile = new File(upFolder, sampleFileName); + FileOutputStream fos = new FileOutputStream(upFile); + InputStream is = assets.open(sampleFileName); + int count = 0; + byte[] buffer = new byte[1024]; + while ((count = is.read(buffer, 0, buffer.length)) >= 0) { + fos.write(buffer, 0, count); + } + is.close(); + fos.close(); + } catch (IOException e) { + Toast.makeText(this, R.string.error_copying_sample_file, Toast.LENGTH_SHORT).show(); + Log.e(LOG_TAG, getString(R.string.error_copying_sample_file), e); + } + + mFrame = findViewById(R.id.frame); + } + + + @Override + public void onDestroy() { + File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); + File upFile = upFolder.listFiles()[0]; + upFile.delete(); + upFolder.delete(); + super.onDestroy(); + } + + + public void onClickHandler(View button) { + switch (button.getId()) { + case R.id.button_refresh: + startRefresh(); + break; + case R.id.button_upload: + startUpload(); + break; + case R.id.button_delete_remote: + startRemoteDeletion(); + break; + case R.id.button_download: + startDownload(); + break; + case R.id.button_delete_local: + startLocalDeletion(); + break; + default: + Toast.makeText(this, R.string.youre_doing_it_wrong, Toast.LENGTH_SHORT).show(); + } + } + + private void startRefresh() { + ReadRemoteFolderOperation refreshOperation = new ReadRemoteFolderOperation(FileUtils.PATH_SEPARATOR); + refreshOperation.execute(mClient, this, mHandler); + } + + private void startUpload() { + File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); + File fileToUpload = upFolder.listFiles()[0]; + String remotePath = FileUtils.PATH_SEPARATOR + fileToUpload.getName(); + String mimeType = getString(R.string.sample_file_mimetype); + UploadRemoteFileOperation uploadOperation = new UploadRemoteFileOperation(fileToUpload.getAbsolutePath(), remotePath, mimeType); + uploadOperation.addDatatransferProgressListener(this); + uploadOperation.execute(mClient, this, mHandler); + } + + private void startRemoteDeletion() { + File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); + File fileToUpload = upFolder.listFiles()[0]; + String remotePath = FileUtils.PATH_SEPARATOR + fileToUpload.getName(); + RemoveRemoteFileOperation removeOperation = new RemoveRemoteFileOperation(remotePath); + removeOperation.execute(mClient, this, mHandler); + } + + private void startDownload() { + File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path)); + downFolder.mkdir(); + File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); + File fileToUpload = upFolder.listFiles()[0]; + String remotePath = FileUtils.PATH_SEPARATOR + fileToUpload.getName(); + DownloadRemoteFileOperation downloadOperation = new DownloadRemoteFileOperation(remotePath, downFolder.getAbsolutePath()); + downloadOperation.addDatatransferProgressListener(this); + downloadOperation.execute(mClient, this, mHandler); + } + + @SuppressWarnings("deprecation") + private void startLocalDeletion() { + File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path)); + File downloadedFile = downFolder.listFiles()[0]; + if (!downloadedFile.delete() && downloadedFile.exists()) { + Toast.makeText(this, R.string.error_deleting_local_file, Toast.LENGTH_SHORT).show(); + } else { + ((TextView) findViewById(R.id.download_progress)).setText("0%"); + findViewById(R.id.frame).setBackgroundDrawable(null); + } + } + + @Override + public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) { + if (!result.isSuccess()) { + Toast.makeText(this, R.string.todo_operation_finished_in_fail, Toast.LENGTH_SHORT).show(); + Log.e(LOG_TAG, result.getLogMessage(), result.getException()); + + } else if (operation instanceof ReadRemoteFolderOperation) { + onSuccessfulRefresh((ReadRemoteFolderOperation)operation, result); + + } else if (operation instanceof UploadRemoteFileOperation ) { + onSuccessfulUpload((UploadRemoteFileOperation)operation, result); + + } else if (operation instanceof RemoveRemoteFileOperation ) { + onSuccessfulRemoteDeletion((RemoveRemoteFileOperation)operation, result); + + } else if (operation instanceof DownloadRemoteFileOperation ) { + onSuccessfulDownload((DownloadRemoteFileOperation)operation, result); + + } else { + Toast.makeText(this, R.string.todo_operation_finished_in_success, Toast.LENGTH_SHORT).show(); + } + } + + private void onSuccessfulRefresh(ReadRemoteFolderOperation operation, RemoteOperationResult result) { + mFilesAdapter.clear(); + List files = result.getData(); + if (files != null) { + Iterator it = files.iterator(); + while (it.hasNext()) { + mFilesAdapter.add(it.next()); + } + mFilesAdapter.remove(mFilesAdapter.getItem(0)); + } + mFilesAdapter.notifyDataSetChanged(); + } + + private void onSuccessfulUpload(UploadRemoteFileOperation operation, RemoteOperationResult result) { + startRefresh(); + } + + private void onSuccessfulRemoteDeletion(RemoveRemoteFileOperation operation, RemoteOperationResult result) { + startRefresh(); + TextView progressView = (TextView) findViewById(R.id.upload_progress); + if (progressView != null) { + progressView.setText("0%"); + } + } + + @SuppressWarnings("deprecation") + private void onSuccessfulDownload(DownloadRemoteFileOperation operation, RemoteOperationResult result) { + File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path)); + File downloadedFile = downFolder.listFiles()[0]; + BitmapDrawable bDraw = new BitmapDrawable(getResources(), downloadedFile.getAbsolutePath()); + mFrame.setBackgroundDrawable(bDraw); + } + + @Override + public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) { + final long percentage = (totalToTransfer > 0 ? totalTransferredSoFar * 100 / totalToTransfer : 0); + final boolean upload = fileName.contains(getString(R.string.upload_folder_path)); + Log.d(LOG_TAG, "progressRate " + percentage); + mHandler.post(new Runnable() { + @Override + public void run() { + TextView progressView = null; + if (upload) { + progressView = (TextView) findViewById(R.id.upload_progress); + } else { + progressView = (TextView) findViewById(R.id.download_progress); + } + if (progressView != null) { + progressView.setText(Long.toString(percentage) + "%"); + } + } + }); + } + +} diff --git a/oc_framework/sample_client/src/com/owncloud/android/oc_framework/sampleclient/FilesArrayAdapter.java b/oc_framework/sample_client/src/com/owncloud/android/oc_framework/sampleclient/FilesArrayAdapter.java deleted file mode 100644 index 0020c726..00000000 --- a/oc_framework/sample_client/src/com/owncloud/android/oc_framework/sampleclient/FilesArrayAdapter.java +++ /dev/null @@ -1,46 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -package com.owncloud.android.oc_framework.sampleclient; - -import android.content.Context; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ArrayAdapter; -import android.widget.TextView; - -import com.owncloud.android.oc_framework.operations.RemoteFile; - -public class FilesArrayAdapter extends ArrayAdapter { - - public FilesArrayAdapter(Context context, int resource) { - super(context, resource); - } - - public View getView(int position, View convertView, ViewGroup parent) { - TextView textView = (TextView)super.getView(position, convertView, parent); - textView.setText(getItem(position).getRemotePath()); - return textView; - } -} - diff --git a/oc_framework/sample_client/src/com/owncloud/android/oc_framework/sampleclient/MainActivity.java b/oc_framework/sample_client/src/com/owncloud/android/oc_framework/sampleclient/MainActivity.java deleted file mode 100644 index 79d273a0..00000000 --- a/oc_framework/sample_client/src/com/owncloud/android/oc_framework/sampleclient/MainActivity.java +++ /dev/null @@ -1,267 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.sampleclient; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.Iterator; -import java.util.List; - -import com.owncloud.android.oc_framework.accounts.AccountUtils; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; -import com.owncloud.android.oc_framework.operations.RemoteFile; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.remote.DownloadRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.ReadRemoteFolderOperation; -import com.owncloud.android.oc_framework.operations.remote.RemoveRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.UploadRemoteFileOperation; -import com.owncloud.android.oc_framework.utils.FileUtils; - -import android.app.Activity; -import android.content.res.AssetManager; -import android.graphics.drawable.BitmapDrawable; -import android.net.Uri; -import android.os.Bundle; -import android.os.Handler; -import android.util.Log; -import android.view.View; -import android.widget.ListView; -import android.widget.TextView; -import android.widget.Toast; - -public class MainActivity extends Activity implements OnRemoteOperationListener, OnDatatransferProgressListener { - - private static String LOG_TAG = MainActivity.class.getCanonicalName(); - - private Handler mHandler; - - private WebdavClient mClient; - - private FilesArrayAdapter mFilesAdapter; - - private View mFrame; - - /** Called when the activity is first created. */ - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.main); - - mHandler = new Handler(); - - Uri serverUri = Uri.parse(getString(R.string.server_base_url) + AccountUtils.WEBDAV_PATH_4_0); - mClient = OwnCloudClientFactory.createOwnCloudClient(serverUri, this, true); - mClient.setBasicCredentials(getString(R.string.username), getString(R.string.password)); - - mFilesAdapter = new FilesArrayAdapter(this, R.layout.file_in_list); - ((ListView)findViewById(R.id.list_view)).setAdapter(mFilesAdapter); - - // TODO move to background thread or task - AssetManager assets = getAssets(); - try { - String sampleFileName = getString(R.string.sample_file_name); - File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); - upFolder.mkdir(); - File upFile = new File(upFolder, sampleFileName); - FileOutputStream fos = new FileOutputStream(upFile); - InputStream is = assets.open(sampleFileName); - int count = 0; - byte[] buffer = new byte[1024]; - while ((count = is.read(buffer, 0, buffer.length)) >= 0) { - fos.write(buffer, 0, count); - } - is.close(); - fos.close(); - } catch (IOException e) { - Toast.makeText(this, R.string.error_copying_sample_file, Toast.LENGTH_SHORT).show(); - Log.e(LOG_TAG, getString(R.string.error_copying_sample_file), e); - } - - mFrame = findViewById(R.id.frame); - } - - - @Override - public void onDestroy() { - File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); - File upFile = upFolder.listFiles()[0]; - upFile.delete(); - upFolder.delete(); - super.onDestroy(); - } - - - public void onClickHandler(View button) { - switch (button.getId()) { - case R.id.button_refresh: - startRefresh(); - break; - case R.id.button_upload: - startUpload(); - break; - case R.id.button_delete_remote: - startRemoteDeletion(); - break; - case R.id.button_download: - startDownload(); - break; - case R.id.button_delete_local: - startLocalDeletion(); - break; - default: - Toast.makeText(this, R.string.youre_doing_it_wrong, Toast.LENGTH_SHORT).show(); - } - } - - private void startRefresh() { - ReadRemoteFolderOperation refreshOperation = new ReadRemoteFolderOperation(FileUtils.PATH_SEPARATOR); - refreshOperation.execute(mClient, this, mHandler); - } - - private void startUpload() { - File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); - File fileToUpload = upFolder.listFiles()[0]; - String remotePath = FileUtils.PATH_SEPARATOR + fileToUpload.getName(); - String mimeType = getString(R.string.sample_file_mimetype); - UploadRemoteFileOperation uploadOperation = new UploadRemoteFileOperation(fileToUpload.getAbsolutePath(), remotePath, mimeType); - uploadOperation.addDatatransferProgressListener(this); - uploadOperation.execute(mClient, this, mHandler); - } - - private void startRemoteDeletion() { - File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); - File fileToUpload = upFolder.listFiles()[0]; - String remotePath = FileUtils.PATH_SEPARATOR + fileToUpload.getName(); - RemoveRemoteFileOperation removeOperation = new RemoveRemoteFileOperation(remotePath); - removeOperation.execute(mClient, this, mHandler); - } - - private void startDownload() { - File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path)); - downFolder.mkdir(); - File upFolder = new File(getCacheDir(), getString(R.string.upload_folder_path)); - File fileToUpload = upFolder.listFiles()[0]; - String remotePath = FileUtils.PATH_SEPARATOR + fileToUpload.getName(); - DownloadRemoteFileOperation downloadOperation = new DownloadRemoteFileOperation(remotePath, downFolder.getAbsolutePath()); - downloadOperation.addDatatransferProgressListener(this); - downloadOperation.execute(mClient, this, mHandler); - } - - @SuppressWarnings("deprecation") - private void startLocalDeletion() { - File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path)); - File downloadedFile = downFolder.listFiles()[0]; - if (!downloadedFile.delete() && downloadedFile.exists()) { - Toast.makeText(this, R.string.error_deleting_local_file, Toast.LENGTH_SHORT).show(); - } else { - ((TextView) findViewById(R.id.download_progress)).setText("0%"); - findViewById(R.id.frame).setBackgroundDrawable(null); - } - } - - @Override - public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) { - if (!result.isSuccess()) { - Toast.makeText(this, R.string.todo_operation_finished_in_fail, Toast.LENGTH_SHORT).show(); - Log.e(LOG_TAG, result.getLogMessage(), result.getException()); - - } else if (operation instanceof ReadRemoteFolderOperation) { - onSuccessfulRefresh((ReadRemoteFolderOperation)operation, result); - - } else if (operation instanceof UploadRemoteFileOperation ) { - onSuccessfulUpload((UploadRemoteFileOperation)operation, result); - - } else if (operation instanceof RemoveRemoteFileOperation ) { - onSuccessfulRemoteDeletion((RemoveRemoteFileOperation)operation, result); - - } else if (operation instanceof DownloadRemoteFileOperation ) { - onSuccessfulDownload((DownloadRemoteFileOperation)operation, result); - - } else { - Toast.makeText(this, R.string.todo_operation_finished_in_success, Toast.LENGTH_SHORT).show(); - } - } - - private void onSuccessfulRefresh(ReadRemoteFolderOperation operation, RemoteOperationResult result) { - mFilesAdapter.clear(); - List files = result.getData(); - if (files != null) { - Iterator it = files.iterator(); - while (it.hasNext()) { - mFilesAdapter.add(it.next()); - } - mFilesAdapter.remove(mFilesAdapter.getItem(0)); - } - mFilesAdapter.notifyDataSetChanged(); - } - - private void onSuccessfulUpload(UploadRemoteFileOperation operation, RemoteOperationResult result) { - startRefresh(); - } - - private void onSuccessfulRemoteDeletion(RemoveRemoteFileOperation operation, RemoteOperationResult result) { - startRefresh(); - TextView progressView = (TextView) findViewById(R.id.upload_progress); - if (progressView != null) { - progressView.setText("0%"); - } - } - - @SuppressWarnings("deprecation") - private void onSuccessfulDownload(DownloadRemoteFileOperation operation, RemoteOperationResult result) { - File downFolder = new File(getCacheDir(), getString(R.string.download_folder_path)); - File downloadedFile = downFolder.listFiles()[0]; - BitmapDrawable bDraw = new BitmapDrawable(getResources(), downloadedFile.getAbsolutePath()); - mFrame.setBackgroundDrawable(bDraw); - } - - @Override - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) { - final long percentage = (totalToTransfer > 0 ? totalTransferredSoFar * 100 / totalToTransfer : 0); - final boolean upload = fileName.contains(getString(R.string.upload_folder_path)); - Log.d(LOG_TAG, "progressRate " + percentage); - mHandler.post(new Runnable() { - @Override - public void run() { - TextView progressView = null; - if (upload) { - progressView = (TextView) findViewById(R.id.upload_progress); - } else { - progressView = (TextView) findViewById(R.id.download_progress); - } - if (progressView != null) { - progressView.setText(Long.toString(percentage) + "%"); - } - } - }); - } - -} diff --git a/oc_framework/src/com/owncloud/android/lib/accounts/AccountTypeUtils.java b/oc_framework/src/com/owncloud/android/lib/accounts/AccountTypeUtils.java new file mode 100644 index 00000000..b4ed3308 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/accounts/AccountTypeUtils.java @@ -0,0 +1,50 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.accounts; + +/** + * @author masensio + * @author David A. Velasco + */ +public class AccountTypeUtils { + + public static String getAuthTokenTypePass(String accountType) { + return accountType + ".password"; + } + + public static String getAuthTokenTypeAccessToken(String accountType) { + return accountType + ".oauth2.access_token"; + } + + public static String getAuthTokenTypeRefreshToken(String accountType) { + return accountType + ".oauth2.refresh_token"; + } + + public static String getAuthTokenTypeSamlSessionCookie(String accountType) { + return accountType + ".saml.web_sso.session_cookie"; + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/accounts/AccountUtils.java b/oc_framework/src/com/owncloud/android/lib/accounts/AccountUtils.java new file mode 100644 index 00000000..79983814 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/accounts/AccountUtils.java @@ -0,0 +1,112 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.accounts; + +import com.owncloud.android.lib.utils.OwnCloudVersion; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountsException; +import android.content.Context; + +public class AccountUtils { + public static final String WEBDAV_PATH_1_2 = "/webdav/owncloud.php"; + public static final String WEBDAV_PATH_2_0 = "/files/webdav.php"; + public static final String WEBDAV_PATH_4_0 = "/remote.php/webdav"; + private static final String ODAV_PATH = "/remote.php/odav"; + private static final String SAML_SSO_PATH = "/remote.php/webdav"; + public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php"; + public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php"; + public static final String STATUS_PATH = "/status.php"; + + /** + * Returns the proper URL path to access the WebDAV interface of an ownCloud server, + * according to its version and the authorization method used. + * + * @param version Version of ownCloud server. + * @param supportsOAuth If true, access with OAuth 2 authorization is considered. + * @param supportsSamlSso If true, and supportsOAuth is false, access with SAML-based single-sign-on is considered. + * @return WebDAV path for given OC version, null if OC version unknown + */ + public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth, boolean supportsSamlSso) { + if (version != null) { + if (supportsOAuth) { + return ODAV_PATH; + } + if (supportsSamlSso) { + return SAML_SSO_PATH; + } + if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0) + return WEBDAV_PATH_4_0; + if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0 + || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0) + return WEBDAV_PATH_2_0; + if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0) + return WEBDAV_PATH_1_2; + } + return null; + } + + /** + * Constructs full url to host and webdav resource basing on host version + * @param context + * @param account + * @return url or null on failure + * @throws AccountNotFoundException When 'account' is unknown for the AccountManager + */ + public static String constructFullURLForAccount(Context context, Account account) throws AccountNotFoundException { + AccountManager ama = AccountManager.get(context); + String baseurl = ama.getUserData(account, OwnCloudAccount.Constants.KEY_OC_BASE_URL); + String strver = ama.getUserData(account, OwnCloudAccount.Constants.KEY_OC_VERSION); + boolean supportsOAuth = (ama.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_OAUTH2) != null); + boolean supportsSamlSso = (ama.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null); + OwnCloudVersion ver = new OwnCloudVersion(strver); + String webdavpath = getWebdavPath(ver, supportsOAuth, supportsSamlSso); + + if (baseurl == null || webdavpath == null) + throw new AccountNotFoundException(account, "Account not found", null); + + return baseurl + webdavpath; + } + + + public static class AccountNotFoundException extends AccountsException { + + /** Generated - should be refreshed every time the class changes!! */ + private static final long serialVersionUID = -1684392454798508693L; + + private Account mFailedAccount; + + public AccountNotFoundException(Account failedAccount, String message, Throwable cause) { + super(message, cause); + mFailedAccount = failedAccount; + } + + public Account getFailedAccount() { + return mFailedAccount; + } + } +} diff --git a/oc_framework/src/com/owncloud/android/lib/accounts/OwnCloudAccount.java b/oc_framework/src/com/owncloud/android/lib/accounts/OwnCloudAccount.java new file mode 100644 index 00000000..9d0de82c --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/accounts/OwnCloudAccount.java @@ -0,0 +1,112 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.accounts; + +import android.accounts.Account; +import android.os.Parcel; +import android.os.Parcelable; + +/** + * Account with extra information specific for ownCloud accounts. + * + * TODO integrate in the main app + * + * @author David A. Velasco + */ +public class OwnCloudAccount extends Account { + + public static class Constants { + /** + * Value under this key should handle path to webdav php script. Will be + * removed and usage should be replaced by combining + * {@link com.owncloud.android.authentication.AuthenticatorActivity.KEY_OC_BASE_URL} and + * {@link com.owncloud.android.lib.utils.utils.OwnCloudVersion} + * + * @deprecated + */ + public static final String KEY_OC_URL = "oc_url"; + /** + * Version should be 3 numbers separated by dot so it can be parsed by + * {@link com.owncloud.android.lib.utils.utils.OwnCloudVersion} + */ + public static final String KEY_OC_VERSION = "oc_version"; + /** + * Base url should point to owncloud installation without trailing / ie: + * http://server/path or https://owncloud.server + */ + public static final String KEY_OC_BASE_URL = "oc_base_url"; + /** + * Flag signaling if the ownCloud server can be accessed with OAuth2 access tokens. + */ + public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2"; + /** + * Flag signaling if the ownCloud server can be accessed with session cookies from SAML-based web single-sign-on. + */ + public static final String KEY_SUPPORTS_SAML_WEB_SSO = "oc_supports_saml_web_sso"; + } + + private String mAuthTokenType; + + public OwnCloudAccount(String name, String type, String authTokenType) { + super(name, type); + // TODO validate authTokentype as supported + mAuthTokenType = authTokenType; + } + + /** + * Reconstruct from parcel + * + * @param source The source parcel + */ + public OwnCloudAccount(Parcel source) { + super(source); + mAuthTokenType = source.readString(); + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + super.writeToParcel(dest, flags); + dest.writeString(mAuthTokenType); + } + + + public String getAuthTokenType() { + return mAuthTokenType; + } + + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public OwnCloudAccount createFromParcel(Parcel source) { + return new OwnCloudAccount(source); + } + + @Override + public OwnCloudAccount [] newArray(int size) { + return new OwnCloudAccount[size]; + } + }; + +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/AdvancedSslSocketFactory.java b/oc_framework/src/com/owncloud/android/lib/network/AdvancedSslSocketFactory.java new file mode 100644 index 00000000..72b78b16 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/AdvancedSslSocketFactory.java @@ -0,0 +1,296 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.net.UnknownHostException; +//import java.security.Provider; +import java.security.cert.X509Certificate; +//import java.util.Enumeration; + +import javax.net.SocketFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLHandshakeException; +//import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocket; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.params.HttpConnectionParams; +import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; +import org.apache.http.conn.ssl.X509HostnameVerifier; + +//import android.os.Build; +import android.util.Log; + + + +/** + * AdvancedSSLProtocolSocketFactory allows to create SSL {@link Socket}s with + * a custom SSLContext and an optional Hostname Verifier. + * + * @author David A. Velasco + */ + +public class AdvancedSslSocketFactory implements ProtocolSocketFactory { + + private static final String TAG = AdvancedSslSocketFactory.class.getSimpleName(); + + private SSLContext mSslContext = null; + private AdvancedX509TrustManager mTrustManager = null; + private X509HostnameVerifier mHostnameVerifier = null; + + public SSLContext getSslContext() { + return mSslContext; + } + + /** + * Constructor for AdvancedSSLProtocolSocketFactory. + */ + public AdvancedSslSocketFactory(SSLContext sslContext, AdvancedX509TrustManager trustManager, X509HostnameVerifier hostnameVerifier) { + if (sslContext == null) + throw new IllegalArgumentException("AdvancedSslSocketFactory can not be created with a null SSLContext"); + if (trustManager == null) + throw new IllegalArgumentException("AdvancedSslSocketFactory can not be created with a null Trust Manager"); + mSslContext = sslContext; + mTrustManager = trustManager; + mHostnameVerifier = hostnameVerifier; + } + + /** + * @see ProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) + */ + public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { + Socket socket = mSslContext.getSocketFactory().createSocket(host, port, clientHost, clientPort); + verifyPeerIdentity(host, port, socket); + return socket; + } + + /* + private void logSslInfo() { + if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) { + Log.v(TAG, "SUPPORTED SSL PARAMETERS"); + logSslParameters(mSslContext.getSupportedSSLParameters()); + Log.v(TAG, "DEFAULT SSL PARAMETERS"); + logSslParameters(mSslContext.getDefaultSSLParameters()); + Log.i(TAG, "CURRENT PARAMETERS"); + Log.i(TAG, "Protocol: " + mSslContext.getProtocol()); + } + Log.i(TAG, "PROVIDER"); + logSecurityProvider(mSslContext.getProvider()); + } + + private void logSecurityProvider(Provider provider) { + Log.i(TAG, "name: " + provider.getName()); + Log.i(TAG, "version: " + provider.getVersion()); + Log.i(TAG, "info: " + provider.getInfo()); + Enumeration keys = provider.propertyNames(); + String key; + while (keys.hasMoreElements()) { + key = (String) keys.nextElement(); + Log.i(TAG, " property " + key + " : " + provider.getProperty(key)); + } + } + + private void logSslParameters(SSLParameters params) { + Log.v(TAG, "Cipher suites: "); + String [] elements = params.getCipherSuites(); + for (int i=0; i mDataTransferListeners = new HashSet(); + private ByteBuffer mBuffer = ByteBuffer.allocate(4096); + + public ChunkFromFileChannelRequestEntity(final FileChannel channel, final String contentType, long chunkSize, final File file) { + super(); + if (channel == null) { + throw new IllegalArgumentException("File may not be null"); + } + if (chunkSize <= 0) { + throw new IllegalArgumentException("Chunk size must be greater than zero"); + } + mChannel = channel; + mContentType = contentType; + mChunkSize = chunkSize; + mFile = file; + mOffset = 0; + mTransferred = 0; + } + + public void setOffset(long offset) { + mOffset = offset; + } + + public long getContentLength() { + try { + return Math.min(mChunkSize, mChannel.size() - mChannel.position()); + } catch (IOException e) { + return mChunkSize; + } + } + + public String getContentType() { + return mContentType; + } + + public boolean isRepeatable() { + return true; + } + + @Override + public void addDatatransferProgressListener(OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.add(listener); + } + } + + @Override + public void addDatatransferProgressListeners(Collection listeners) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.addAll(listeners); + } + } + + @Override + public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.remove(listener); + } + } + + + public void writeRequest(final OutputStream out) throws IOException { + int readCount = 0; + Iterator it = null; + + try { + mChannel.position(mOffset); + long size = mFile.length(); + if (size == 0) size = -1; + long maxCount = Math.min(mOffset + mChunkSize, mChannel.size()); + while (mChannel.position() < maxCount) { + readCount = mChannel.read(mBuffer); + out.write(mBuffer.array(), 0, readCount); + mBuffer.clear(); + if (mTransferred < maxCount) { // condition to avoid accumulate progress for repeated chunks + mTransferred += readCount; + } + synchronized (mDataTransferListeners) { + it = mDataTransferListeners.iterator(); + while (it.hasNext()) { + it.next().onTransferProgress(readCount, mTransferred, size, mFile.getAbsolutePath()); + } + } + } + + } catch (IOException io) { + Log.e(TAG, io.getMessage()); + throw new RuntimeException("Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); + + } + } + +} \ No newline at end of file diff --git a/oc_framework/src/com/owncloud/android/lib/network/FileRequestEntity.java b/oc_framework/src/com/owncloud/android/lib/network/FileRequestEntity.java new file mode 100644 index 00000000..9bce93a7 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/FileRequestEntity.java @@ -0,0 +1,138 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +import java.io.File; +import java.io.IOException; +import java.io.OutputStream; +import java.io.RandomAccessFile; +import java.nio.ByteBuffer; +import java.nio.channels.FileChannel; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; + +import org.apache.commons.httpclient.methods.RequestEntity; + +import android.util.Log; + + + +/** + * A RequestEntity that represents a File. + * + */ +public class FileRequestEntity implements RequestEntity, ProgressiveDataTransferer { + + final File mFile; + final String mContentType; + Set mDataTransferListeners = new HashSet(); + + public FileRequestEntity(final File file, final String contentType) { + super(); + this.mFile = file; + this.mContentType = contentType; + if (file == null) { + throw new IllegalArgumentException("File may not be null"); + } + } + + @Override + public long getContentLength() { + return mFile.length(); + } + + @Override + public String getContentType() { + return mContentType; + } + + @Override + public boolean isRepeatable() { + return true; + } + + @Override + public void addDatatransferProgressListener(OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.add(listener); + } + } + + @Override + public void addDatatransferProgressListeners(Collection listeners) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.addAll(listeners); + } + } + + @Override + public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.remove(listener); + } + } + + + @Override + public void writeRequest(final OutputStream out) throws IOException { + //byte[] tmp = new byte[4096]; + ByteBuffer tmp = ByteBuffer.allocate(4096); + int readResult = 0; + + // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it + // globally in some fashionable manner + RandomAccessFile raf = new RandomAccessFile(mFile, "r"); + FileChannel channel = raf.getChannel(); + Iterator it = null; + long transferred = 0; + long size = mFile.length(); + if (size == 0) size = -1; + try { + while ((readResult = channel.read(tmp)) >= 0) { + out.write(tmp.array(), 0, readResult); + tmp.clear(); + transferred += readResult; + synchronized (mDataTransferListeners) { + it = mDataTransferListeners.iterator(); + while (it.hasNext()) { + it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath()); + } + } + } + + } catch (IOException io) { + Log.e("FileRequestException", io.getMessage()); + throw new RuntimeException("Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); + + } finally { + channel.close(); + raf.close(); + } + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/NetworkUtils.java b/oc_framework/src/com/owncloud/android/lib/network/NetworkUtils.java new file mode 100644 index 00000000..3a91b243 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/NetworkUtils.java @@ -0,0 +1,176 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; + +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.protocol.Protocol; +import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; +import org.apache.http.conn.ssl.X509HostnameVerifier; + +import android.content.Context; +import android.util.Log; + +public class NetworkUtils { + + final private static String TAG = NetworkUtils.class.getSimpleName(); + + /** Default timeout for waiting data from the server */ + public static final int DEFAULT_DATA_TIMEOUT = 60000; + + /** Default timeout for establishing a connection */ + public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; + + /** Connection manager for all the OwnCloudClients */ + private static MultiThreadedHttpConnectionManager mConnManager = null; + + private static Protocol mDefaultHttpsProtocol = null; + + private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null; + + private static X509HostnameVerifier mHostnameVerifier = null; + + + /** + * Registers or unregisters the proper components for advanced SSL handling. + * @throws IOException + */ + public static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException { + Protocol pr = null; + try { + pr = Protocol.getProtocol("https"); + if (pr != null && mDefaultHttpsProtocol == null) { + mDefaultHttpsProtocol = pr; + } + } catch (IllegalStateException e) { + // nothing to do here; really + } + boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory); + if (register && !isRegistered) { + Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443)); + + } else if (!register && isRegistered) { + if (mDefaultHttpsProtocol != null) { + Protocol.registerProtocol("https", mDefaultHttpsProtocol); + } + } + } + + public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { + if (mAdvancedSslSocketFactory == null) { + KeyStore trustStore = getKnownServersStore(context); + AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); + TrustManager[] tms = new TrustManager[] { trustMgr }; + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, tms, null); + + mHostnameVerifier = new BrowserCompatHostnameVerifier(); + mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); + } + return mAdvancedSslSocketFactory; + } + + + private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks"; + + private static String LOCAL_TRUSTSTORE_PASSWORD = "password"; + + private static KeyStore mKnownServersStore = null; + + /** + * Returns the local store of reliable server certificates, explicitly accepted by the user. + * + * Returns a KeyStore instance with empty content if the local store was never created. + * + * Loads the store from the storage environment if needed. + * + * @param context Android context where the operation is being performed. + * @return KeyStore instance with explicitly-accepted server certificates. + * @throws KeyStoreException When the KeyStore instance could not be created. + * @throws IOException When an existing local trust store could not be loaded. + * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm. + * @throws CertificateException When an exception occurred while loading the certificates from the local trust store. + */ + private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { + if (mKnownServersStore == null) { + //mKnownServersStore = KeyStore.getInstance("BKS"); + mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType()); + File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME); + Log.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath()); + if (localTrustStoreFile.exists()) { + InputStream in = new FileInputStream(localTrustStoreFile); + try { + mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); + } finally { + in.close(); + } + } else { + mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance + } + } + return mKnownServersStore; + } + + + public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, + CertificateException, IOException { + KeyStore knownServers = getKnownServersStore(context); + knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert); + FileOutputStream fos = null; + try { + fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE); + knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); + } finally { + fos.close(); + } + } + + + static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() { + if (mConnManager == null) { + mConnManager = new MultiThreadedHttpConnectionManager(); + mConnManager.getParams().setDefaultMaxConnectionsPerHost(5); + mConnManager.getParams().setMaxTotalConnections(5); + } + return mConnManager; + } + + +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/OnDatatransferProgressListener.java b/oc_framework/src/com/owncloud/android/lib/network/OnDatatransferProgressListener.java new file mode 100644 index 00000000..68c16e04 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/OnDatatransferProgressListener.java @@ -0,0 +1,30 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +public interface OnDatatransferProgressListener { + public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileAbsoluteName); +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/OwnCloudClient.java b/oc_framework/src/com/owncloud/android/lib/network/OwnCloudClient.java new file mode 100644 index 00000000..9ec8867f --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/OwnCloudClient.java @@ -0,0 +1,251 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.httpclient.Credentials; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpConnectionManager; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.HttpMethodBase; +import org.apache.commons.httpclient.HttpVersion; +import org.apache.commons.httpclient.URI; +import org.apache.commons.httpclient.UsernamePasswordCredentials; +import org.apache.commons.httpclient.auth.AuthPolicy; +import org.apache.commons.httpclient.auth.AuthScope; +import org.apache.commons.httpclient.cookie.CookiePolicy; +import org.apache.commons.httpclient.methods.HeadMethod; +import org.apache.commons.httpclient.params.HttpMethodParams; +import org.apache.http.HttpStatus; +import org.apache.http.params.CoreProtocolPNames; + +import com.owncloud.android.lib.network.webdav.WebdavUtils; + +import android.net.Uri; +import android.util.Log; + +public class OwnCloudClient extends HttpClient { + private static final int MAX_REDIRECTIONS_COUNT = 3; + + private Uri mUri; + private Credentials mCredentials; + private boolean mFollowRedirects; + private String mSsoSessionCookie; + final private static String TAG = OwnCloudClient.class.getSimpleName(); + public static final String USER_AGENT = "Android-ownCloud"; + + static private byte[] sExhaustBuffer = new byte[1024]; + + /** + * Constructor + */ + public OwnCloudClient(HttpConnectionManager connectionMgr) { + super(connectionMgr); + Log.d(TAG, "Creating OwnCloudClient"); + getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT); + getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); + mFollowRedirects = true; + mSsoSessionCookie = null; + } + + public void setBearerCredentials(String accessToken) { + AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class); + + List authPrefs = new ArrayList(1); + authPrefs.add(BearerAuthScheme.AUTH_POLICY); + getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); + + mCredentials = new BearerCredentials(accessToken); + getState().setCredentials(AuthScope.ANY, mCredentials); + mSsoSessionCookie = null; + } + + public void setBasicCredentials(String username, String password) { + List authPrefs = new ArrayList(1); + authPrefs.add(AuthPolicy.BASIC); + getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); + + getParams().setAuthenticationPreemptive(true); + mCredentials = new UsernamePasswordCredentials(username, password); + getState().setCredentials(AuthScope.ANY, mCredentials); + mSsoSessionCookie = null; + } + + public void setSsoSessionCookie(String accessToken) { + getParams().setAuthenticationPreemptive(false); + getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); + mSsoSessionCookie = accessToken; + mCredentials = null; + } + + + /** + * Check if a file exists in the OC server + * + * TODO replace with ExistenceOperation + * + * @return 'true' if the file exists; 'false' it doesn't exist + * @throws Exception When the existence could not be determined + */ + public boolean existsFile(String path) throws IOException, HttpException { + HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path)); + try { + int status = executeMethod(head); + Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":"")); + exhaustResponse(head.getResponseBodyAsStream()); + return (status == HttpStatus.SC_OK); + + } finally { + head.releaseConnection(); // let the connection available for other methods + } + } + + /** + * Requests the received method with the received timeout (milliseconds). + * + * Executes the method through the inherited HttpClient.executedMethod(method). + * + * Sets the socket and connection timeouts only for the method received. + * + * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default' + * + * @param method HTTP method request. + * @param readTimeout Timeout to set for data reception + * @param conntionTimout Timeout to set for connection establishment + */ + public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException { + int oldSoTimeout = getParams().getSoTimeout(); + int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout(); + try { + if (readTimeout >= 0) { + method.getParams().setSoTimeout(readTimeout); // this should be enough... + getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS + } + if (connectionTimeout >= 0) { + getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); + } + return executeMethod(method); + } finally { + getParams().setSoTimeout(oldSoTimeout); + getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout); + } + } + + + @Override + public int executeMethod(HttpMethod method) throws IOException, HttpException { + boolean customRedirectionNeeded = false; + try { + method.setFollowRedirects(mFollowRedirects); + } catch (Exception e) { + //if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed"); + customRedirectionNeeded = mFollowRedirects; + } + if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) { + method.setRequestHeader("Cookie", mSsoSessionCookie); + } + int status = super.executeMethod(method); + int redirectionsCount = 0; + while (customRedirectionNeeded && + redirectionsCount < MAX_REDIRECTIONS_COUNT && + ( status == HttpStatus.SC_MOVED_PERMANENTLY || + status == HttpStatus.SC_MOVED_TEMPORARILY || + status == HttpStatus.SC_TEMPORARY_REDIRECT) + ) { + + Header location = method.getResponseHeader("Location"); + if (location != null) { + Log.d(TAG, "Location to redirect: " + location.getValue()); + method.setURI(new URI(location.getValue(), true)); + status = super.executeMethod(method); + redirectionsCount++; + + } else { + Log.d(TAG, "No location to redirect!"); + status = HttpStatus.SC_NOT_FOUND; + } + } + + return status; + } + + + /** + * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation. + * + * @param responseBodyAsStream InputStream with the HTTP response to exhaust. + */ + public void exhaustResponse(InputStream responseBodyAsStream) { + if (responseBodyAsStream != null) { + try { + while (responseBodyAsStream.read(sExhaustBuffer) >= 0); + responseBodyAsStream.close(); + + } catch (IOException io) { + Log.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io); + } + } + } + + /** + * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client. + */ + public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) { + getParams().setSoTimeout(defaultDataTimeout); + getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout); + } + + /** + * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs + * @param uri + */ + public void setBaseUri(Uri uri) { + mUri = uri; + } + + public Uri getBaseUri() { + return mUri; + } + + public final Credentials getCredentials() { + return mCredentials; + } + + public final String getSsoSessionCookie() { + return mSsoSessionCookie; + } + + public void setFollowRedirects(boolean followRedirects) { + mFollowRedirects = followRedirects; + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/OwnCloudClientFactory.java b/oc_framework/src/com/owncloud/android/lib/network/OwnCloudClientFactory.java new file mode 100644 index 00000000..daea819c --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/OwnCloudClientFactory.java @@ -0,0 +1,158 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +import java.io.IOException; +import java.security.GeneralSecurityException; + +import com.owncloud.android.lib.accounts.AccountTypeUtils; +import com.owncloud.android.lib.accounts.AccountUtils; +import com.owncloud.android.lib.accounts.OwnCloudAccount; +import com.owncloud.android.lib.accounts.AccountUtils.AccountNotFoundException; + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountManagerFuture; +import android.accounts.AuthenticatorException; +import android.accounts.OperationCanceledException; +import android.app.Activity; +import android.content.Context; +import android.net.Uri; +import android.os.Bundle; +import android.util.Log; + +public class OwnCloudClientFactory { + + final private static String TAG = OwnCloudClientFactory.class.getSimpleName(); + + /** Default timeout for waiting data from the server */ + public static final int DEFAULT_DATA_TIMEOUT = 60000; + + /** Default timeout for establishing a connection */ + public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; + + + /** + * Creates a OwnCloudClient setup for an ownCloud account + * + * Do not call this method from the main thread. + * + * @param account The ownCloud account + * @param appContext Android application context + * @return A OwnCloudClient object ready to be used + * @throws AuthenticatorException If the authenticator failed to get the authorization token for the account. + * @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account. + * @throws IOException If there was some I/O error while getting the authorization token for the account. + * @throws AccountNotFoundException If 'account' is unknown for the AccountManager + */ + public static OwnCloudClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { + //Log_OC.d(TAG, "Creating OwnCloudClient associated to " + account.name); + + Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account)); + AccountManager am = AccountManager.get(appContext); + boolean isOauth2 = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here + boolean isSamlSso = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null; + OwnCloudClient client = createOwnCloudClient(uri, appContext, !isSamlSso); + if (isOauth2) { + String accessToken = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypeAccessToken(account.type), false); + client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token + + } else if (isSamlSso) { // TODO avoid a call to getUserData here + String accessToken = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(account.type), false); + client.setSsoSessionCookie(accessToken); + + } else { + String username = account.name.substring(0, account.name.lastIndexOf('@')); + //String password = am.getPassword(account); + String password = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypePass(account.type), false); + client.setBasicCredentials(username, password); + } + + return client; + } + + + public static OwnCloudClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { + Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account)); + AccountManager am = AccountManager.get(appContext); + boolean isOauth2 = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here + boolean isSamlSso = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null; + OwnCloudClient client = createOwnCloudClient(uri, appContext, !isSamlSso); + + if (isOauth2) { // TODO avoid a call to getUserData here + AccountManagerFuture future = am.getAuthToken(account, AccountTypeUtils.getAuthTokenTypeAccessToken(account.type), null, currentActivity, null, null); + Bundle result = future.getResult(); + String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN); + if (accessToken == null) throw new AuthenticatorException("WTF!"); + client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token + + } else if (isSamlSso) { // TODO avoid a call to getUserData here + AccountManagerFuture future = am.getAuthToken(account, AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(account.type), null, currentActivity, null, null); + Bundle result = future.getResult(); + String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN); + if (accessToken == null) throw new AuthenticatorException("WTF!"); + client.setSsoSessionCookie(accessToken); + + } else { + String username = account.name.substring(0, account.name.lastIndexOf('@')); + //String password = am.getPassword(account); + //String password = am.blockingGetAuthToken(account, MainApp.getAuthTokenTypePass(), false); + AccountManagerFuture future = am.getAuthToken(account, AccountTypeUtils.getAuthTokenTypePass(account.type), null, currentActivity, null, null); + Bundle result = future.getResult(); + String password = result.getString(AccountManager.KEY_AUTHTOKEN); + client.setBasicCredentials(username, password); + } + + return client; + } + + /** + * Creates a OwnCloudClient to access a URL and sets the desired parameters for ownCloud client connections. + * + * @param uri URL to the ownCloud server + * @param context Android context where the OwnCloudClient is being created. + * @return A OwnCloudClient object ready to be used + */ + public static OwnCloudClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) { + try { + NetworkUtils.registerAdvancedSslContext(true, context); + } catch (GeneralSecurityException e) { + Log.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e); + + } catch (IOException e) { + Log.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e); + } + + OwnCloudClient client = new OwnCloudClient(NetworkUtils.getMultiThreadedConnManager()); + + client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); + client.setBaseUri(uri); + client.setFollowRedirects(followRedirects); + + return client; + } + + +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/ProgressiveDataTransferer.java b/oc_framework/src/com/owncloud/android/lib/network/ProgressiveDataTransferer.java new file mode 100644 index 00000000..9819d238 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/ProgressiveDataTransferer.java @@ -0,0 +1,39 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +import java.util.Collection; + + + +public interface ProgressiveDataTransferer { + + public void addDatatransferProgressListener (OnDatatransferProgressListener listener); + + public void addDatatransferProgressListeners(Collection listeners); + + public void removeDatatransferProgressListener(OnDatatransferProgressListener listener); + +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/ServerNameIndicator.java b/oc_framework/src/com/owncloud/android/lib/network/ServerNameIndicator.java new file mode 100644 index 00000000..b29b7858 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/ServerNameIndicator.java @@ -0,0 +1,151 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network; + +import java.lang.ref.WeakReference; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.concurrent.atomic.AtomicReference; + +import javax.net.ssl.SSLSocket; + +import android.util.Log; + + +/** + * Enables the support of Server Name Indication if existing + * in the underlying network implementation. + * + * Build as a singleton. + * + * @author David A. Velasco + */ +public class ServerNameIndicator { + + private static final String TAG = ServerNameIndicator.class.getSimpleName(); + + private static final AtomicReference mSingleInstance = new AtomicReference(); + + private static final String METHOD_NAME = "setHostname"; + + private final WeakReference> mSSLSocketClassRef; + private final WeakReference mSetHostnameMethodRef; + + + /** + * Private constructor, class is a singleton. + * + * @param sslSocketClass Underlying implementation class of {@link SSLSocket} used to connect with the server. + * @param setHostnameMethod Name of the method to call to enable the SNI support. + */ + private ServerNameIndicator(Class sslSocketClass, Method setHostnameMethod) { + mSSLSocketClassRef = new WeakReference>(sslSocketClass); + mSetHostnameMethodRef = (setHostnameMethod == null) ? null : new WeakReference(setHostnameMethod); + } + + + /** + * Calls the {@code #setHostname(String)} method of the underlying implementation + * of {@link SSLSocket} if exists. + * + * Creates and initializes the single instance of the class when needed + * + * @param hostname The name of the server host of interest. + * @param sslSocket Client socket to connect with the server. + */ + public static void setServerNameIndication(String hostname, SSLSocket sslSocket) { + final Method setHostnameMethod = getMethod(sslSocket); + if (setHostnameMethod != null) { + try { + setHostnameMethod.invoke(sslSocket, hostname); + Log.i(TAG, "SNI done, hostname: " + hostname); + + } catch (IllegalArgumentException e) { + Log.e(TAG, "Call to SSLSocket#setHost(String) failed ", e); + + } catch (IllegalAccessException e) { + Log.e(TAG, "Call to SSLSocket#setHost(String) failed ", e); + + } catch (InvocationTargetException e) { + Log.e(TAG, "Call to SSLSocket#setHost(String) failed ", e); + } + } else { + Log.i(TAG, "SNI not supported"); + } + } + + + /** + * Gets the method to invoke trying to minimize the effective + * application of reflection. + * + * @param sslSocket Instance of the SSL socket to use in connection with server. + * @return Method to call to indicate the server name of interest to the server. + */ + private static Method getMethod(SSLSocket sslSocket) { + final Class sslSocketClass = sslSocket.getClass(); + final ServerNameIndicator instance = mSingleInstance.get(); + if (instance == null) { + return initFrom(sslSocketClass); + + } else if (instance.mSSLSocketClassRef.get() != sslSocketClass) { + // the underlying class changed + return initFrom(sslSocketClass); + + } else if (instance.mSetHostnameMethodRef == null) { + // SNI not supported + return null; + + } else { + final Method cachedSetHostnameMethod = instance.mSetHostnameMethodRef.get(); + return (cachedSetHostnameMethod == null) ? initFrom(sslSocketClass) : cachedSetHostnameMethod; + } + } + + + /** + * Singleton initializer. + * + * Uses reflection to extract and 'cache' the method to invoke to indicate the desited host name to the server side. + * + * @param sslSocketClass Underlying class providing the implementation of {@link SSLSocket}. + * @return Method to call to indicate the server name of interest to the server. + */ + private static Method initFrom(Class sslSocketClass) { + Log.i(TAG, "SSLSocket implementation: " + sslSocketClass.getCanonicalName()); + Method setHostnameMethod = null; + try { + setHostnameMethod = sslSocketClass.getMethod(METHOD_NAME, String.class); + } catch (SecurityException e) { + Log.e(TAG, "Could not access to SSLSocket#setHostname(String) method ", e); + + } catch (NoSuchMethodException e) { + Log.i(TAG, "Could not find SSLSocket#setHostname(String) method - SNI not supported"); + } + mSingleInstance.set(new ServerNameIndicator(sslSocketClass, setHostnameMethod)); + return setHostnameMethod; + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/webdav/WebdavEntry.java b/oc_framework/src/com/owncloud/android/lib/network/webdav/WebdavEntry.java new file mode 100644 index 00000000..d9844841 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/webdav/WebdavEntry.java @@ -0,0 +1,158 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network.webdav; + +import java.util.Date; + +import org.apache.jackrabbit.webdav.MultiStatusResponse; +import org.apache.jackrabbit.webdav.property.DavProperty; +import org.apache.jackrabbit.webdav.property.DavPropertyName; +import org.apache.jackrabbit.webdav.property.DavPropertySet; + + + +import android.net.Uri; +import android.util.Log; + +public class WebdavEntry { + private String mName, mPath, mUri, mContentType, mEtag; + private long mContentLength, mCreateTimestamp, mModifiedTimestamp; + + public WebdavEntry(MultiStatusResponse ms, String splitElement) { + resetData(); + if (ms.getStatus().length != 0) { + mUri = ms.getHref(); + + mPath = mUri.split(splitElement, 2)[1]; + + int status = ms.getStatus()[0].getStatusCode(); + DavPropertySet propSet = ms.getProperties(status); + @SuppressWarnings("rawtypes") + DavProperty prop = propSet.get(DavPropertyName.DISPLAYNAME); + if (prop != null) { + mName = (String) prop.getName().toString(); + mName = mName.substring(1, mName.length()-1); + } + else { + String[] tmp = mPath.split("/"); + if (tmp.length > 0) + mName = tmp[tmp.length - 1]; + } + + // use unknown mimetype as default behavior + mContentType = "application/octet-stream"; + prop = propSet.get(DavPropertyName.GETCONTENTTYPE); + if (prop != null) { + mContentType = (String) prop.getValue(); + // dvelasco: some builds of ownCloud server 4.0.x added a trailing ';' to the MIME type ; if looks fixed, but let's be cautious + if (mContentType.indexOf(";") >= 0) { + mContentType = mContentType.substring(0, mContentType.indexOf(";")); + } + } + + // check if it's a folder in the standard way: see RFC2518 12.2 . RFC4918 14.3 + prop = propSet.get(DavPropertyName.RESOURCETYPE); + if (prop!= null) { + Object value = prop.getValue(); + if (value != null) { + mContentType = "DIR"; // a specific attribute would be better, but this is enough; unless while we have no reason to distinguish MIME types for folders + } + } + + prop = propSet.get(DavPropertyName.GETCONTENTLENGTH); + if (prop != null) + mContentLength = Long.parseLong((String) prop.getValue()); + + prop = propSet.get(DavPropertyName.GETLASTMODIFIED); + if (prop != null) { + Date d = WebdavUtils + .parseResponseDate((String) prop.getValue()); + mModifiedTimestamp = (d != null) ? d.getTime() : 0; + } + + prop = propSet.get(DavPropertyName.CREATIONDATE); + if (prop != null) { + Date d = WebdavUtils + .parseResponseDate((String) prop.getValue()); + mCreateTimestamp = (d != null) ? d.getTime() : 0; + } + + prop = propSet.get(DavPropertyName.GETETAG); + if (prop != null) { + mEtag = (String) prop.getValue(); + mEtag = mEtag.substring(1, mEtag.length()-1); + } + + } else { + Log.e("WebdavEntry", + "General fuckup, no status for webdav response"); + } + } + + public String path() { + return mPath; + } + + public String decodedPath() { + return Uri.decode(mPath); + } + + public String name() { + return mName; + } + + public boolean isDirectory() { + return mContentType.equals("DIR"); + } + + public String contentType() { + return mContentType; + } + + public String uri() { + return mUri; + } + + public long contentLength() { + return mContentLength; + } + + public long createTimestamp() { + return mCreateTimestamp; + } + + public long modifiedTimestamp() { + return mModifiedTimestamp; + } + + public String etag() { + return mEtag; + } + + private void resetData() { + mName = mUri = mContentType = null; + mContentLength = mCreateTimestamp = mModifiedTimestamp = 0; + } +} diff --git a/oc_framework/src/com/owncloud/android/lib/network/webdav/WebdavUtils.java b/oc_framework/src/com/owncloud/android/lib/network/webdav/WebdavUtils.java new file mode 100644 index 00000000..7528e6f1 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/network/webdav/WebdavUtils.java @@ -0,0 +1,83 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.network.webdav; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.Locale; + +import android.net.Uri; + +public class WebdavUtils { + public static final SimpleDateFormat DISPLAY_DATE_FORMAT = new SimpleDateFormat( + "dd.MM.yyyy hh:mm"); + private static final SimpleDateFormat DATETIME_FORMATS[] = { + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US), + new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US), + new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US), + new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US), + new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), + new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; + + public static String prepareXmlForPropFind() { + String ret = ""; + return ret; + } + + public static String prepareXmlForPatch() { + return ""; + } + + public static Date parseResponseDate(String date) { + Date returnDate = null; + for (int i = 0; i < DATETIME_FORMATS.length; ++i) { + try { + returnDate = DATETIME_FORMATS[i].parse(date); + return returnDate; + } catch (ParseException e) { + } + } + return null; + } + + /** + * Encodes a path according to URI RFC 2396. + * + * If the received path doesn't start with "/", the method adds it. + * + * @param remoteFilePath Path + * @return Encoded path according to RFC 2396, always starting with "/" + */ + public static String encodePath(String remoteFilePath) { + String encodedPath = Uri.encode(remoteFilePath, "/"); + if (!encodedPath.startsWith("/")) + encodedPath = "/" + encodedPath; + return encodedPath; + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/common/OnRemoteOperationListener.java b/oc_framework/src/com/owncloud/android/lib/operations/common/OnRemoteOperationListener.java new file mode 100644 index 00000000..30f16031 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/common/OnRemoteOperationListener.java @@ -0,0 +1,33 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.common; + + +public interface OnRemoteOperationListener { + + void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result); + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/common/OperationCancelledException.java b/oc_framework/src/com/owncloud/android/lib/operations/common/OperationCancelledException.java new file mode 100644 index 00000000..cd73dd8b --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/common/OperationCancelledException.java @@ -0,0 +1,35 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.common; + +public class OperationCancelledException extends Exception { + + /** + * Generated serial version - to avoid Java warning + */ + private static final long serialVersionUID = -6350981497740424983L; + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteFile.java b/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteFile.java new file mode 100644 index 00000000..3304b1c1 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteFile.java @@ -0,0 +1,187 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.common; + +import java.io.Serializable; + +import android.os.Parcel; +import android.os.Parcelable; + +import com.owncloud.android.lib.network.webdav.WebdavEntry; +import com.owncloud.android.lib.utils.FileUtils; + +/** + * Contains the data of a Remote File from a WebDavEntry + * + * @author masensio + */ + +public class RemoteFile implements Parcelable, Serializable { + + /** Generated - should be refreshed every time the class changes!! */ + private static final long serialVersionUID = 532139091191390616L; + + private String mRemotePath; + private String mMimeType; + private long mLength; + private long mCreationTimestamp; + private long mModifiedTimestamp; + private String mEtag; + + /** + * Getters and Setters + */ + + public String getRemotePath() { + return mRemotePath; + } + + public void setRemotePath(String remotePath) { + this.mRemotePath = remotePath; + } + + public String getMimeType() { + return mMimeType; + } + + public void setMimeType(String mimeType) { + this.mMimeType = mimeType; + } + + public long getLength() { + return mLength; + } + + public void setLength(long length) { + this.mLength = length; + } + + public long getCreationTimestamp() { + return mCreationTimestamp; + } + + public void setCreationTimestamp(long creationTimestamp) { + this.mCreationTimestamp = creationTimestamp; + } + + public long getModifiedTimestamp() { + return mModifiedTimestamp; + } + + public void setModifiedTimestamp(long modifiedTimestamp) { + this.mModifiedTimestamp = modifiedTimestamp; + } + + public String getEtag() { + return mEtag; + } + + public void setEtag(String etag) { + this.mEtag = etag; + } + + /** + * Create new {@link RemoteFile} with given path. + * + * The path received must be URL-decoded. Path separator must be OCFile.PATH_SEPARATOR, and it must be the first character in 'path'. + * + * @param path The remote path of the file. + */ + public RemoteFile(String path) { + resetData(); + if (path == null || path.length() <= 0 || !path.startsWith(FileUtils.PATH_SEPARATOR)) { + throw new IllegalArgumentException("Trying to create a OCFile with a non valid remote path: " + path); + } + mRemotePath = path; + } + + public RemoteFile(WebdavEntry we) { + this(we.decodedPath()); + this.setCreationTimestamp(we.createTimestamp()); + this.setLength(we.contentLength()); + this.setMimeType(we.contentType()); + this.setModifiedTimestamp(we.modifiedTimestamp()); + this.setEtag(we.etag()); + } + + /** + * Used internally. Reset all file properties + */ + private void resetData() { + mRemotePath = null; + mMimeType = null; + mLength = 0; + mCreationTimestamp = 0; + mModifiedTimestamp = 0; + mEtag = null; + } + + /** + * Parcelable Methods + */ + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + @Override + public RemoteFile createFromParcel(Parcel source) { + return new RemoteFile(source); + } + + @Override + public RemoteFile[] newArray(int size) { + return new RemoteFile[size]; + } + }; + + + /** + * Reconstruct from parcel + * + * @param source The source parcel + */ + private RemoteFile(Parcel source) { + mRemotePath = source.readString(); + mMimeType = source.readString(); + mLength = source.readLong(); + mCreationTimestamp = source.readLong(); + mModifiedTimestamp = source.readLong(); + mEtag = source.readString(); + } + + @Override + public int describeContents() { + return this.hashCode(); + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeString(mRemotePath); + dest.writeString(mMimeType); + dest.writeLong(mLength); + dest.writeLong(mCreationTimestamp); + dest.writeLong(mModifiedTimestamp); + dest.writeString(mEtag); + } + + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteOperation.java new file mode 100644 index 00000000..44c652bf --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteOperation.java @@ -0,0 +1,295 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.common; + +import java.io.IOException; + +import org.apache.commons.httpclient.Credentials; + +import com.owncloud.android.lib.network.BearerCredentials; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.OwnCloudClientFactory; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; + + + +import android.accounts.Account; +import android.accounts.AccountManager; +import android.accounts.AccountsException; +import android.app.Activity; +import android.content.Context; +import android.os.Handler; +import android.util.Log; + + +/** + * Operation which execution involves one or several interactions with an ownCloud server. + * + * Provides methods to execute the operation both synchronously or asynchronously. + * + * @author David A. Velasco + */ +public abstract class RemoteOperation implements Runnable { + + private static final String TAG = RemoteOperation.class.getSimpleName(); + + /** ownCloud account in the remote ownCloud server to operate */ + private Account mAccount = null; + + /** Android Application context */ + private Context mContext = null; + + /** Object to interact with the remote server */ + private OwnCloudClient mClient = null; + + /** Callback object to notify about the execution of the remote operation */ + private OnRemoteOperationListener mListener = null; + + /** Handler to the thread where mListener methods will be called */ + private Handler mListenerHandler = null; + + /** Activity */ + private Activity mCallerActivity; + + + /** + * Abstract method to implement the operation in derived classes. + */ + protected abstract RemoteOperationResult run(OwnCloudClient client); + + + /** + * Synchronously executes the remote operation on the received ownCloud account. + * + * Do not call this method from the main thread. + * + * This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}. + * + * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation. + * @param context Android context for the component calling the method. + * @return Result of the operation. + */ + public final RemoteOperationResult execute(Account account, Context context) { + if (account == null) + throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account"); + if (context == null) + throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context"); + mAccount = account; + mContext = context.getApplicationContext(); + try { + mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext); + } catch (Exception e) { + Log.e(TAG, "Error while trying to access to " + mAccount.name, e); + return new RemoteOperationResult(e); + } + return run(mClient); + } + + + /** + * Synchronously executes the remote operation + * + * Do not call this method from the main thread. + * + * @param client Client object to reach an ownCloud server during the execution of the operation. + * @return Result of the operation. + */ + public final RemoteOperationResult execute(OwnCloudClient client) { + if (client == null) + throw new IllegalArgumentException("Trying to execute a remote operation with a NULL OwnCloudClient"); + mClient = client; + return run(client); + } + + + /** + * Asynchronously executes the remote operation + * + * This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient)}. + * + * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation. + * @param context Android context for the component calling the method. + * @param listener Listener to be notified about the execution of the operation. + * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. + * @return Thread were the remote operation is executed. + */ + public final Thread execute(Account account, Context context, OnRemoteOperationListener listener, Handler listenerHandler, Activity callerActivity) { + if (account == null) + throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account"); + if (context == null) + throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context"); + mAccount = account; + mContext = context.getApplicationContext(); + mCallerActivity = callerActivity; + mClient = null; // the client instance will be created from mAccount and mContext in the runnerThread to create below + + mListener = listener; + + mListenerHandler = listenerHandler; + + Thread runnerThread = new Thread(this); + runnerThread.start(); + return runnerThread; + } + + + /** + * Asynchronously executes the remote operation + * + * @param client Client object to reach an ownCloud server during the execution of the operation. + * @param listener Listener to be notified about the execution of the operation. + * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. + * @return Thread were the remote operation is executed. + */ + public final Thread execute(OwnCloudClient client, OnRemoteOperationListener listener, Handler listenerHandler) { + if (client == null) { + throw new IllegalArgumentException("Trying to execute a remote operation with a NULL OwnCloudClient"); + } + mClient = client; + + if (listener == null) { + throw new IllegalArgumentException("Trying to execute a remote operation asynchronously without a listener to notiy the result"); + } + mListener = listener; + + if (listenerHandler == null) { + throw new IllegalArgumentException("Trying to execute a remote operation asynchronously without a handler to the listener's thread"); + } + mListenerHandler = listenerHandler; + + Thread runnerThread = new Thread(this); + runnerThread.start(); + return runnerThread; + } + + /** + * Synchronously retries the remote operation using the same OwnCloudClient in the last call to {@link RemoteOperation#execute(OwnCloudClient)} + * + * @param listener Listener to be notified about the execution of the operation. + * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. + * @return Thread were the remote operation is executed. + */ + public final RemoteOperationResult retry() { + return execute(mClient); + } + + /** + * Asynchronously retries the remote operation using the same OwnCloudClient in the last call to {@link RemoteOperation#execute(OwnCloudClient, OnRemoteOperationListener, Handler)} + * + * @param listener Listener to be notified about the execution of the operation. + * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. + * @return Thread were the remote operation is executed. + */ + public final Thread retry(OnRemoteOperationListener listener, Handler listenerHandler) { + return execute(mClient, listener, listenerHandler); + } + + + /** + * Asynchronous execution of the operation + * started by {@link RemoteOperation#execute(OwnCloudClient, OnRemoteOperationListener, Handler)}, + * and result posting. + * + * TODO refactor && clean the code; now it's a mess + */ + @Override + public final void run() { + RemoteOperationResult result = null; + boolean repeat = false; + do { + try{ + if (mClient == null) { + if (mAccount != null && mContext != null) { + if (mCallerActivity != null) { + mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext, mCallerActivity); + } else { + mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext); + } + } else { + throw new IllegalStateException("Trying to run a remote operation asynchronously with no client instance or account"); + } + } + + } catch (IOException e) { + Log.e(TAG, "Error while trying to access to " + mAccount.name, new AccountsException("I/O exception while trying to authorize the account", e)); + result = new RemoteOperationResult(e); + + } catch (AccountsException e) { + Log.e(TAG, "Error while trying to access to " + mAccount.name, e); + result = new RemoteOperationResult(e); + } + + if (result == null) + result = run(mClient); + + repeat = false; + if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() && +// (result.getCode() == ResultCode.UNAUTHORIZED || (result.isTemporalRedirection() && result.isIdPRedirection()))) { + (result.getCode() == ResultCode.UNAUTHORIZED || result.isIdPRedirection())) { + /// possible fail due to lack of authorization in an operation performed in foreground + Credentials cred = mClient.getCredentials(); + String ssoSessionCookie = mClient.getSsoSessionCookie(); + if (cred != null || ssoSessionCookie != null) { + /// confirmed : unauthorized operation + AccountManager am = AccountManager.get(mContext); + boolean bearerAuthorization = (cred != null && cred instanceof BearerCredentials); + boolean samlBasedSsoAuthorization = (cred == null && ssoSessionCookie != null); + if (bearerAuthorization) { + am.invalidateAuthToken(mAccount.type, ((BearerCredentials)cred).getAccessToken()); + } else if (samlBasedSsoAuthorization ) { + am.invalidateAuthToken(mAccount.type, ssoSessionCookie); + } else { + am.clearPassword(mAccount); + } + mClient = null; + repeat = true; // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity + result = null; + } + } + } while (repeat); + + final RemoteOperationResult resultToSend = result; + if (mListenerHandler != null && mListener != null) { + mListenerHandler.post(new Runnable() { + @Override + public void run() { + mListener.onRemoteOperationFinish(RemoteOperation.this, resultToSend); + } + }); + } + } + + + /** + * Returns the current client instance to access the remote server. + * + * @return Current client instance to access the remote server. + */ + public final OwnCloudClient getClient() { + return mClient; + } + + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteOperationResult.java b/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteOperationResult.java new file mode 100644 index 00000000..df6d7471 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/common/RemoteOperationResult.java @@ -0,0 +1,363 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.common; + +import java.io.IOException; +import java.io.Serializable; +import java.net.MalformedURLException; +import java.net.SocketException; +import java.net.SocketTimeoutException; +import java.net.UnknownHostException; +import java.util.ArrayList; + +import javax.net.ssl.SSLException; + +import org.apache.commons.httpclient.ConnectTimeoutException; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpStatus; +import org.apache.jackrabbit.webdav.DavException; +import org.json.JSONException; + +import com.owncloud.android.lib.accounts.AccountUtils.AccountNotFoundException; +import com.owncloud.android.lib.network.CertificateCombinedException; + +import android.accounts.Account; +import android.accounts.AccountsException; +import android.util.Log; + + +/** + * The result of a remote operation required to an ownCloud server. + * + * Provides a common classification of remote operation results for all the + * application. + * + * @author David A. Velasco + */ +public class RemoteOperationResult implements Serializable { + + /** Generated - should be refreshed every time the class changes!! */ + private static final long serialVersionUID = -8257349554488668693L; + + private static final String TAG = "RemoteOperationResult"; + + public enum ResultCode { + OK, + OK_SSL, + OK_NO_SSL, + UNHANDLED_HTTP_CODE, + UNAUTHORIZED, + FILE_NOT_FOUND, + INSTANCE_NOT_CONFIGURED, + UNKNOWN_ERROR, + WRONG_CONNECTION, + TIMEOUT, + INCORRECT_ADDRESS, + HOST_NOT_AVAILABLE, + NO_NETWORK_CONNECTION, + SSL_ERROR, + SSL_RECOVERABLE_PEER_UNVERIFIED, + BAD_OC_VERSION, + CANCELLED, + INVALID_LOCAL_FILE_NAME, + INVALID_OVERWRITE, + CONFLICT, + OAUTH2_ERROR, + SYNC_CONFLICT, + LOCAL_STORAGE_FULL, + LOCAL_STORAGE_NOT_MOVED, + LOCAL_STORAGE_NOT_COPIED, + OAUTH2_ERROR_ACCESS_DENIED, + QUOTA_EXCEEDED, + ACCOUNT_NOT_FOUND, + ACCOUNT_EXCEPTION, + ACCOUNT_NOT_NEW, + ACCOUNT_NOT_THE_SAME, + INVALID_CHARACTER_IN_NAME + } + + private boolean mSuccess = false; + private int mHttpCode = -1; + private Exception mException = null; + private ResultCode mCode = ResultCode.UNKNOWN_ERROR; + private String mRedirectedLocation; + + private ArrayList mFiles; + + public RemoteOperationResult(ResultCode code) { + mCode = code; + mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL || code == ResultCode.OK_NO_SSL); + mFiles = null; + } + + private RemoteOperationResult(boolean success, int httpCode) { + mSuccess = success; + mHttpCode = httpCode; + + if (success) { + mCode = ResultCode.OK; + + } else if (httpCode > 0) { + switch (httpCode) { + case HttpStatus.SC_UNAUTHORIZED: + mCode = ResultCode.UNAUTHORIZED; + break; + case HttpStatus.SC_NOT_FOUND: + mCode = ResultCode.FILE_NOT_FOUND; + break; + case HttpStatus.SC_INTERNAL_SERVER_ERROR: + mCode = ResultCode.INSTANCE_NOT_CONFIGURED; + break; + case HttpStatus.SC_CONFLICT: + mCode = ResultCode.CONFLICT; + break; + case HttpStatus.SC_INSUFFICIENT_STORAGE: + mCode = ResultCode.QUOTA_EXCEEDED; + break; + default: + mCode = ResultCode.UNHANDLED_HTTP_CODE; + Log.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode); + } + } + } + + public RemoteOperationResult(boolean success, int httpCode, Header[] headers) { + this(success, httpCode); + if (headers != null) { + Header current; + for (int i=0; i files){ + mFiles = files; + } + + public ArrayList getData(){ + return mFiles; + } + + public boolean isSuccess() { + return mSuccess; + } + + public boolean isCancelled() { + return mCode == ResultCode.CANCELLED; + } + + public int getHttpCode() { + return mHttpCode; + } + + public ResultCode getCode() { + return mCode; + } + + public Exception getException() { + return mException; + } + + public boolean isSslRecoverableException() { + return mCode == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED; + } + + private CertificateCombinedException getCertificateCombinedException(Exception e) { + CertificateCombinedException result = null; + if (e instanceof CertificateCombinedException) { + return (CertificateCombinedException) e; + } + Throwable cause = mException.getCause(); + Throwable previousCause = null; + while (cause != null && cause != previousCause && !(cause instanceof CertificateCombinedException)) { + previousCause = cause; + cause = cause.getCause(); + } + if (cause != null && cause instanceof CertificateCombinedException) { + result = (CertificateCombinedException) cause; + } + return result; + } + + public String getLogMessage() { + + if (mException != null) { + if (mException instanceof OperationCancelledException) { + return "Operation cancelled by the caller"; + + } else if (mException instanceof SocketException) { + return "Socket exception"; + + } else if (mException instanceof SocketTimeoutException) { + return "Socket timeout exception"; + + } else if (mException instanceof ConnectTimeoutException) { + return "Connect timeout exception"; + + } else if (mException instanceof MalformedURLException) { + return "Malformed URL exception"; + + } else if (mException instanceof UnknownHostException) { + return "Unknown host exception"; + + } else if (mException instanceof CertificateCombinedException) { + if (((CertificateCombinedException) mException).isRecoverable()) + return "SSL recoverable exception"; + else + return "SSL exception"; + + } else if (mException instanceof SSLException) { + return "SSL exception"; + + } else if (mException instanceof DavException) { + return "Unexpected WebDAV exception"; + + } else if (mException instanceof HttpException) { + return "HTTP violation"; + + } else if (mException instanceof IOException) { + return "Unrecovered transport exception"; + + } else if (mException instanceof AccountNotFoundException) { + Account failedAccount = ((AccountNotFoundException)mException).getFailedAccount(); + return mException.getMessage() + " (" + (failedAccount != null ? failedAccount.name : "NULL") + ")"; + + } else if (mException instanceof AccountsException) { + return "Exception while using account"; + + } else if (mException instanceof JSONException) { + return "JSON exception"; + + } else { + return "Unexpected exception"; + } + } + + if (mCode == ResultCode.INSTANCE_NOT_CONFIGURED) { + return "The ownCloud server is not configured!"; + + } else if (mCode == ResultCode.NO_NETWORK_CONNECTION) { + return "No network connection"; + + } else if (mCode == ResultCode.BAD_OC_VERSION) { + return "No valid ownCloud version was found at the server"; + + } else if (mCode == ResultCode.LOCAL_STORAGE_FULL) { + return "Local storage full"; + + } else if (mCode == ResultCode.LOCAL_STORAGE_NOT_MOVED) { + return "Error while moving file to final directory"; + + } else if (mCode == ResultCode.ACCOUNT_NOT_NEW) { + return "Account already existing when creating a new one"; + + } else if (mCode == ResultCode.ACCOUNT_NOT_THE_SAME) { + return "Authenticated with a different account than the one updating"; + } else if (mCode == ResultCode.INVALID_CHARACTER_IN_NAME) { + return "The file name contains an forbidden character"; + } + + return "Operation finished with HTTP status code " + mHttpCode + " (" + (isSuccess() ? "success" : "fail") + ")"; + + } + + public boolean isServerFail() { + return (mHttpCode >= HttpStatus.SC_INTERNAL_SERVER_ERROR); + } + + public boolean isException() { + return (mException != null); + } + + public boolean isTemporalRedirection() { + return (mHttpCode == 302 || mHttpCode == 307); + } + + public String getRedirectedLocation() { + return mRedirectedLocation; + } + + public boolean isIdPRedirection() { + return (mRedirectedLocation != null && + (mRedirectedLocation.toUpperCase().contains("SAML") || + mRedirectedLocation.toLowerCase().contains("wayf"))); + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/ChunkedUploadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/ChunkedUploadRemoteFileOperation.java new file mode 100644 index 00000000..9fde7c0f --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/ChunkedUploadRemoteFileOperation.java @@ -0,0 +1,101 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.nio.channels.FileChannel; +import java.util.Random; + +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.methods.PutMethod; + +import com.owncloud.android.lib.network.ChunkFromFileChannelRequestEntity; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.ProgressiveDataTransferer; +import com.owncloud.android.lib.network.webdav.WebdavUtils; + + +import android.util.Log; + + +public class ChunkedUploadRemoteFileOperation extends UploadRemoteFileOperation { + + public static final long CHUNK_SIZE = 1024000; + private static final String OC_CHUNKED_HEADER = "OC-Chunked"; + private static final String TAG = ChunkedUploadRemoteFileOperation.class.getSimpleName(); + + public ChunkedUploadRemoteFileOperation(String storagePath, String remotePath, String mimeType) { + super(storagePath, remotePath, mimeType); + } + + @Override + protected int uploadFile(OwnCloudClient client) throws HttpException, IOException { + int status = -1; + + FileChannel channel = null; + RandomAccessFile raf = null; + try { + File file = new File(mStoragePath); + raf = new RandomAccessFile(file, "r"); + channel = raf.getChannel(); + mEntity = new ChunkFromFileChannelRequestEntity(channel, mMimeType, CHUNK_SIZE, file); + //((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(getDataTransferListeners()); + synchronized (mDataTransferListeners) { + ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners); + } + + long offset = 0; + String uriPrefix = client.getBaseUri() + WebdavUtils.encodePath(mRemotePath) + "-chunking-" + Math.abs((new Random()).nextInt(9000)+1000) + "-" ; + long chunkCount = (long) Math.ceil((double)file.length() / CHUNK_SIZE); + for (int chunkIndex = 0; chunkIndex < chunkCount ; chunkIndex++, offset += CHUNK_SIZE) { + if (mPutMethod != null) { + mPutMethod.releaseConnection(); // let the connection available for other methods + } + mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex); + mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER); + ((ChunkFromFileChannelRequestEntity)mEntity).setOffset(offset); + mPutMethod.setRequestEntity(mEntity); + status = client.executeMethod(mPutMethod); + client.exhaustResponse(mPutMethod.getResponseBodyAsStream()); + Log.d(TAG, "Upload of " + mStoragePath + " to " + mRemotePath + ", chunk index " + chunkIndex + ", count " + chunkCount + ", HTTP result status " + status); + if (!isSuccess(status)) + break; + } + + } finally { + if (channel != null) + channel.close(); + if (raf != null) + raf.close(); + if (mPutMethod != null) + mPutMethod.releaseConnection(); // let the connection available for other methods + } + return status; + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/CreateRemoteFolderOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/CreateRemoteFolderOperation.java new file mode 100644 index 00000000..f0a325ed --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/CreateRemoteFolderOperation.java @@ -0,0 +1,118 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.jackrabbit.webdav.client.methods.MkColMethod; + +import android.util.Log; + +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.utils.FileUtils; + + + +/** + * Remote operation performing the creation of a new folder in the ownCloud server. + * + * @author David A. Velasco + * @author masensio + * + */ +public class CreateRemoteFolderOperation extends RemoteOperation { + + private static final String TAG = CreateRemoteFolderOperation.class.getSimpleName(); + + private static final int READ_TIMEOUT = 10000; + private static final int CONNECTION_TIMEOUT = 5000; + + + protected String mRemotePath; + protected boolean mCreateFullPath; + + /** + * Constructor + * + * @param remotePath Full path to the new directory to create in the remote server. + * @param createFullPath 'True' means that all the ancestor folders should be created if don't exist yet. + */ + public CreateRemoteFolderOperation(String remotePath, boolean createFullPath) { + mRemotePath = remotePath; + mCreateFullPath = createFullPath; + } + + /** + * Performs the operation + * + * @param client Client object to communicate with the remote ownCloud server. + */ + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + RemoteOperationResult result = null; + MkColMethod mkcol = null; + + boolean noInvalidChars = FileUtils.isValidPath(mRemotePath); + if (noInvalidChars) { + try { + mkcol = new MkColMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); + int status = client.executeMethod(mkcol, READ_TIMEOUT, CONNECTION_TIMEOUT); + if (!mkcol.succeeded() && mkcol.getStatusCode() == HttpStatus.SC_CONFLICT && mCreateFullPath) { + result = createParentFolder(FileUtils.getParentPath(mRemotePath), client); + status = client.executeMethod(mkcol, READ_TIMEOUT, CONNECTION_TIMEOUT); // second (and last) try + } + + result = new RemoteOperationResult(mkcol.succeeded(), status, mkcol.getResponseHeaders()); + Log.d(TAG, "Create directory " + mRemotePath + ": " + result.getLogMessage()); + client.exhaustResponse(mkcol.getResponseBodyAsStream()); + + } catch (Exception e) { + result = new RemoteOperationResult(e); + Log.e(TAG, "Create directory " + mRemotePath + ": " + result.getLogMessage(), e); + + } finally { + if (mkcol != null) + mkcol.releaseConnection(); + } + } else { + result = new RemoteOperationResult(ResultCode.INVALID_CHARACTER_IN_NAME); + } + + return result; + } + + + private RemoteOperationResult createParentFolder(String parentPath, OwnCloudClient client) { + RemoteOperation operation = new CreateRemoteFolderOperation(parentPath, + mCreateFullPath); + return operation.execute(client); + } + + + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/DownloadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/DownloadRemoteFileOperation.java new file mode 100644 index 00000000..35f99f51 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/DownloadRemoteFileOperation.java @@ -0,0 +1,179 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.http.HttpStatus; + +import android.util.Log; + +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.OperationCancelledException; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; + +/** + * Remote operation performing the download of a remote file in the ownCloud server. + * + * @author David A. Velasco + * @author masensio + */ + +public class DownloadRemoteFileOperation extends RemoteOperation { + + private static final String TAG = DownloadRemoteFileOperation.class.getSimpleName(); + + private Set mDataTransferListeners = new HashSet(); + private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false); + //private long mModificationTimestamp = 0; + private GetMethod mGet; + + private String mRemotePath; + private String mDownloadFolderPath; + + public DownloadRemoteFileOperation(String remotePath, String downloadFolderPath) { + mRemotePath = remotePath; + mDownloadFolderPath = downloadFolderPath; + } + + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + RemoteOperationResult result = null; + + /// download will be performed to a temporal file, then moved to the final location + File tmpFile = new File(getTmpPath()); + + /// perform the download + try { + tmpFile.getParentFile().mkdirs(); + int status = downloadFile(client, tmpFile); + result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null)); + Log.i(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage()); + + } catch (Exception e) { + result = new RemoteOperationResult(e); + Log.e(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage(), e); + } + + return result; + } + + + protected int downloadFile(OwnCloudClient client, File targetFile) throws HttpException, IOException, OperationCancelledException { + int status = -1; + boolean savedFile = false; + mGet = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); + Iterator it = null; + + FileOutputStream fos = null; + try { + status = client.executeMethod(mGet); + if (isSuccess(status)) { + targetFile.createNewFile(); + BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream()); + fos = new FileOutputStream(targetFile); + long transferred = 0; + + Header contentLength = mGet.getResponseHeader("Content-Length"); + long totalToTransfer = (contentLength != null && contentLength.getValue().length() >0) ? Long.parseLong(contentLength.getValue()) : 0; + + byte[] bytes = new byte[4096]; + int readResult = 0; + while ((readResult = bis.read(bytes)) != -1) { + synchronized(mCancellationRequested) { + if (mCancellationRequested.get()) { + mGet.abort(); + throw new OperationCancelledException(); + } + } + fos.write(bytes, 0, readResult); + transferred += readResult; + synchronized (mDataTransferListeners) { + it = mDataTransferListeners.iterator(); + while (it.hasNext()) { + it.next().onTransferProgress(readResult, transferred, totalToTransfer, targetFile.getName()); + } + } + } + savedFile = true; + /* + Header modificationTime = mGet.getResponseHeader("Last-Modified"); + if (modificationTime != null) { + Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue()); + mModificationTimestamp = (d != null) ? d.getTime() : 0; + } + */ + + } else { + client.exhaustResponse(mGet.getResponseBodyAsStream()); + } + + } finally { + if (fos != null) fos.close(); + if (!savedFile && targetFile.exists()) { + targetFile.delete(); + } + mGet.releaseConnection(); // let the connection available for other methods + } + return status; + } + + private boolean isSuccess(int status) { + return (status == HttpStatus.SC_OK); + } + + private String getTmpPath() { + return mDownloadFolderPath + mRemotePath; + } + + public void addDatatransferProgressListener (OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.add(listener); + } + } + + public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.remove(listener); + } + } + + public void cancel() { + mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it + } +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/ExistenceCheckRemoteOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/ExistenceCheckRemoteOperation.java new file mode 100644 index 00000000..d4b49f91 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/ExistenceCheckRemoteOperation.java @@ -0,0 +1,104 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.commons.httpclient.methods.HeadMethod; + +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; + +import android.content.Context; +import android.net.ConnectivityManager; +import android.util.Log; + +/** + * Operation to check the existence or absence of a path in a remote server. + * + * @author David A. Velasco + */ +public class ExistenceCheckRemoteOperation extends RemoteOperation { + + /** Maximum time to wait for a response from the server in MILLISECONDs. */ + public static final int TIMEOUT = 10000; + + private static final String TAG = ExistenceCheckRemoteOperation.class.getSimpleName(); + + private String mPath; + private Context mContext; + private boolean mSuccessIfAbsent; + + + /** + * Full constructor. Success of the operation will depend upon the value of successIfAbsent. + * + * @param path Path to append to the URL owned by the client instance. + * @param context Android application context. + * @param successIfAbsent When 'true', the operation finishes in success if the path does NOT exist in the remote server (HTTP 404). + */ + public ExistenceCheckRemoteOperation(String path, Context context, boolean successIfAbsent) { + mPath = (path != null) ? path : ""; + mContext = context; + mSuccessIfAbsent = successIfAbsent; + } + + + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + if (!isOnline()) { + return new RemoteOperationResult(RemoteOperationResult.ResultCode.NO_NETWORK_CONNECTION); + } + RemoteOperationResult result = null; + HeadMethod head = null; + try { + head = new HeadMethod(client.getBaseUri() + WebdavUtils.encodePath(mPath)); + int status = client.executeMethod(head, TIMEOUT, TIMEOUT); + client.exhaustResponse(head.getResponseBodyAsStream()); + boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent); + result = new RemoteOperationResult(success, status, head.getResponseHeaders()); + Log.d(TAG, "Existence check for " + client.getBaseUri() + WebdavUtils.encodePath(mPath) + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + "finished with HTTP status " + status + (!success?"(FAIL)":"")); + + } catch (Exception e) { + result = new RemoteOperationResult(e); + Log.e(TAG, "Existence check for " + client.getBaseUri() + WebdavUtils.encodePath(mPath) + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + ": " + result.getLogMessage(), result.getException()); + + } finally { + if (head != null) + head.releaseConnection(); + } + return result; + } + + private boolean isOnline() { + ConnectivityManager cm = (ConnectivityManager) mContext + .getSystemService(Context.CONNECTIVITY_SERVICE); + return cm != null && cm.getActiveNetworkInfo() != null + && cm.getActiveNetworkInfo().isConnectedOrConnecting(); + } + + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/GetUserNameRemoteOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/GetUserNameRemoteOperation.java new file mode 100644 index 00000000..9f5c0ff6 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/GetUserNameRemoteOperation.java @@ -0,0 +1,127 @@ + +/* ownCloud Android client application + * Copyright (C) 2012-2013 ownCloud Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2, + * as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + */ +package com.owncloud.android.lib.operations.remote; + +import java.io.IOException; + +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.http.HttpStatus; +import org.json.JSONException; +import org.json.JSONObject; + +import android.util.Log; + +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; + + +/** + * @author masensio + * + * Get the UserName for a SAML connection, from a JSON with the format: + * id + * display-name + * email + */ + +public class GetUserNameRemoteOperation extends RemoteOperation { + + private static final String TAG = GetUserNameRemoteOperation.class.getSimpleName(); + + // HEADER + private static final String HEADER_OCS_API = "OCS-APIREQUEST"; + private static final String HEADER_OCS_API_VALUE = "true"; + + // OCS Route + private static final String OCS_ROUTE ="/index.php/ocs/cloud/user?format=json"; + + // JSON Node names + private static final String NODE_OCS = "ocs"; + private static final String NODE_DATA = "data"; + private static final String NODE_ID = "id"; + private static final String NODE_DISPLAY_NAME= "display-name"; + private static final String NODE_EMAIL= "email"; + + private String mUserName; + + public String getUserName() { + return mUserName; + } + + + public GetUserNameRemoteOperation() { + } + + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + RemoteOperationResult result = null; + int status = -1; + + // Get Method + GetMethod get = new GetMethod(client.getBaseUri() + OCS_ROUTE); + Log.d(TAG, "URL ------> " + client.getBaseUri() + OCS_ROUTE); + // Add the Header + get.addRequestHeader(HEADER_OCS_API, HEADER_OCS_API_VALUE); + + //Get the user + try { + status = client.executeMethod(get); + if(isSuccess(status)) { + Log.d(TAG, "Obtain RESPONSE"); + String response = get.getResponseBodyAsString(); + + Log.d(TAG, "GET RESPONSE.................... " + response); + + // Parse the response + JSONObject respJSON = new JSONObject(response); + JSONObject respOCS = respJSON.getJSONObject(NODE_OCS); + JSONObject respData = respOCS.getJSONObject(NODE_DATA); + String id = respData.getString(NODE_ID); + String displayName = respData.getString(NODE_DISPLAY_NAME); + String email = respData.getString(NODE_EMAIL); + + // Result + result = new RemoteOperationResult(isSuccess(status), status, (get != null ? get.getResponseHeaders() : null)); + mUserName = displayName; + + Log.d(TAG, "Response: " + id + " - " + displayName + " - " + email); + + } + } catch (HttpException e) { + result = new RemoteOperationResult(e); + e.printStackTrace(); + } catch (IOException e) { + result = new RemoteOperationResult(e); + e.printStackTrace(); + } catch (JSONException e) { + result = new RemoteOperationResult(e); + e.printStackTrace(); + } finally { + get.releaseConnection(); + } + + return result; + } + + private boolean isSuccess(int status) { + return (status == HttpStatus.SC_OK); + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/ReadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/ReadRemoteFileOperation.java new file mode 100644 index 00000000..0410cd62 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/ReadRemoteFileOperation.java @@ -0,0 +1,115 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ +package com.owncloud.android.lib.operations.remote; + +import java.util.ArrayList; + +import org.apache.http.HttpStatus; +import org.apache.jackrabbit.webdav.DavConstants; +import org.apache.jackrabbit.webdav.MultiStatus; +import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; + +import android.util.Log; + +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.webdav.WebdavEntry; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.RemoteFile; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; + + +/** + * Remote operation performing the read a file from the ownCloud server. + * + * @author David A. Velasco + * @author masensio + */ + +public class ReadRemoteFileOperation extends RemoteOperation { + + private static final String TAG = ReadRemoteFileOperation.class.getSimpleName(); + private static final int SYNC_READ_TIMEOUT = 10000; + private static final int SYNC_CONNECTION_TIMEOUT = 5000; + + private String mRemotePath; + + + /** + * Constructor + * + * @param remotePath Remote path of the file. + */ + public ReadRemoteFileOperation(String remotePath) { + mRemotePath = remotePath; + } + + /** + * Performs the read operation. + * + * @param client Client object to communicate with the remote ownCloud server. + */ + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + PropFindMethod propfind = null; + RemoteOperationResult result = null; + + /// take the duty of check the server for the current state of the file there + try { + propfind = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath), + DavConstants.PROPFIND_ALL_PROP, + DavConstants.DEPTH_0); + int status; + status = client.executeMethod(propfind, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); + + boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS; + if (isMultiStatus) { + // Parse response + MultiStatus resp = propfind.getResponseBodyAsMultiStatus(); + WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath()); + RemoteFile remoteFile = new RemoteFile(we); + ArrayList files = new ArrayList(); + files.add(remoteFile); + + // Result of the operation + result = new RemoteOperationResult(true, status, propfind.getResponseHeaders()); + result.setData(files); + + } else { + client.exhaustResponse(propfind.getResponseBodyAsStream()); + result = new RemoteOperationResult(false, status, propfind.getResponseHeaders()); + } + + } catch (Exception e) { + result = new RemoteOperationResult(e); + e.printStackTrace(); + Log.e(TAG, "Synchronizing file " + mRemotePath + ": " + result.getLogMessage(), result.getException()); + } finally { + if (propfind != null) + propfind.releaseConnection(); + } + return result; + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/ReadRemoteFolderOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/ReadRemoteFolderOperation.java new file mode 100644 index 00000000..521d73e7 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/ReadRemoteFolderOperation.java @@ -0,0 +1,169 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import java.util.ArrayList; + +import org.apache.http.HttpStatus; +import org.apache.jackrabbit.webdav.DavConstants; +import org.apache.jackrabbit.webdav.MultiStatus; +import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; + +import android.util.Log; + +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.webdav.WebdavEntry; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.RemoteFile; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; + +/** + * Remote operation performing the read of remote file or folder in the ownCloud server. + * + * @author David A. Velasco + * @author masensio + */ + +public class ReadRemoteFolderOperation extends RemoteOperation { + + private static final String TAG = ReadRemoteFolderOperation.class.getSimpleName(); + + private String mRemotePath; + private ArrayList mFolderAndFiles; + + /** + * Constructor + * + * @param remotePath Remote path of the file. + */ + public ReadRemoteFolderOperation(String remotePath) { + mRemotePath = remotePath; + } + + /** + * Performs the read operation. + * + * @param client Client object to communicate with the remote ownCloud server. + */ + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + RemoteOperationResult result = null; + PropFindMethod query = null; + + try { + // remote request + query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath), + DavConstants.PROPFIND_ALL_PROP, + DavConstants.DEPTH_1); + int status = client.executeMethod(query); + + // check and process response + if (isMultiStatus(status)) { + // get data from remote folder + MultiStatus dataInServer = query.getResponseBodyAsMultiStatus(); + readData(dataInServer, client); + + // Result of the operation + result = new RemoteOperationResult(true, status, query.getResponseHeaders()); + // Add data to the result + if (result.isSuccess()) { + result.setData(mFolderAndFiles); + } + } else { + // synchronization failed + client.exhaustResponse(query.getResponseBodyAsStream()); + result = new RemoteOperationResult(false, status, query.getResponseHeaders()); + } + + } catch (Exception e) { + result = new RemoteOperationResult(e); + + + } finally { + if (query != null) + query.releaseConnection(); // let the connection available for other methods + if (result.isSuccess()) { + Log.i(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage()); + } else { + if (result.isException()) { + Log.e(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage(), result.getException()); + } else { + Log.e(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage()); + } + } + + } + return result; + } + + public boolean isMultiStatus(int status) { + return (status == HttpStatus.SC_MULTI_STATUS); + } + + /** + * Read the data retrieved from the server about the contents of the target folder + * + * + * @param dataInServer Full response got from the server with the data of the target + * folder and its direct children. + * @param client Client instance to the remote server where the data were + * retrieved. + * @return + */ + private void readData(MultiStatus dataInServer, OwnCloudClient client) { + mFolderAndFiles = new ArrayList(); + + // parse data from remote folder + WebdavEntry we = new WebdavEntry(dataInServer.getResponses()[0], client.getBaseUri().getPath()); + mFolderAndFiles.add(fillOCFile(we)); + + // loop to update every child + RemoteFile remoteFile = null; + for (int i = 1; i < dataInServer.getResponses().length; ++i) { + /// new OCFile instance with the data from the server + we = new WebdavEntry(dataInServer.getResponses()[i], client.getBaseUri().getPath()); + remoteFile = fillOCFile(we); + mFolderAndFiles.add(remoteFile); + } + + } + + /** + * Creates and populates a new {@link RemoteFile} object with the data read from the server. + * + * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder). + * @return New OCFile instance representing the remote resource described by we. + */ + private RemoteFile fillOCFile(WebdavEntry we) { + RemoteFile file = new RemoteFile(we.decodedPath()); + file.setCreationTimestamp(we.createTimestamp()); + file.setLength(we.contentLength()); + file.setMimeType(we.contentType()); + file.setModifiedTimestamp(we.modifiedTimestamp()); + file.setEtag(we.etag()); + return file; + } +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/RemoveRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/RemoveRemoteFileOperation.java new file mode 100644 index 00000000..b80fa526 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/RemoveRemoteFileOperation.java @@ -0,0 +1,90 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import org.apache.commons.httpclient.HttpStatus; +import org.apache.jackrabbit.webdav.client.methods.DeleteMethod; + +import android.util.Log; + +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; + +/** + * Remote operation performing the removal of a remote file or folder in the ownCloud server. + * + * @author David A. Velasco + * @author masensio + */ +public class RemoveRemoteFileOperation extends RemoteOperation { + private static final String TAG = RemoveRemoteFileOperation.class.getSimpleName(); + + private static final int REMOVE_READ_TIMEOUT = 10000; + private static final int REMOVE_CONNECTION_TIMEOUT = 5000; + + private String mRemotePath; + + /** + * Constructor + * + * @param remotePath RemotePath of the remote file or folder to remove from the server + */ + public RemoveRemoteFileOperation(String remotePath) { + mRemotePath = remotePath; + } + + /** + * Performs the rename operation. + * + * @param client Client object to communicate with the remote ownCloud server. + */ + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + RemoteOperationResult result = null; + DeleteMethod delete = null; + + try { + delete = new DeleteMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); + int status = client.executeMethod(delete, REMOVE_READ_TIMEOUT, REMOVE_CONNECTION_TIMEOUT); + + delete.getResponseBodyAsString(); // exhaust the response, although not interesting + result = new RemoteOperationResult((delete.succeeded() || status == HttpStatus.SC_NOT_FOUND), status, delete.getResponseHeaders()); + Log.i(TAG, "Remove " + mRemotePath + ": " + result.getLogMessage()); + + } catch (Exception e) { + result = new RemoteOperationResult(e); + Log.e(TAG, "Remove " + mRemotePath + ": " + result.getLogMessage(), e); + + } finally { + if (delete != null) + delete.releaseConnection(); + } + + return result; + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/RenameRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/RenameRemoteFileOperation.java new file mode 100644 index 00000000..7bc5f0cc --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/RenameRemoteFileOperation.java @@ -0,0 +1,153 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import java.io.File; + +import org.apache.jackrabbit.webdav.client.methods.DavMethodBase; + +import android.util.Log; + +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.utils.FileUtils; + + +/** + * Remote operation performing the rename of a remote file or folder in the ownCloud server. + * + * @author David A. Velasco + * @author masensio + */ +public class RenameRemoteFileOperation extends RemoteOperation { + + private static final String TAG = RenameRemoteFileOperation.class.getSimpleName(); + + private static final int RENAME_READ_TIMEOUT = 10000; + private static final int RENAME_CONNECTION_TIMEOUT = 5000; + + private String mOldName; + private String mOldRemotePath; + private String mNewName; + private String mNewRemotePath; + + + /** + * Constructor + * + * @param oldName Old name of the file. + * @param oldRemotePath Old remote path of the file. + * @param newName New name to set as the name of file. + * @param isFolder 'true' for folder and 'false' for files + */ + public RenameRemoteFileOperation(String oldName, String oldRemotePath, String newName, boolean isFolder) { + mOldName = oldName; + mOldRemotePath = oldRemotePath; + mNewName = newName; + + String parent = (new File(mOldRemotePath)).getParent(); + parent = (parent.endsWith(FileUtils.PATH_SEPARATOR)) ? parent : parent + FileUtils.PATH_SEPARATOR; + mNewRemotePath = parent + mNewName; + if (isFolder) { + mNewRemotePath += FileUtils.PATH_SEPARATOR; + } + } + + /** + * Performs the rename operation. + * + * @param client Client object to communicate with the remote ownCloud server. + */ + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + RemoteOperationResult result = null; + + LocalMoveMethod move = null; + + boolean noInvalidChars = FileUtils.isValidPath(mNewRemotePath); + + if (noInvalidChars) { + try { + + if (mNewName.equals(mOldName)) { + return new RemoteOperationResult(ResultCode.OK); + } + + + // check if a file with the new name already exists + if (client.existsFile(mNewRemotePath)) { + return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE); + } + + move = new LocalMoveMethod( client.getBaseUri() + WebdavUtils.encodePath(mOldRemotePath), + client.getBaseUri() + WebdavUtils.encodePath(mNewRemotePath)); + int status = client.executeMethod(move, RENAME_READ_TIMEOUT, RENAME_CONNECTION_TIMEOUT); + + move.getResponseBodyAsString(); // exhaust response, although not interesting + result = new RemoteOperationResult(move.succeeded(), status, move.getResponseHeaders()); + Log.i(TAG, "Rename " + mOldRemotePath + " to " + mNewRemotePath + ": " + result.getLogMessage()); + + } catch (Exception e) { + result = new RemoteOperationResult(e); + Log.e(TAG, "Rename " + mOldRemotePath + " to " + ((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " + result.getLogMessage(), e); + + } finally { + if (move != null) + move.releaseConnection(); + } + } else { + result = new RemoteOperationResult(ResultCode.INVALID_CHARACTER_IN_NAME); + } + + return result; + } + + /** + * Move operation + * + */ + private class LocalMoveMethod extends DavMethodBase { + + public LocalMoveMethod(String uri, String dest) { + super(uri); + addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest)); + } + + @Override + public String getName() { + return "MOVE"; + } + + @Override + protected boolean isSuccess(int status) { + return status == 201 || status == 204; + } + + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/operations/remote/UploadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/lib/operations/remote/UploadRemoteFileOperation.java new file mode 100644 index 00000000..4872aaf1 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/operations/remote/UploadRemoteFileOperation.java @@ -0,0 +1,154 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.operations.remote; + +import java.io.File; +import java.io.IOException; +import java.util.HashSet; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; + +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.methods.RequestEntity; +import org.apache.http.HttpStatus; + +import com.owncloud.android.lib.network.FileRequestEntity; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.network.ProgressiveDataTransferer; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.OperationCancelledException; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; + +/** + * Remote operation performing the upload of a remote file to the ownCloud server. + * + * @author David A. Velasco + * @author masensio + */ + +public class UploadRemoteFileOperation extends RemoteOperation { + + + protected String mStoragePath; + protected String mRemotePath; + protected String mMimeType; + protected PutMethod mPutMethod = null; + + private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false); + protected Set mDataTransferListeners = new HashSet(); + + protected RequestEntity mEntity = null; + + public UploadRemoteFileOperation(String storagePath, String remotePath, String mimeType) { + mStoragePath = storagePath; + mRemotePath = remotePath; + mMimeType = mimeType; + } + + @Override + protected RemoteOperationResult run(OwnCloudClient client) { + RemoteOperationResult result = null; + + try { + // / perform the upload + synchronized (mCancellationRequested) { + if (mCancellationRequested.get()) { + throw new OperationCancelledException(); + } else { + mPutMethod = new PutMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); + } + } + + int status = uploadFile(client); + + result = new RemoteOperationResult(isSuccess(status), status, (mPutMethod != null ? mPutMethod.getResponseHeaders() : null)); + + } catch (Exception e) { + // TODO something cleaner with cancellations + if (mCancellationRequested.get()) { + result = new RemoteOperationResult(new OperationCancelledException()); + } else { + result = new RemoteOperationResult(e); + } + } + return result; + } + + public boolean isSuccess(int status) { + return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT)); + } + + protected int uploadFile(OwnCloudClient client) throws HttpException, IOException, OperationCancelledException { + int status = -1; + try { + File f = new File(mStoragePath); + mEntity = new FileRequestEntity(f, mMimeType); + synchronized (mDataTransferListeners) { + ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners); + } + mPutMethod.setRequestEntity(mEntity); + status = client.executeMethod(mPutMethod); + client.exhaustResponse(mPutMethod.getResponseBodyAsStream()); + + } finally { + mPutMethod.releaseConnection(); // let the connection available for other methods + } + return status; + } + + public Set getDataTransferListeners() { + return mDataTransferListeners; + } + + public void addDatatransferProgressListener (OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.add(listener); + } + if (mEntity != null) { + ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener); + } + } + + public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { + synchronized (mDataTransferListeners) { + mDataTransferListeners.remove(listener); + } + if (mEntity != null) { + ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener); + } + } + + public void cancel() { + synchronized (mCancellationRequested) { + mCancellationRequested.set(true); + if (mPutMethod != null) + mPutMethod.abort(); + } + } + +} diff --git a/oc_framework/src/com/owncloud/android/lib/utils/FileUtils.java b/oc_framework/src/com/owncloud/android/lib/utils/FileUtils.java new file mode 100644 index 00000000..6924c374 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/utils/FileUtils.java @@ -0,0 +1,78 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.utils; + +import java.io.File; + +import android.util.Log; + +public class FileUtils { + + public static final String PATH_SEPARATOR = "/"; + + + public static String getParentPath(String remotePath) { + String parentPath = new File(remotePath).getParent(); + parentPath = parentPath.endsWith(PATH_SEPARATOR) ? parentPath : parentPath + PATH_SEPARATOR; + return parentPath; + } + + /** + * Validate the fileName to detect if contains any forbidden character: / , \ , < , > , : , " , | , ? , * + * @param fileName + * @return + */ + public static boolean isValidName(String fileName) { + boolean result = true; + + Log.d("FileUtils", "fileName =======" + fileName); + if (fileName.contains(PATH_SEPARATOR) || + fileName.contains("\\") || fileName.contains("<") || fileName.contains(">") || + fileName.contains(":") || fileName.contains("\"") || fileName.contains("|") || + fileName.contains("?") || fileName.contains("*")) { + result = false; + } + return result; + } + + /** + * Validate the path to detect if contains any forbidden character: \ , < , > , : , " , | , ? , * + * @param path + * @return + */ + public static boolean isValidPath(String path) { + boolean result = true; + + Log.d("FileUtils", "path ....... " + path); + if (path.contains("\\") || path.contains("<") || path.contains(">") || + path.contains(":") || path.contains("\"") || path.contains("|") || + path.contains("?") || path.contains("*")) { + result = false; + } + return result; + } + + +} diff --git a/oc_framework/src/com/owncloud/android/lib/utils/OwnCloudVersion.java b/oc_framework/src/com/owncloud/android/lib/utils/OwnCloudVersion.java new file mode 100644 index 00000000..542540c8 --- /dev/null +++ b/oc_framework/src/com/owncloud/android/lib/utils/OwnCloudVersion.java @@ -0,0 +1,92 @@ +/* ownCloud Android Library is available under MIT license + * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) + * Copyright (C) 2012 Bartek Przybylski + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS + * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN + * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + */ + +package com.owncloud.android.lib.utils; + +public class OwnCloudVersion implements Comparable { + public static final OwnCloudVersion owncloud_v1 = new OwnCloudVersion( + 0x010000); + public static final OwnCloudVersion owncloud_v2 = new OwnCloudVersion( + 0x020000); + public static final OwnCloudVersion owncloud_v3 = new OwnCloudVersion( + 0x030000); + public static final OwnCloudVersion owncloud_v4 = new OwnCloudVersion( + 0x040000); + public static final OwnCloudVersion owncloud_v4_5 = new OwnCloudVersion( + 0x040500); + + // format is in version + // 0xAABBCC + // for version AA.BB.CC + // ie version 2.0.3 will be stored as 0x030003 + private int mVersion; + private boolean mIsValid; + + public OwnCloudVersion(int version) { + mVersion = version; + mIsValid = true; + } + + public OwnCloudVersion(String version) { + mVersion = 0; + mIsValid = false; + parseVersionString(version); + } + + public String toString() { + return ((mVersion >> 16) % 256) + "." + ((mVersion >> 8) % 256) + "." + + ((mVersion) % 256); + } + + public boolean isVersionValid() { + return mIsValid; + } + + @Override + public int compareTo(OwnCloudVersion another) { + return another.mVersion == mVersion ? 0 + : another.mVersion < mVersion ? 1 : -1; + } + + private void parseVersionString(String version) { + try { + String[] nums = version.split("\\."); + if (nums.length > 0) { + mVersion += Integer.parseInt(nums[0]); + } + mVersion = mVersion << 8; + if (nums.length > 1) { + mVersion += Integer.parseInt(nums[1]); + } + mVersion = mVersion << 8; + if (nums.length > 2) { + mVersion += Integer.parseInt(nums[2]); + } + mIsValid = true; + } catch (Exception e) { + mIsValid = false; + } + } +} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/accounts/AccountTypeUtils.java b/oc_framework/src/com/owncloud/android/oc_framework/accounts/AccountTypeUtils.java deleted file mode 100644 index 5f814625..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/accounts/AccountTypeUtils.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.accounts; - -/** - * @author masensio - * @author David A. Velasco - */ -public class AccountTypeUtils { - - public static String getAuthTokenTypePass(String accountType) { - return accountType + ".password"; - } - - public static String getAuthTokenTypeAccessToken(String accountType) { - return accountType + ".oauth2.access_token"; - } - - public static String getAuthTokenTypeRefreshToken(String accountType) { - return accountType + ".oauth2.refresh_token"; - } - - public static String getAuthTokenTypeSamlSessionCookie(String accountType) { - return accountType + ".saml.web_sso.session_cookie"; - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/accounts/AccountUtils.java b/oc_framework/src/com/owncloud/android/oc_framework/accounts/AccountUtils.java deleted file mode 100644 index 5ef2fec7..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/accounts/AccountUtils.java +++ /dev/null @@ -1,135 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.accounts; - -import com.owncloud.android.oc_framework.utils.OwnCloudVersion; - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.accounts.AccountsException; -import android.content.Context; - -public class AccountUtils { - public static final String WEBDAV_PATH_1_2 = "/webdav/owncloud.php"; - public static final String WEBDAV_PATH_2_0 = "/files/webdav.php"; - public static final String WEBDAV_PATH_4_0 = "/remote.php/webdav"; - private static final String ODAV_PATH = "/remote.php/odav"; - private static final String SAML_SSO_PATH = "/remote.php/webdav"; - public static final String CARDDAV_PATH_2_0 = "/apps/contacts/carddav.php"; - public static final String CARDDAV_PATH_4_0 = "/remote/carddav.php"; - public static final String STATUS_PATH = "/status.php"; - - /** - * - * @param version version of owncloud - * @return webdav path for given OC version, null if OC version unknown - */ - public static String getWebdavPath(OwnCloudVersion version, boolean supportsOAuth, boolean supportsSamlSso) { - if (version != null) { - if (supportsOAuth) { - return ODAV_PATH; - } - if (supportsSamlSso) { - return SAML_SSO_PATH; - } - if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0) - return WEBDAV_PATH_4_0; - if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0 - || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0) - return WEBDAV_PATH_2_0; - if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0) - return WEBDAV_PATH_1_2; - } - return null; - } - -// /** -// * Returns the proper URL path to access the WebDAV interface of an ownCloud server, -// * according to its version and the authorization method used. -// * -// * @param version Version of ownCloud server. -// * @param authTokenType Authorization token type, matching some of the AUTH_TOKEN_TYPE_* constants in {@link AccountAuthenticator}. -// * @return WebDAV path for given OC version and authorization method, null if OC version is unknown. -// */ -// public static String getWebdavPath(OwnCloudVersion version, String authTokenType) { -// if (version != null) { -// if (MainApp.getAuthTokenTypeAccessToken().equals(authTokenType)) { -// return ODAV_PATH; -// } -// if (MainApp.getAuthTokenTypeSamlSessionCookie().equals(authTokenType)) { -// return SAML_SSO_PATH; -// } -// if (version.compareTo(OwnCloudVersion.owncloud_v4) >= 0) -// return WEBDAV_PATH_4_0; -// if (version.compareTo(OwnCloudVersion.owncloud_v3) >= 0 -// || version.compareTo(OwnCloudVersion.owncloud_v2) >= 0) -// return WEBDAV_PATH_2_0; -// if (version.compareTo(OwnCloudVersion.owncloud_v1) >= 0) -// return WEBDAV_PATH_1_2; -// } -// return null; -// } - - /** - * Constructs full url to host and webdav resource basing on host version - * @param context - * @param account - * @return url or null on failure - * @throws AccountNotFoundException When 'account' is unknown for the AccountManager - */ - public static String constructFullURLForAccount(Context context, Account account) throws AccountNotFoundException { - AccountManager ama = AccountManager.get(context); - String baseurl = ama.getUserData(account, OwnCloudAccount.Constants.KEY_OC_BASE_URL); - String strver = ama.getUserData(account, OwnCloudAccount.Constants.KEY_OC_VERSION); - boolean supportsOAuth = (ama.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_OAUTH2) != null); - boolean supportsSamlSso = (ama.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null); - OwnCloudVersion ver = new OwnCloudVersion(strver); - String webdavpath = getWebdavPath(ver, supportsOAuth, supportsSamlSso); - - if (baseurl == null || webdavpath == null) - throw new AccountNotFoundException(account, "Account not found", null); - - return baseurl + webdavpath; - } - - - public static class AccountNotFoundException extends AccountsException { - - /** Generated - should be refreshed every time the class changes!! */ - private static final long serialVersionUID = -1684392454798508693L; - - private Account mFailedAccount; - - public AccountNotFoundException(Account failedAccount, String message, Throwable cause) { - super(message, cause); - mFailedAccount = failedAccount; - } - - public Account getFailedAccount() { - return mFailedAccount; - } - } -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/accounts/OwnCloudAccount.java b/oc_framework/src/com/owncloud/android/oc_framework/accounts/OwnCloudAccount.java deleted file mode 100644 index 2032504c..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/accounts/OwnCloudAccount.java +++ /dev/null @@ -1,112 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.accounts; - -import android.accounts.Account; -import android.os.Parcel; -import android.os.Parcelable; - -/** - * Account with extra information specific for ownCloud accounts. - * - * TODO integrate in the main app - * - * @author David A. Velasco - */ -public class OwnCloudAccount extends Account { - - public static class Constants { - /** - * Value under this key should handle path to webdav php script. Will be - * removed and usage should be replaced by combining - * {@link com.owncloud.android.authentication.AuthenticatorActivity.KEY_OC_BASE_URL} and - * {@link com.owncloud.android.oc_framework.utils.utils.OwnCloudVersion} - * - * @deprecated - */ - public static final String KEY_OC_URL = "oc_url"; - /** - * Version should be 3 numbers separated by dot so it can be parsed by - * {@link com.owncloud.android.oc_framework.utils.utils.OwnCloudVersion} - */ - public static final String KEY_OC_VERSION = "oc_version"; - /** - * Base url should point to owncloud installation without trailing / ie: - * http://server/path or https://owncloud.server - */ - public static final String KEY_OC_BASE_URL = "oc_base_url"; - /** - * Flag signaling if the ownCloud server can be accessed with OAuth2 access tokens. - */ - public static final String KEY_SUPPORTS_OAUTH2 = "oc_supports_oauth2"; - /** - * Flag signaling if the ownCloud server can be accessed with session cookies from SAML-based web single-sign-on. - */ - public static final String KEY_SUPPORTS_SAML_WEB_SSO = "oc_supports_saml_web_sso"; - } - - private String mAuthTokenType; - - public OwnCloudAccount(String name, String type, String authTokenType) { - super(name, type); - // TODO validate authTokentype as supported - mAuthTokenType = authTokenType; - } - - /** - * Reconstruct from parcel - * - * @param source The source parcel - */ - public OwnCloudAccount(Parcel source) { - super(source); - mAuthTokenType = source.readString(); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - super.writeToParcel(dest, flags); - dest.writeString(mAuthTokenType); - } - - - public String getAuthTokenType() { - return mAuthTokenType; - } - - - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public OwnCloudAccount createFromParcel(Parcel source) { - return new OwnCloudAccount(source); - } - - @Override - public OwnCloudAccount [] newArray(int size) { - return new OwnCloudAccount[size]; - } - }; - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/AdvancedSslSocketFactory.java b/oc_framework/src/com/owncloud/android/oc_framework/network/AdvancedSslSocketFactory.java deleted file mode 100644 index 89b8b236..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/AdvancedSslSocketFactory.java +++ /dev/null @@ -1,296 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network; - -import java.io.IOException; -import java.net.InetAddress; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.net.SocketAddress; -import java.net.UnknownHostException; -//import java.security.Provider; -import java.security.cert.X509Certificate; -//import java.util.Enumeration; - -import javax.net.SocketFactory; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -//import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; - -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.commons.httpclient.params.HttpConnectionParams; -import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; -import org.apache.http.conn.ssl.X509HostnameVerifier; - -//import android.os.Build; -import android.util.Log; - - - -/** - * AdvancedSSLProtocolSocketFactory allows to create SSL {@link Socket}s with - * a custom SSLContext and an optional Hostname Verifier. - * - * @author David A. Velasco - */ - -public class AdvancedSslSocketFactory implements ProtocolSocketFactory { - - private static final String TAG = AdvancedSslSocketFactory.class.getSimpleName(); - - private SSLContext mSslContext = null; - private AdvancedX509TrustManager mTrustManager = null; - private X509HostnameVerifier mHostnameVerifier = null; - - public SSLContext getSslContext() { - return mSslContext; - } - - /** - * Constructor for AdvancedSSLProtocolSocketFactory. - */ - public AdvancedSslSocketFactory(SSLContext sslContext, AdvancedX509TrustManager trustManager, X509HostnameVerifier hostnameVerifier) { - if (sslContext == null) - throw new IllegalArgumentException("AdvancedSslSocketFactory can not be created with a null SSLContext"); - if (trustManager == null) - throw new IllegalArgumentException("AdvancedSslSocketFactory can not be created with a null Trust Manager"); - mSslContext = sslContext; - mTrustManager = trustManager; - mHostnameVerifier = hostnameVerifier; - } - - /** - * @see ProtocolSocketFactory#createSocket(java.lang.String,int,java.net.InetAddress,int) - */ - public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException { - Socket socket = mSslContext.getSocketFactory().createSocket(host, port, clientHost, clientPort); - verifyPeerIdentity(host, port, socket); - return socket; - } - - /* - private void logSslInfo() { - if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) { - Log.v(TAG, "SUPPORTED SSL PARAMETERS"); - logSslParameters(mSslContext.getSupportedSSLParameters()); - Log.v(TAG, "DEFAULT SSL PARAMETERS"); - logSslParameters(mSslContext.getDefaultSSLParameters()); - Log.i(TAG, "CURRENT PARAMETERS"); - Log.i(TAG, "Protocol: " + mSslContext.getProtocol()); - } - Log.i(TAG, "PROVIDER"); - logSecurityProvider(mSslContext.getProvider()); - } - - private void logSecurityProvider(Provider provider) { - Log.i(TAG, "name: " + provider.getName()); - Log.i(TAG, "version: " + provider.getVersion()); - Log.i(TAG, "info: " + provider.getInfo()); - Enumeration keys = provider.propertyNames(); - String key; - while (keys.hasMoreElements()) { - key = (String) keys.nextElement(); - Log.i(TAG, " property " + key + " : " + provider.getProperty(key)); - } - } - - private void logSslParameters(SSLParameters params) { - Log.v(TAG, "Cipher suites: "); - String [] elements = params.getCipherSuites(); - for (int i=0; i listeners); - - public void removeDatatransferProgressListener(OnDatatransferProgressListener listener); - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/ServerNameIndicator.java b/oc_framework/src/com/owncloud/android/oc_framework/network/ServerNameIndicator.java deleted file mode 100644 index e5a6d68d..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/ServerNameIndicator.java +++ /dev/null @@ -1,151 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network; - -import java.lang.ref.WeakReference; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.concurrent.atomic.AtomicReference; - -import javax.net.ssl.SSLSocket; - -import android.util.Log; - - -/** - * Enables the support of Server Name Indication if existing - * in the underlying network implementation. - * - * Build as a singleton. - * - * @author David A. Velasco - */ -public class ServerNameIndicator { - - private static final String TAG = ServerNameIndicator.class.getSimpleName(); - - private static final AtomicReference mSingleInstance = new AtomicReference(); - - private static final String METHOD_NAME = "setHostname"; - - private final WeakReference> mSSLSocketClassRef; - private final WeakReference mSetHostnameMethodRef; - - - /** - * Private constructor, class is a singleton. - * - * @param sslSocketClass Underlying implementation class of {@link SSLSocket} used to connect with the server. - * @param setHostnameMethod Name of the method to call to enable the SNI support. - */ - private ServerNameIndicator(Class sslSocketClass, Method setHostnameMethod) { - mSSLSocketClassRef = new WeakReference>(sslSocketClass); - mSetHostnameMethodRef = (setHostnameMethod == null) ? null : new WeakReference(setHostnameMethod); - } - - - /** - * Calls the {@code #setHostname(String)} method of the underlying implementation - * of {@link SSLSocket} if exists. - * - * Creates and initializes the single instance of the class when needed - * - * @param hostname The name of the server host of interest. - * @param sslSocket Client socket to connect with the server. - */ - public static void setServerNameIndication(String hostname, SSLSocket sslSocket) { - final Method setHostnameMethod = getMethod(sslSocket); - if (setHostnameMethod != null) { - try { - setHostnameMethod.invoke(sslSocket, hostname); - Log.i(TAG, "SNI done, hostname: " + hostname); - - } catch (IllegalArgumentException e) { - Log.e(TAG, "Call to SSLSocket#setHost(String) failed ", e); - - } catch (IllegalAccessException e) { - Log.e(TAG, "Call to SSLSocket#setHost(String) failed ", e); - - } catch (InvocationTargetException e) { - Log.e(TAG, "Call to SSLSocket#setHost(String) failed ", e); - } - } else { - Log.i(TAG, "SNI not supported"); - } - } - - - /** - * Gets the method to invoke trying to minimize the effective - * application of reflection. - * - * @param sslSocket Instance of the SSL socket to use in connection with server. - * @return Method to call to indicate the server name of interest to the server. - */ - private static Method getMethod(SSLSocket sslSocket) { - final Class sslSocketClass = sslSocket.getClass(); - final ServerNameIndicator instance = mSingleInstance.get(); - if (instance == null) { - return initFrom(sslSocketClass); - - } else if (instance.mSSLSocketClassRef.get() != sslSocketClass) { - // the underlying class changed - return initFrom(sslSocketClass); - - } else if (instance.mSetHostnameMethodRef == null) { - // SNI not supported - return null; - - } else { - final Method cachedSetHostnameMethod = instance.mSetHostnameMethodRef.get(); - return (cachedSetHostnameMethod == null) ? initFrom(sslSocketClass) : cachedSetHostnameMethod; - } - } - - - /** - * Singleton initializer. - * - * Uses reflection to extract and 'cache' the method to invoke to indicate the desited host name to the server side. - * - * @param sslSocketClass Underlying class providing the implementation of {@link SSLSocket}. - * @return Method to call to indicate the server name of interest to the server. - */ - private static Method initFrom(Class sslSocketClass) { - Log.i(TAG, "SSLSocket implementation: " + sslSocketClass.getCanonicalName()); - Method setHostnameMethod = null; - try { - setHostnameMethod = sslSocketClass.getMethod(METHOD_NAME, String.class); - } catch (SecurityException e) { - Log.e(TAG, "Could not access to SSLSocket#setHostname(String) method ", e); - - } catch (NoSuchMethodException e) { - Log.i(TAG, "Could not find SSLSocket#setHostname(String) method - SNI not supported"); - } - mSingleInstance.set(new ServerNameIndicator(sslSocketClass, setHostnameMethod)); - return setHostnameMethod; - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/ChunkFromFileChannelRequestEntity.java b/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/ChunkFromFileChannelRequestEntity.java deleted file mode 100644 index 6a921e91..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/ChunkFromFileChannelRequestEntity.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network.webdav; - -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.apache.commons.httpclient.methods.RequestEntity; - -import com.owncloud.android.oc_framework.network.ProgressiveDataTransferer; - -import android.util.Log; - - -/** - * A RequestEntity that represents a PIECE of a file. - * - * @author David A. Velasco - */ -public class ChunkFromFileChannelRequestEntity implements RequestEntity, ProgressiveDataTransferer { - - private static final String TAG = ChunkFromFileChannelRequestEntity.class.getSimpleName(); - - //private final File mFile; - private final FileChannel mChannel; - private final String mContentType; - private final long mChunkSize; - private final File mFile; - private long mOffset; - private long mTransferred; - Set mDataTransferListeners = new HashSet(); - private ByteBuffer mBuffer = ByteBuffer.allocate(4096); - - public ChunkFromFileChannelRequestEntity(final FileChannel channel, final String contentType, long chunkSize, final File file) { - super(); - if (channel == null) { - throw new IllegalArgumentException("File may not be null"); - } - if (chunkSize <= 0) { - throw new IllegalArgumentException("Chunk size must be greater than zero"); - } - mChannel = channel; - mContentType = contentType; - mChunkSize = chunkSize; - mFile = file; - mOffset = 0; - mTransferred = 0; - } - - public void setOffset(long offset) { - mOffset = offset; - } - - public long getContentLength() { - try { - return Math.min(mChunkSize, mChannel.size() - mChannel.position()); - } catch (IOException e) { - return mChunkSize; - } - } - - public String getContentType() { - return mContentType; - } - - public boolean isRepeatable() { - return true; - } - - @Override - public void addDatatransferProgressListener(OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.add(listener); - } - } - - @Override - public void addDatatransferProgressListeners(Collection listeners) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.addAll(listeners); - } - } - - @Override - public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.remove(listener); - } - } - - - public void writeRequest(final OutputStream out) throws IOException { - int readCount = 0; - Iterator it = null; - - try { - mChannel.position(mOffset); - long size = mFile.length(); - if (size == 0) size = -1; - long maxCount = Math.min(mOffset + mChunkSize, mChannel.size()); - while (mChannel.position() < maxCount) { - readCount = mChannel.read(mBuffer); - out.write(mBuffer.array(), 0, readCount); - mBuffer.clear(); - if (mTransferred < maxCount) { // condition to avoid accumulate progress for repeated chunks - mTransferred += readCount; - } - synchronized (mDataTransferListeners) { - it = mDataTransferListeners.iterator(); - while (it.hasNext()) { - it.next().onTransferProgress(readCount, mTransferred, size, mFile.getAbsolutePath()); - } - } - } - - } catch (IOException io) { - Log.e(TAG, io.getMessage()); - throw new RuntimeException("Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); - - } - } - -} \ No newline at end of file diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/FileRequestEntity.java b/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/FileRequestEntity.java deleted file mode 100644 index 1bc3eb67..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/FileRequestEntity.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network.webdav; - -import java.io.File; -import java.io.IOException; -import java.io.OutputStream; -import java.io.RandomAccessFile; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; - -import org.apache.commons.httpclient.methods.RequestEntity; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.ProgressiveDataTransferer; - - -/** - * A RequestEntity that represents a File. - * - */ -public class FileRequestEntity implements RequestEntity, ProgressiveDataTransferer { - - final File mFile; - final String mContentType; - Set mDataTransferListeners = new HashSet(); - - public FileRequestEntity(final File file, final String contentType) { - super(); - this.mFile = file; - this.mContentType = contentType; - if (file == null) { - throw new IllegalArgumentException("File may not be null"); - } - } - - @Override - public long getContentLength() { - return mFile.length(); - } - - @Override - public String getContentType() { - return mContentType; - } - - @Override - public boolean isRepeatable() { - return true; - } - - @Override - public void addDatatransferProgressListener(OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.add(listener); - } - } - - @Override - public void addDatatransferProgressListeners(Collection listeners) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.addAll(listeners); - } - } - - @Override - public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.remove(listener); - } - } - - - @Override - public void writeRequest(final OutputStream out) throws IOException { - //byte[] tmp = new byte[4096]; - ByteBuffer tmp = ByteBuffer.allocate(4096); - int readResult = 0; - - // TODO(bprzybylski): each mem allocation can throw OutOfMemoryError we need to handle it - // globally in some fashionable manner - RandomAccessFile raf = new RandomAccessFile(mFile, "r"); - FileChannel channel = raf.getChannel(); - Iterator it = null; - long transferred = 0; - long size = mFile.length(); - if (size == 0) size = -1; - try { - while ((readResult = channel.read(tmp)) >= 0) { - out.write(tmp.array(), 0, readResult); - tmp.clear(); - transferred += readResult; - synchronized (mDataTransferListeners) { - it = mDataTransferListeners.iterator(); - while (it.hasNext()) { - it.next().onTransferProgress(readResult, transferred, size, mFile.getAbsolutePath()); - } - } - } - - } catch (IOException io) { - Log.e("FileRequestException", io.getMessage()); - throw new RuntimeException("Ugly solution to workaround the default policy of retries when the server falls while uploading ; temporal fix; really", io); - - } finally { - channel.close(); - raf.close(); - } - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/OnDatatransferProgressListener.java b/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/OnDatatransferProgressListener.java deleted file mode 100644 index 0ace2dbb..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/OnDatatransferProgressListener.java +++ /dev/null @@ -1,30 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network.webdav; - -public interface OnDatatransferProgressListener { - public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileAbsoluteName); -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/OwnCloudClientFactory.java b/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/OwnCloudClientFactory.java deleted file mode 100644 index b90deedb..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/OwnCloudClientFactory.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network.webdav; - -import java.io.IOException; -import java.security.GeneralSecurityException; - -import com.owncloud.android.oc_framework.accounts.AccountTypeUtils; -import com.owncloud.android.oc_framework.accounts.AccountUtils; -import com.owncloud.android.oc_framework.accounts.OwnCloudAccount; -import com.owncloud.android.oc_framework.accounts.AccountUtils.AccountNotFoundException; -import com.owncloud.android.oc_framework.network.NetworkUtils; - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.accounts.AccountManagerFuture; -import android.accounts.AuthenticatorException; -import android.accounts.OperationCanceledException; -import android.app.Activity; -import android.content.Context; -import android.net.Uri; -import android.os.Bundle; -import android.util.Log; - -public class OwnCloudClientFactory { - - final private static String TAG = OwnCloudClientFactory.class.getSimpleName(); - - /** Default timeout for waiting data from the server */ - public static final int DEFAULT_DATA_TIMEOUT = 60000; - - /** Default timeout for establishing a connection */ - public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; - - - /** - * Creates a WebdavClient setup for an ownCloud account - * - * Do not call this method from the main thread. - * - * @param account The ownCloud account - * @param appContext Android application context - * @return A WebdavClient object ready to be used - * @throws AuthenticatorException If the authenticator failed to get the authorization token for the account. - * @throws OperationCanceledException If the authenticator operation was cancelled while getting the authorization token for the account. - * @throws IOException If there was some I/O error while getting the authorization token for the account. - * @throws AccountNotFoundException If 'account' is unknown for the AccountManager - */ - public static WebdavClient createOwnCloudClient (Account account, Context appContext) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { - //Log_OC.d(TAG, "Creating WebdavClient associated to " + account.name); - - Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account)); - AccountManager am = AccountManager.get(appContext); - boolean isOauth2 = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here - boolean isSamlSso = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null; - WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso); - if (isOauth2) { - String accessToken = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypeAccessToken(account.type), false); - client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token - - } else if (isSamlSso) { // TODO avoid a call to getUserData here - String accessToken = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(account.type), false); - client.setSsoSessionCookie(accessToken); - - } else { - String username = account.name.substring(0, account.name.lastIndexOf('@')); - //String password = am.getPassword(account); - String password = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypePass(account.type), false); - client.setBasicCredentials(username, password); - } - - return client; - } - - - public static WebdavClient createOwnCloudClient (Account account, Context appContext, Activity currentActivity) throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException { - Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account)); - AccountManager am = AccountManager.get(appContext); - boolean isOauth2 = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here - boolean isSamlSso = am.getUserData(account, OwnCloudAccount.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null; - WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso); - - if (isOauth2) { // TODO avoid a call to getUserData here - AccountManagerFuture future = am.getAuthToken(account, AccountTypeUtils.getAuthTokenTypeAccessToken(account.type), null, currentActivity, null, null); - Bundle result = future.getResult(); - String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN); - if (accessToken == null) throw new AuthenticatorException("WTF!"); - client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token - - } else if (isSamlSso) { // TODO avoid a call to getUserData here - AccountManagerFuture future = am.getAuthToken(account, AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(account.type), null, currentActivity, null, null); - Bundle result = future.getResult(); - String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN); - if (accessToken == null) throw new AuthenticatorException("WTF!"); - client.setSsoSessionCookie(accessToken); - - } else { - String username = account.name.substring(0, account.name.lastIndexOf('@')); - //String password = am.getPassword(account); - //String password = am.blockingGetAuthToken(account, MainApp.getAuthTokenTypePass(), false); - AccountManagerFuture future = am.getAuthToken(account, AccountTypeUtils.getAuthTokenTypePass(account.type), null, currentActivity, null, null); - Bundle result = future.getResult(); - String password = result.getString(AccountManager.KEY_AUTHTOKEN); - client.setBasicCredentials(username, password); - } - - return client; - } - - /** - * Creates a WebdavClient to access a URL and sets the desired parameters for ownCloud client connections. - * - * @param uri URL to the ownCloud server - * @param context Android context where the WebdavClient is being created. - * @return A WebdavClient object ready to be used - */ - public static WebdavClient createOwnCloudClient(Uri uri, Context context, boolean followRedirects) { - try { - NetworkUtils.registerAdvancedSslContext(true, context); - } catch (GeneralSecurityException e) { - Log.e(TAG, "Advanced SSL Context could not be loaded. Default SSL management in the system will be used for HTTPS connections", e); - - } catch (IOException e) { - Log.e(TAG, "The local server truststore could not be read. Default SSL management in the system will be used for HTTPS connections", e); - } - - WebdavClient client = new WebdavClient(NetworkUtils.getMultiThreadedConnManager()); - - client.setDefaultTimeouts(DEFAULT_DATA_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); - client.setBaseUri(uri); - client.setFollowRedirects(followRedirects); - - return client; - } - - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavClient.java b/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavClient.java deleted file mode 100644 index eb828d4d..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavClient.java +++ /dev/null @@ -1,252 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network.webdav; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.httpclient.Credentials; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpClient; -import org.apache.commons.httpclient.HttpConnectionManager; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpMethod; -import org.apache.commons.httpclient.HttpMethodBase; -import org.apache.commons.httpclient.HttpVersion; -import org.apache.commons.httpclient.URI; -import org.apache.commons.httpclient.UsernamePasswordCredentials; -import org.apache.commons.httpclient.auth.AuthPolicy; -import org.apache.commons.httpclient.auth.AuthScope; -import org.apache.commons.httpclient.cookie.CookiePolicy; -import org.apache.commons.httpclient.methods.HeadMethod; -import org.apache.commons.httpclient.params.HttpMethodParams; -import org.apache.http.HttpStatus; -import org.apache.http.params.CoreProtocolPNames; - -import com.owncloud.android.oc_framework.network.BearerAuthScheme; -import com.owncloud.android.oc_framework.network.BearerCredentials; - -import android.net.Uri; -import android.util.Log; - -public class WebdavClient extends HttpClient { - private static final int MAX_REDIRECTIONS_COUNT = 3; - - private Uri mUri; - private Credentials mCredentials; - private boolean mFollowRedirects; - private String mSsoSessionCookie; - final private static String TAG = WebdavClient.class.getSimpleName(); - public static final String USER_AGENT = "Android-ownCloud"; - - static private byte[] sExhaustBuffer = new byte[1024]; - - /** - * Constructor - */ - public WebdavClient(HttpConnectionManager connectionMgr) { - super(connectionMgr); - Log.d(TAG, "Creating WebdavClient"); - getParams().setParameter(HttpMethodParams.USER_AGENT, USER_AGENT); - getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); - mFollowRedirects = true; - mSsoSessionCookie = null; - } - - public void setBearerCredentials(String accessToken) { - AuthPolicy.registerAuthScheme(BearerAuthScheme.AUTH_POLICY, BearerAuthScheme.class); - - List authPrefs = new ArrayList(1); - authPrefs.add(BearerAuthScheme.AUTH_POLICY); - getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); - - mCredentials = new BearerCredentials(accessToken); - getState().setCredentials(AuthScope.ANY, mCredentials); - mSsoSessionCookie = null; - } - - public void setBasicCredentials(String username, String password) { - List authPrefs = new ArrayList(1); - authPrefs.add(AuthPolicy.BASIC); - getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs); - - getParams().setAuthenticationPreemptive(true); - mCredentials = new UsernamePasswordCredentials(username, password); - getState().setCredentials(AuthScope.ANY, mCredentials); - mSsoSessionCookie = null; - } - - public void setSsoSessionCookie(String accessToken) { - getParams().setAuthenticationPreemptive(false); - getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES); - mSsoSessionCookie = accessToken; - mCredentials = null; - } - - - /** - * Check if a file exists in the OC server - * - * TODO replace with ExistenceOperation - * - * @return 'true' if the file exists; 'false' it doesn't exist - * @throws Exception When the existence could not be determined - */ - public boolean existsFile(String path) throws IOException, HttpException { - HeadMethod head = new HeadMethod(mUri.toString() + WebdavUtils.encodePath(path)); - try { - int status = executeMethod(head); - Log.d(TAG, "HEAD to " + path + " finished with HTTP status " + status + ((status != HttpStatus.SC_OK)?"(FAIL)":"")); - exhaustResponse(head.getResponseBodyAsStream()); - return (status == HttpStatus.SC_OK); - - } finally { - head.releaseConnection(); // let the connection available for other methods - } - } - - /** - * Requests the received method with the received timeout (milliseconds). - * - * Executes the method through the inherited HttpClient.executedMethod(method). - * - * Sets the socket and connection timeouts only for the method received. - * - * The timeouts are both in milliseconds; 0 means 'infinite'; < 0 means 'do not change the default' - * - * @param method HTTP method request. - * @param readTimeout Timeout to set for data reception - * @param conntionTimout Timeout to set for connection establishment - */ - public int executeMethod(HttpMethodBase method, int readTimeout, int connectionTimeout) throws HttpException, IOException { - int oldSoTimeout = getParams().getSoTimeout(); - int oldConnectionTimeout = getHttpConnectionManager().getParams().getConnectionTimeout(); - try { - if (readTimeout >= 0) { - method.getParams().setSoTimeout(readTimeout); // this should be enough... - getParams().setSoTimeout(readTimeout); // ... but this looks like necessary for HTTPS - } - if (connectionTimeout >= 0) { - getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout); - } - return executeMethod(method); - } finally { - getParams().setSoTimeout(oldSoTimeout); - getHttpConnectionManager().getParams().setConnectionTimeout(oldConnectionTimeout); - } - } - - - @Override - public int executeMethod(HttpMethod method) throws IOException, HttpException { - boolean customRedirectionNeeded = false; - try { - method.setFollowRedirects(mFollowRedirects); - } catch (Exception e) { - //if (mFollowRedirects) Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() + " method, custom redirection will be used if needed"); - customRedirectionNeeded = mFollowRedirects; - } - if (mSsoSessionCookie != null && mSsoSessionCookie.length() > 0) { - method.setRequestHeader("Cookie", mSsoSessionCookie); - } - int status = super.executeMethod(method); - int redirectionsCount = 0; - while (customRedirectionNeeded && - redirectionsCount < MAX_REDIRECTIONS_COUNT && - ( status == HttpStatus.SC_MOVED_PERMANENTLY || - status == HttpStatus.SC_MOVED_TEMPORARILY || - status == HttpStatus.SC_TEMPORARY_REDIRECT) - ) { - - Header location = method.getResponseHeader("Location"); - if (location != null) { - Log.d(TAG, "Location to redirect: " + location.getValue()); - method.setURI(new URI(location.getValue(), true)); - status = super.executeMethod(method); - redirectionsCount++; - - } else { - Log.d(TAG, "No location to redirect!"); - status = HttpStatus.SC_NOT_FOUND; - } - } - - return status; - } - - - /** - * Exhausts a not interesting HTTP response. Encouraged by HttpClient documentation. - * - * @param responseBodyAsStream InputStream with the HTTP response to exhaust. - */ - public void exhaustResponse(InputStream responseBodyAsStream) { - if (responseBodyAsStream != null) { - try { - while (responseBodyAsStream.read(sExhaustBuffer) >= 0); - responseBodyAsStream.close(); - - } catch (IOException io) { - Log.e(TAG, "Unexpected exception while exhausting not interesting HTTP response; will be IGNORED", io); - } - } - } - - /** - * Sets the connection and wait-for-data timeouts to be applied by default to the methods performed by this client. - */ - public void setDefaultTimeouts(int defaultDataTimeout, int defaultConnectionTimeout) { - getParams().setSoTimeout(defaultDataTimeout); - getHttpConnectionManager().getParams().setConnectionTimeout(defaultConnectionTimeout); - } - - /** - * Sets the base URI for the helper methods that receive paths as parameters, instead of full URLs - * @param uri - */ - public void setBaseUri(Uri uri) { - mUri = uri; - } - - public Uri getBaseUri() { - return mUri; - } - - public final Credentials getCredentials() { - return mCredentials; - } - - public final String getSsoSessionCookie() { - return mSsoSessionCookie; - } - - public void setFollowRedirects(boolean followRedirects) { - mFollowRedirects = followRedirects; - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavEntry.java b/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavEntry.java deleted file mode 100644 index 9d0d61fe..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavEntry.java +++ /dev/null @@ -1,158 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network.webdav; - -import java.util.Date; - -import org.apache.jackrabbit.webdav.MultiStatusResponse; -import org.apache.jackrabbit.webdav.property.DavProperty; -import org.apache.jackrabbit.webdav.property.DavPropertyName; -import org.apache.jackrabbit.webdav.property.DavPropertySet; - - - -import android.net.Uri; -import android.util.Log; - -public class WebdavEntry { - private String mName, mPath, mUri, mContentType, mEtag; - private long mContentLength, mCreateTimestamp, mModifiedTimestamp; - - public WebdavEntry(MultiStatusResponse ms, String splitElement) { - resetData(); - if (ms.getStatus().length != 0) { - mUri = ms.getHref(); - - mPath = mUri.split(splitElement, 2)[1]; - - int status = ms.getStatus()[0].getStatusCode(); - DavPropertySet propSet = ms.getProperties(status); - @SuppressWarnings("rawtypes") - DavProperty prop = propSet.get(DavPropertyName.DISPLAYNAME); - if (prop != null) { - mName = (String) prop.getName().toString(); - mName = mName.substring(1, mName.length()-1); - } - else { - String[] tmp = mPath.split("/"); - if (tmp.length > 0) - mName = tmp[tmp.length - 1]; - } - - // use unknown mimetype as default behavior - mContentType = "application/octet-stream"; - prop = propSet.get(DavPropertyName.GETCONTENTTYPE); - if (prop != null) { - mContentType = (String) prop.getValue(); - // dvelasco: some builds of ownCloud server 4.0.x added a trailing ';' to the MIME type ; if looks fixed, but let's be cautious - if (mContentType.indexOf(";") >= 0) { - mContentType = mContentType.substring(0, mContentType.indexOf(";")); - } - } - - // check if it's a folder in the standard way: see RFC2518 12.2 . RFC4918 14.3 - prop = propSet.get(DavPropertyName.RESOURCETYPE); - if (prop!= null) { - Object value = prop.getValue(); - if (value != null) { - mContentType = "DIR"; // a specific attribute would be better, but this is enough; unless while we have no reason to distinguish MIME types for folders - } - } - - prop = propSet.get(DavPropertyName.GETCONTENTLENGTH); - if (prop != null) - mContentLength = Long.parseLong((String) prop.getValue()); - - prop = propSet.get(DavPropertyName.GETLASTMODIFIED); - if (prop != null) { - Date d = WebdavUtils - .parseResponseDate((String) prop.getValue()); - mModifiedTimestamp = (d != null) ? d.getTime() : 0; - } - - prop = propSet.get(DavPropertyName.CREATIONDATE); - if (prop != null) { - Date d = WebdavUtils - .parseResponseDate((String) prop.getValue()); - mCreateTimestamp = (d != null) ? d.getTime() : 0; - } - - prop = propSet.get(DavPropertyName.GETETAG); - if (prop != null) { - mEtag = (String) prop.getValue(); - mEtag = mEtag.substring(1, mEtag.length()-1); - } - - } else { - Log.e("WebdavEntry", - "General fuckup, no status for webdav response"); - } - } - - public String path() { - return mPath; - } - - public String decodedPath() { - return Uri.decode(mPath); - } - - public String name() { - return mName; - } - - public boolean isDirectory() { - return mContentType.equals("DIR"); - } - - public String contentType() { - return mContentType; - } - - public String uri() { - return mUri; - } - - public long contentLength() { - return mContentLength; - } - - public long createTimestamp() { - return mCreateTimestamp; - } - - public long modifiedTimestamp() { - return mModifiedTimestamp; - } - - public String etag() { - return mEtag; - } - - private void resetData() { - mName = mUri = mContentType = null; - mContentLength = mCreateTimestamp = mModifiedTimestamp = 0; - } -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavUtils.java b/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavUtils.java deleted file mode 100644 index 7b963fca..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/network/webdav/WebdavUtils.java +++ /dev/null @@ -1,83 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.network.webdav; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import android.net.Uri; - -public class WebdavUtils { - public static final SimpleDateFormat DISPLAY_DATE_FORMAT = new SimpleDateFormat( - "dd.MM.yyyy hh:mm"); - private static final SimpleDateFormat DATETIME_FORMATS[] = { - new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US), - new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US), - new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.sss'Z'", Locale.US), - new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US), - new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US), - new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), - new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; - - public static String prepareXmlForPropFind() { - String ret = ""; - return ret; - } - - public static String prepareXmlForPatch() { - return ""; - } - - public static Date parseResponseDate(String date) { - Date returnDate = null; - for (int i = 0; i < DATETIME_FORMATS.length; ++i) { - try { - returnDate = DATETIME_FORMATS[i].parse(date); - return returnDate; - } catch (ParseException e) { - } - } - return null; - } - - /** - * Encodes a path according to URI RFC 2396. - * - * If the received path doesn't start with "/", the method adds it. - * - * @param remoteFilePath Path - * @return Encoded path according to RFC 2396, always starting with "/" - */ - public static String encodePath(String remoteFilePath) { - String encodedPath = Uri.encode(remoteFilePath, "/"); - if (!encodedPath.startsWith("/")) - encodedPath = "/" + encodedPath; - return encodedPath; - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/OnRemoteOperationListener.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/OnRemoteOperationListener.java deleted file mode 100644 index c87a1905..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/OnRemoteOperationListener.java +++ /dev/null @@ -1,32 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations; - -public interface OnRemoteOperationListener { - - void onRemoteOperationFinish(RemoteOperation caller, RemoteOperationResult result); - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/OperationCancelledException.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/OperationCancelledException.java deleted file mode 100644 index b47a8e15..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/OperationCancelledException.java +++ /dev/null @@ -1,35 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations; - -public class OperationCancelledException extends Exception { - - /** - * Generated serial version - to avoid Java warning - */ - private static final long serialVersionUID = -6350981497740424983L; - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteFile.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteFile.java deleted file mode 100644 index 9c947c80..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteFile.java +++ /dev/null @@ -1,187 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations; - -import java.io.Serializable; - -import android.os.Parcel; -import android.os.Parcelable; - -import com.owncloud.android.oc_framework.network.webdav.WebdavEntry; -import com.owncloud.android.oc_framework.utils.FileUtils; - -/** - * Contains the data of a Remote File from a WebDavEntry - * - * @author masensio - */ - -public class RemoteFile implements Parcelable, Serializable { - - /** Generated - should be refreshed every time the class changes!! */ - private static final long serialVersionUID = 532139091191390616L; - - private String mRemotePath; - private String mMimeType; - private long mLength; - private long mCreationTimestamp; - private long mModifiedTimestamp; - private String mEtag; - - /** - * Getters and Setters - */ - - public String getRemotePath() { - return mRemotePath; - } - - public void setRemotePath(String remotePath) { - this.mRemotePath = remotePath; - } - - public String getMimeType() { - return mMimeType; - } - - public void setMimeType(String mimeType) { - this.mMimeType = mimeType; - } - - public long getLength() { - return mLength; - } - - public void setLength(long length) { - this.mLength = length; - } - - public long getCreationTimestamp() { - return mCreationTimestamp; - } - - public void setCreationTimestamp(long creationTimestamp) { - this.mCreationTimestamp = creationTimestamp; - } - - public long getModifiedTimestamp() { - return mModifiedTimestamp; - } - - public void setModifiedTimestamp(long modifiedTimestamp) { - this.mModifiedTimestamp = modifiedTimestamp; - } - - public String getEtag() { - return mEtag; - } - - public void setEtag(String etag) { - this.mEtag = etag; - } - - /** - * Create new {@link RemoteFile} with given path. - * - * The path received must be URL-decoded. Path separator must be OCFile.PATH_SEPARATOR, and it must be the first character in 'path'. - * - * @param path The remote path of the file. - */ - public RemoteFile(String path) { - resetData(); - if (path == null || path.length() <= 0 || !path.startsWith(FileUtils.PATH_SEPARATOR)) { - throw new IllegalArgumentException("Trying to create a OCFile with a non valid remote path: " + path); - } - mRemotePath = path; - } - - public RemoteFile(WebdavEntry we) { - this(we.decodedPath()); - this.setCreationTimestamp(we.createTimestamp()); - this.setLength(we.contentLength()); - this.setMimeType(we.contentType()); - this.setModifiedTimestamp(we.modifiedTimestamp()); - this.setEtag(we.etag()); - } - - /** - * Used internally. Reset all file properties - */ - private void resetData() { - mRemotePath = null; - mMimeType = null; - mLength = 0; - mCreationTimestamp = 0; - mModifiedTimestamp = 0; - mEtag = null; - } - - /** - * Parcelable Methods - */ - public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { - @Override - public RemoteFile createFromParcel(Parcel source) { - return new RemoteFile(source); - } - - @Override - public RemoteFile[] newArray(int size) { - return new RemoteFile[size]; - } - }; - - - /** - * Reconstruct from parcel - * - * @param source The source parcel - */ - private RemoteFile(Parcel source) { - mRemotePath = source.readString(); - mMimeType = source.readString(); - mLength = source.readLong(); - mCreationTimestamp = source.readLong(); - mModifiedTimestamp = source.readLong(); - mEtag = source.readString(); - } - - @Override - public int describeContents() { - return this.hashCode(); - } - - @Override - public void writeToParcel(Parcel dest, int flags) { - dest.writeString(mRemotePath); - dest.writeString(mMimeType); - dest.writeLong(mLength); - dest.writeLong(mCreationTimestamp); - dest.writeLong(mModifiedTimestamp); - dest.writeString(mEtag); - } - - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteOperation.java deleted file mode 100644 index 7efb588e..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteOperation.java +++ /dev/null @@ -1,295 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations; - -import java.io.IOException; - -import org.apache.commons.httpclient.Credentials; - -import com.owncloud.android.oc_framework.network.BearerCredentials; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; - - - -import android.accounts.Account; -import android.accounts.AccountManager; -import android.accounts.AccountsException; -import android.app.Activity; -import android.content.Context; -import android.os.Handler; -import android.util.Log; - - -/** - * Operation which execution involves one or several interactions with an ownCloud server. - * - * Provides methods to execute the operation both synchronously or asynchronously. - * - * @author David A. Velasco - */ -public abstract class RemoteOperation implements Runnable { - - private static final String TAG = RemoteOperation.class.getSimpleName(); - - /** ownCloud account in the remote ownCloud server to operate */ - private Account mAccount = null; - - /** Android Application context */ - private Context mContext = null; - - /** Object to interact with the remote server */ - private WebdavClient mClient = null; - - /** Callback object to notify about the execution of the remote operation */ - private OnRemoteOperationListener mListener = null; - - /** Handler to the thread where mListener methods will be called */ - private Handler mListenerHandler = null; - - /** Activity */ - private Activity mCallerActivity; - - - /** - * Abstract method to implement the operation in derived classes. - */ - protected abstract RemoteOperationResult run(WebdavClient client); - - - /** - * Synchronously executes the remote operation on the received ownCloud account. - * - * Do not call this method from the main thread. - * - * This method should be used whenever an ownCloud account is available, instead of {@link #execute(WebdavClient)}. - * - * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation. - * @param context Android context for the component calling the method. - * @return Result of the operation. - */ - public final RemoteOperationResult execute(Account account, Context context) { - if (account == null) - throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account"); - if (context == null) - throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context"); - mAccount = account; - mContext = context.getApplicationContext(); - try { - mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext); - } catch (Exception e) { - Log.e(TAG, "Error while trying to access to " + mAccount.name, e); - return new RemoteOperationResult(e); - } - return run(mClient); - } - - - /** - * Synchronously executes the remote operation - * - * Do not call this method from the main thread. - * - * @param client Client object to reach an ownCloud server during the execution of the operation. - * @return Result of the operation. - */ - public final RemoteOperationResult execute(WebdavClient client) { - if (client == null) - throw new IllegalArgumentException("Trying to execute a remote operation with a NULL WebdavClient"); - mClient = client; - return run(client); - } - - - /** - * Asynchronously executes the remote operation - * - * This method should be used whenever an ownCloud account is available, instead of {@link #execute(WebdavClient)}. - * - * @param account ownCloud account in remote ownCloud server to reach during the execution of the operation. - * @param context Android context for the component calling the method. - * @param listener Listener to be notified about the execution of the operation. - * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. - * @return Thread were the remote operation is executed. - */ - public final Thread execute(Account account, Context context, OnRemoteOperationListener listener, Handler listenerHandler, Activity callerActivity) { - if (account == null) - throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Account"); - if (context == null) - throw new IllegalArgumentException("Trying to execute a remote operation with a NULL Context"); - mAccount = account; - mContext = context.getApplicationContext(); - mCallerActivity = callerActivity; - mClient = null; // the client instance will be created from mAccount and mContext in the runnerThread to create below - - mListener = listener; - - mListenerHandler = listenerHandler; - - Thread runnerThread = new Thread(this); - runnerThread.start(); - return runnerThread; - } - - - /** - * Asynchronously executes the remote operation - * - * @param client Client object to reach an ownCloud server during the execution of the operation. - * @param listener Listener to be notified about the execution of the operation. - * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. - * @return Thread were the remote operation is executed. - */ - public final Thread execute(WebdavClient client, OnRemoteOperationListener listener, Handler listenerHandler) { - if (client == null) { - throw new IllegalArgumentException("Trying to execute a remote operation with a NULL WebdavClient"); - } - mClient = client; - - if (listener == null) { - throw new IllegalArgumentException("Trying to execute a remote operation asynchronously without a listener to notiy the result"); - } - mListener = listener; - - if (listenerHandler == null) { - throw new IllegalArgumentException("Trying to execute a remote operation asynchronously without a handler to the listener's thread"); - } - mListenerHandler = listenerHandler; - - Thread runnerThread = new Thread(this); - runnerThread.start(); - return runnerThread; - } - - /** - * Synchronously retries the remote operation using the same WebdavClient in the last call to {@link RemoteOperation#execute(WebdavClient)} - * - * @param listener Listener to be notified about the execution of the operation. - * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. - * @return Thread were the remote operation is executed. - */ - public final RemoteOperationResult retry() { - return execute(mClient); - } - - /** - * Asynchronously retries the remote operation using the same WebdavClient in the last call to {@link RemoteOperation#execute(WebdavClient, OnRemoteOperationListener, Handler)} - * - * @param listener Listener to be notified about the execution of the operation. - * @param listenerHandler Handler associated to the thread where the methods of the listener objects must be called. - * @return Thread were the remote operation is executed. - */ - public final Thread retry(OnRemoteOperationListener listener, Handler listenerHandler) { - return execute(mClient, listener, listenerHandler); - } - - - /** - * Asynchronous execution of the operation - * started by {@link RemoteOperation#execute(WebdavClient, OnRemoteOperationListener, Handler)}, - * and result posting. - * - * TODO refactor && clean the code; now it's a mess - */ - @Override - public final void run() { - RemoteOperationResult result = null; - boolean repeat = false; - do { - try{ - if (mClient == null) { - if (mAccount != null && mContext != null) { - if (mCallerActivity != null) { - mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext, mCallerActivity); - } else { - mClient = OwnCloudClientFactory.createOwnCloudClient(mAccount, mContext); - } - } else { - throw new IllegalStateException("Trying to run a remote operation asynchronously with no client instance or account"); - } - } - - } catch (IOException e) { - Log.e(TAG, "Error while trying to access to " + mAccount.name, new AccountsException("I/O exception while trying to authorize the account", e)); - result = new RemoteOperationResult(e); - - } catch (AccountsException e) { - Log.e(TAG, "Error while trying to access to " + mAccount.name, e); - result = new RemoteOperationResult(e); - } - - if (result == null) - result = run(mClient); - - repeat = false; - if (mCallerActivity != null && mAccount != null && mContext != null && !result.isSuccess() && -// (result.getCode() == ResultCode.UNAUTHORIZED || (result.isTemporalRedirection() && result.isIdPRedirection()))) { - (result.getCode() == ResultCode.UNAUTHORIZED || result.isIdPRedirection())) { - /// possible fail due to lack of authorization in an operation performed in foreground - Credentials cred = mClient.getCredentials(); - String ssoSessionCookie = mClient.getSsoSessionCookie(); - if (cred != null || ssoSessionCookie != null) { - /// confirmed : unauthorized operation - AccountManager am = AccountManager.get(mContext); - boolean bearerAuthorization = (cred != null && cred instanceof BearerCredentials); - boolean samlBasedSsoAuthorization = (cred == null && ssoSessionCookie != null); - if (bearerAuthorization) { - am.invalidateAuthToken(mAccount.type, ((BearerCredentials)cred).getAccessToken()); - } else if (samlBasedSsoAuthorization ) { - am.invalidateAuthToken(mAccount.type, ssoSessionCookie); - } else { - am.clearPassword(mAccount); - } - mClient = null; - repeat = true; // when repeated, the creation of a new OwnCloudClient after erasing the saved credentials will trigger the login activity - result = null; - } - } - } while (repeat); - - final RemoteOperationResult resultToSend = result; - if (mListenerHandler != null && mListener != null) { - mListenerHandler.post(new Runnable() { - @Override - public void run() { - mListener.onRemoteOperationFinish(RemoteOperation.this, resultToSend); - } - }); - } - } - - - /** - * Returns the current client instance to access the remote server. - * - * @return Current client instance to access the remote server. - */ - public final WebdavClient getClient() { - return mClient; - } - - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteOperationResult.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteOperationResult.java deleted file mode 100644 index 1dc1720a..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/RemoteOperationResult.java +++ /dev/null @@ -1,363 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations; - -import java.io.IOException; -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.SocketException; -import java.net.SocketTimeoutException; -import java.net.UnknownHostException; -import java.util.ArrayList; - -import javax.net.ssl.SSLException; - -import org.apache.commons.httpclient.ConnectTimeoutException; -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.HttpStatus; -import org.apache.jackrabbit.webdav.DavException; -import org.json.JSONException; - -import com.owncloud.android.oc_framework.accounts.AccountUtils.AccountNotFoundException; -import com.owncloud.android.oc_framework.network.CertificateCombinedException; - -import android.accounts.Account; -import android.accounts.AccountsException; -import android.util.Log; - - -/** - * The result of a remote operation required to an ownCloud server. - * - * Provides a common classification of remote operation results for all the - * application. - * - * @author David A. Velasco - */ -public class RemoteOperationResult implements Serializable { - - /** Generated - should be refreshed every time the class changes!! */ - private static final long serialVersionUID = -8257349554488668693L; - - private static final String TAG = "RemoteOperationResult"; - - public enum ResultCode { - OK, - OK_SSL, - OK_NO_SSL, - UNHANDLED_HTTP_CODE, - UNAUTHORIZED, - FILE_NOT_FOUND, - INSTANCE_NOT_CONFIGURED, - UNKNOWN_ERROR, - WRONG_CONNECTION, - TIMEOUT, - INCORRECT_ADDRESS, - HOST_NOT_AVAILABLE, - NO_NETWORK_CONNECTION, - SSL_ERROR, - SSL_RECOVERABLE_PEER_UNVERIFIED, - BAD_OC_VERSION, - CANCELLED, - INVALID_LOCAL_FILE_NAME, - INVALID_OVERWRITE, - CONFLICT, - OAUTH2_ERROR, - SYNC_CONFLICT, - LOCAL_STORAGE_FULL, - LOCAL_STORAGE_NOT_MOVED, - LOCAL_STORAGE_NOT_COPIED, - OAUTH2_ERROR_ACCESS_DENIED, - QUOTA_EXCEEDED, - ACCOUNT_NOT_FOUND, - ACCOUNT_EXCEPTION, - ACCOUNT_NOT_NEW, - ACCOUNT_NOT_THE_SAME, - INVALID_CHARACTER_IN_NAME - } - - private boolean mSuccess = false; - private int mHttpCode = -1; - private Exception mException = null; - private ResultCode mCode = ResultCode.UNKNOWN_ERROR; - private String mRedirectedLocation; - - private ArrayList mFiles; - - public RemoteOperationResult(ResultCode code) { - mCode = code; - mSuccess = (code == ResultCode.OK || code == ResultCode.OK_SSL || code == ResultCode.OK_NO_SSL); - mFiles = null; - } - - private RemoteOperationResult(boolean success, int httpCode) { - mSuccess = success; - mHttpCode = httpCode; - - if (success) { - mCode = ResultCode.OK; - - } else if (httpCode > 0) { - switch (httpCode) { - case HttpStatus.SC_UNAUTHORIZED: - mCode = ResultCode.UNAUTHORIZED; - break; - case HttpStatus.SC_NOT_FOUND: - mCode = ResultCode.FILE_NOT_FOUND; - break; - case HttpStatus.SC_INTERNAL_SERVER_ERROR: - mCode = ResultCode.INSTANCE_NOT_CONFIGURED; - break; - case HttpStatus.SC_CONFLICT: - mCode = ResultCode.CONFLICT; - break; - case HttpStatus.SC_INSUFFICIENT_STORAGE: - mCode = ResultCode.QUOTA_EXCEEDED; - break; - default: - mCode = ResultCode.UNHANDLED_HTTP_CODE; - Log.d(TAG, "RemoteOperationResult has processed UNHANDLED_HTTP_CODE: " + httpCode); - } - } - } - - public RemoteOperationResult(boolean success, int httpCode, Header[] headers) { - this(success, httpCode); - if (headers != null) { - Header current; - for (int i=0; i files){ - mFiles = files; - } - - public ArrayList getData(){ - return mFiles; - } - - public boolean isSuccess() { - return mSuccess; - } - - public boolean isCancelled() { - return mCode == ResultCode.CANCELLED; - } - - public int getHttpCode() { - return mHttpCode; - } - - public ResultCode getCode() { - return mCode; - } - - public Exception getException() { - return mException; - } - - public boolean isSslRecoverableException() { - return mCode == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED; - } - - private CertificateCombinedException getCertificateCombinedException(Exception e) { - CertificateCombinedException result = null; - if (e instanceof CertificateCombinedException) { - return (CertificateCombinedException) e; - } - Throwable cause = mException.getCause(); - Throwable previousCause = null; - while (cause != null && cause != previousCause && !(cause instanceof CertificateCombinedException)) { - previousCause = cause; - cause = cause.getCause(); - } - if (cause != null && cause instanceof CertificateCombinedException) { - result = (CertificateCombinedException) cause; - } - return result; - } - - public String getLogMessage() { - - if (mException != null) { - if (mException instanceof OperationCancelledException) { - return "Operation cancelled by the caller"; - - } else if (mException instanceof SocketException) { - return "Socket exception"; - - } else if (mException instanceof SocketTimeoutException) { - return "Socket timeout exception"; - - } else if (mException instanceof ConnectTimeoutException) { - return "Connect timeout exception"; - - } else if (mException instanceof MalformedURLException) { - return "Malformed URL exception"; - - } else if (mException instanceof UnknownHostException) { - return "Unknown host exception"; - - } else if (mException instanceof CertificateCombinedException) { - if (((CertificateCombinedException) mException).isRecoverable()) - return "SSL recoverable exception"; - else - return "SSL exception"; - - } else if (mException instanceof SSLException) { - return "SSL exception"; - - } else if (mException instanceof DavException) { - return "Unexpected WebDAV exception"; - - } else if (mException instanceof HttpException) { - return "HTTP violation"; - - } else if (mException instanceof IOException) { - return "Unrecovered transport exception"; - - } else if (mException instanceof AccountNotFoundException) { - Account failedAccount = ((AccountNotFoundException)mException).getFailedAccount(); - return mException.getMessage() + " (" + (failedAccount != null ? failedAccount.name : "NULL") + ")"; - - } else if (mException instanceof AccountsException) { - return "Exception while using account"; - - } else if (mException instanceof JSONException) { - return "JSON exception"; - - } else { - return "Unexpected exception"; - } - } - - if (mCode == ResultCode.INSTANCE_NOT_CONFIGURED) { - return "The ownCloud server is not configured!"; - - } else if (mCode == ResultCode.NO_NETWORK_CONNECTION) { - return "No network connection"; - - } else if (mCode == ResultCode.BAD_OC_VERSION) { - return "No valid ownCloud version was found at the server"; - - } else if (mCode == ResultCode.LOCAL_STORAGE_FULL) { - return "Local storage full"; - - } else if (mCode == ResultCode.LOCAL_STORAGE_NOT_MOVED) { - return "Error while moving file to final directory"; - - } else if (mCode == ResultCode.ACCOUNT_NOT_NEW) { - return "Account already existing when creating a new one"; - - } else if (mCode == ResultCode.ACCOUNT_NOT_THE_SAME) { - return "Authenticated with a different account than the one updating"; - } else if (mCode == ResultCode.INVALID_CHARACTER_IN_NAME) { - return "The file name contains an forbidden character"; - } - - return "Operation finished with HTTP status code " + mHttpCode + " (" + (isSuccess() ? "success" : "fail") + ")"; - - } - - public boolean isServerFail() { - return (mHttpCode >= HttpStatus.SC_INTERNAL_SERVER_ERROR); - } - - public boolean isException() { - return (mException != null); - } - - public boolean isTemporalRedirection() { - return (mHttpCode == 302 || mHttpCode == 307); - } - - public String getRedirectedLocation() { - return mRedirectedLocation; - } - - public boolean isIdPRedirection() { - return (mRedirectedLocation != null && - (mRedirectedLocation.toUpperCase().contains("SAML") || - mRedirectedLocation.toLowerCase().contains("wayf"))); - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ChunkedUploadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ChunkedUploadRemoteFileOperation.java deleted file mode 100644 index 6df42642..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ChunkedUploadRemoteFileOperation.java +++ /dev/null @@ -1,101 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.util.Random; - -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.PutMethod; - -import com.owncloud.android.oc_framework.network.ProgressiveDataTransferer; -import com.owncloud.android.oc_framework.network.webdav.ChunkFromFileChannelRequestEntity; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; - - -import android.util.Log; - - -public class ChunkedUploadRemoteFileOperation extends UploadRemoteFileOperation { - - public static final long CHUNK_SIZE = 1024000; - private static final String OC_CHUNKED_HEADER = "OC-Chunked"; - private static final String TAG = ChunkedUploadRemoteFileOperation.class.getSimpleName(); - - public ChunkedUploadRemoteFileOperation(String storagePath, String remotePath, String mimeType) { - super(storagePath, remotePath, mimeType); - } - - @Override - protected int uploadFile(WebdavClient client) throws HttpException, IOException { - int status = -1; - - FileChannel channel = null; - RandomAccessFile raf = null; - try { - File file = new File(mStoragePath); - raf = new RandomAccessFile(file, "r"); - channel = raf.getChannel(); - mEntity = new ChunkFromFileChannelRequestEntity(channel, mMimeType, CHUNK_SIZE, file); - //((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(getDataTransferListeners()); - synchronized (mDataTransferListeners) { - ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners); - } - - long offset = 0; - String uriPrefix = client.getBaseUri() + WebdavUtils.encodePath(mRemotePath) + "-chunking-" + Math.abs((new Random()).nextInt(9000)+1000) + "-" ; - long chunkCount = (long) Math.ceil((double)file.length() / CHUNK_SIZE); - for (int chunkIndex = 0; chunkIndex < chunkCount ; chunkIndex++, offset += CHUNK_SIZE) { - if (mPutMethod != null) { - mPutMethod.releaseConnection(); // let the connection available for other methods - } - mPutMethod = new PutMethod(uriPrefix + chunkCount + "-" + chunkIndex); - mPutMethod.addRequestHeader(OC_CHUNKED_HEADER, OC_CHUNKED_HEADER); - ((ChunkFromFileChannelRequestEntity)mEntity).setOffset(offset); - mPutMethod.setRequestEntity(mEntity); - status = client.executeMethod(mPutMethod); - client.exhaustResponse(mPutMethod.getResponseBodyAsStream()); - Log.d(TAG, "Upload of " + mStoragePath + " to " + mRemotePath + ", chunk index " + chunkIndex + ", count " + chunkCount + ", HTTP result status " + status); - if (!isSuccess(status)) - break; - } - - } finally { - if (channel != null) - channel.close(); - if (raf != null) - raf.close(); - if (mPutMethod != null) - mPutMethod.releaseConnection(); // let the connection available for other methods - } - return status; - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/CreateRemoteFolderOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/CreateRemoteFolderOperation.java deleted file mode 100644 index ebbe3e67..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/CreateRemoteFolderOperation.java +++ /dev/null @@ -1,118 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import org.apache.commons.httpclient.HttpStatus; -import org.apache.jackrabbit.webdav.client.methods.MkColMethod; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.utils.FileUtils; - - - -/** - * Remote operation performing the creation of a new folder in the ownCloud server. - * - * @author David A. Velasco - * @author masensio - * - */ -public class CreateRemoteFolderOperation extends RemoteOperation { - - private static final String TAG = CreateRemoteFolderOperation.class.getSimpleName(); - - private static final int READ_TIMEOUT = 10000; - private static final int CONNECTION_TIMEOUT = 5000; - - - protected String mRemotePath; - protected boolean mCreateFullPath; - - /** - * Constructor - * - * @param remotePath Full path to the new directory to create in the remote server. - * @param createFullPath 'True' means that all the ancestor folders should be created if don't exist yet. - */ - public CreateRemoteFolderOperation(String remotePath, boolean createFullPath) { - mRemotePath = remotePath; - mCreateFullPath = createFullPath; - } - - /** - * Performs the operation - * - * @param client Client object to communicate with the remote ownCloud server. - */ - @Override - protected RemoteOperationResult run(WebdavClient client) { - RemoteOperationResult result = null; - MkColMethod mkcol = null; - - boolean noInvalidChars = FileUtils.isValidPath(mRemotePath); - if (noInvalidChars) { - try { - mkcol = new MkColMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); - int status = client.executeMethod(mkcol, READ_TIMEOUT, CONNECTION_TIMEOUT); - if (!mkcol.succeeded() && mkcol.getStatusCode() == HttpStatus.SC_CONFLICT && mCreateFullPath) { - result = createParentFolder(FileUtils.getParentPath(mRemotePath), client); - status = client.executeMethod(mkcol, READ_TIMEOUT, CONNECTION_TIMEOUT); // second (and last) try - } - - result = new RemoteOperationResult(mkcol.succeeded(), status, mkcol.getResponseHeaders()); - Log.d(TAG, "Create directory " + mRemotePath + ": " + result.getLogMessage()); - client.exhaustResponse(mkcol.getResponseBodyAsStream()); - - } catch (Exception e) { - result = new RemoteOperationResult(e); - Log.e(TAG, "Create directory " + mRemotePath + ": " + result.getLogMessage(), e); - - } finally { - if (mkcol != null) - mkcol.releaseConnection(); - } - } else { - result = new RemoteOperationResult(ResultCode.INVALID_CHARACTER_IN_NAME); - } - - return result; - } - - - private RemoteOperationResult createParentFolder(String parentPath, WebdavClient client) { - RemoteOperation operation = new CreateRemoteFolderOperation(parentPath, - mCreateFullPath); - return operation.execute(client); - } - - - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/DownloadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/DownloadRemoteFileOperation.java deleted file mode 100644 index 6d90e629..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/DownloadRemoteFileOperation.java +++ /dev/null @@ -1,179 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.commons.httpclient.Header; -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.http.HttpStatus; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.OperationCancelledException; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; - -/** - * Remote operation performing the download of a remote file in the ownCloud server. - * - * @author David A. Velasco - * @author masensio - */ - -public class DownloadRemoteFileOperation extends RemoteOperation { - - private static final String TAG = DownloadRemoteFileOperation.class.getSimpleName(); - - private Set mDataTransferListeners = new HashSet(); - private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false); - //private long mModificationTimestamp = 0; - private GetMethod mGet; - - private String mRemotePath; - private String mDownloadFolderPath; - - public DownloadRemoteFileOperation(String remotePath, String downloadFolderPath) { - mRemotePath = remotePath; - mDownloadFolderPath = downloadFolderPath; - } - - @Override - protected RemoteOperationResult run(WebdavClient client) { - RemoteOperationResult result = null; - - /// download will be performed to a temporal file, then moved to the final location - File tmpFile = new File(getTmpPath()); - - /// perform the download - try { - tmpFile.getParentFile().mkdirs(); - int status = downloadFile(client, tmpFile); - result = new RemoteOperationResult(isSuccess(status), status, (mGet != null ? mGet.getResponseHeaders() : null)); - Log.i(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage()); - - } catch (Exception e) { - result = new RemoteOperationResult(e); - Log.e(TAG, "Download of " + mRemotePath + " to " + getTmpPath() + ": " + result.getLogMessage(), e); - } - - return result; - } - - - protected int downloadFile(WebdavClient client, File targetFile) throws HttpException, IOException, OperationCancelledException { - int status = -1; - boolean savedFile = false; - mGet = new GetMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); - Iterator it = null; - - FileOutputStream fos = null; - try { - status = client.executeMethod(mGet); - if (isSuccess(status)) { - targetFile.createNewFile(); - BufferedInputStream bis = new BufferedInputStream(mGet.getResponseBodyAsStream()); - fos = new FileOutputStream(targetFile); - long transferred = 0; - - Header contentLength = mGet.getResponseHeader("Content-Length"); - long totalToTransfer = (contentLength != null && contentLength.getValue().length() >0) ? Long.parseLong(contentLength.getValue()) : 0; - - byte[] bytes = new byte[4096]; - int readResult = 0; - while ((readResult = bis.read(bytes)) != -1) { - synchronized(mCancellationRequested) { - if (mCancellationRequested.get()) { - mGet.abort(); - throw new OperationCancelledException(); - } - } - fos.write(bytes, 0, readResult); - transferred += readResult; - synchronized (mDataTransferListeners) { - it = mDataTransferListeners.iterator(); - while (it.hasNext()) { - it.next().onTransferProgress(readResult, transferred, totalToTransfer, targetFile.getName()); - } - } - } - savedFile = true; - /* - Header modificationTime = mGet.getResponseHeader("Last-Modified"); - if (modificationTime != null) { - Date d = WebdavUtils.parseResponseDate((String) modificationTime.getValue()); - mModificationTimestamp = (d != null) ? d.getTime() : 0; - } - */ - - } else { - client.exhaustResponse(mGet.getResponseBodyAsStream()); - } - - } finally { - if (fos != null) fos.close(); - if (!savedFile && targetFile.exists()) { - targetFile.delete(); - } - mGet.releaseConnection(); // let the connection available for other methods - } - return status; - } - - private boolean isSuccess(int status) { - return (status == HttpStatus.SC_OK); - } - - private String getTmpPath() { - return mDownloadFolderPath + mRemotePath; - } - - public void addDatatransferProgressListener (OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.add(listener); - } - } - - public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.remove(listener); - } - } - - public void cancel() { - mCancellationRequested.set(true); // atomic set; there is no need of synchronizing it - } -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ExistenceCheckRemoteOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ExistenceCheckRemoteOperation.java deleted file mode 100644 index e2c936fd..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ExistenceCheckRemoteOperation.java +++ /dev/null @@ -1,104 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import org.apache.commons.httpclient.HttpStatus; -import org.apache.commons.httpclient.methods.HeadMethod; - -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; - -import android.content.Context; -import android.net.ConnectivityManager; -import android.util.Log; - -/** - * Operation to check the existence or absence of a path in a remote server. - * - * @author David A. Velasco - */ -public class ExistenceCheckRemoteOperation extends RemoteOperation { - - /** Maximum time to wait for a response from the server in MILLISECONDs. */ - public static final int TIMEOUT = 10000; - - private static final String TAG = ExistenceCheckRemoteOperation.class.getSimpleName(); - - private String mPath; - private Context mContext; - private boolean mSuccessIfAbsent; - - - /** - * Full constructor. Success of the operation will depend upon the value of successIfAbsent. - * - * @param path Path to append to the URL owned by the client instance. - * @param context Android application context. - * @param successIfAbsent When 'true', the operation finishes in success if the path does NOT exist in the remote server (HTTP 404). - */ - public ExistenceCheckRemoteOperation(String path, Context context, boolean successIfAbsent) { - mPath = (path != null) ? path : ""; - mContext = context; - mSuccessIfAbsent = successIfAbsent; - } - - - @Override - protected RemoteOperationResult run(WebdavClient client) { - if (!isOnline()) { - return new RemoteOperationResult(RemoteOperationResult.ResultCode.NO_NETWORK_CONNECTION); - } - RemoteOperationResult result = null; - HeadMethod head = null; - try { - head = new HeadMethod(client.getBaseUri() + WebdavUtils.encodePath(mPath)); - int status = client.executeMethod(head, TIMEOUT, TIMEOUT); - client.exhaustResponse(head.getResponseBodyAsStream()); - boolean success = (status == HttpStatus.SC_OK && !mSuccessIfAbsent) || (status == HttpStatus.SC_NOT_FOUND && mSuccessIfAbsent); - result = new RemoteOperationResult(success, status, head.getResponseHeaders()); - Log.d(TAG, "Existence check for " + client.getBaseUri() + WebdavUtils.encodePath(mPath) + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + "finished with HTTP status " + status + (!success?"(FAIL)":"")); - - } catch (Exception e) { - result = new RemoteOperationResult(e); - Log.e(TAG, "Existence check for " + client.getBaseUri() + WebdavUtils.encodePath(mPath) + " targeting for " + (mSuccessIfAbsent ? " absence " : " existence ") + ": " + result.getLogMessage(), result.getException()); - - } finally { - if (head != null) - head.releaseConnection(); - } - return result; - } - - private boolean isOnline() { - ConnectivityManager cm = (ConnectivityManager) mContext - .getSystemService(Context.CONNECTIVITY_SERVICE); - return cm != null && cm.getActiveNetworkInfo() != null - && cm.getActiveNetworkInfo().isConnectedOrConnecting(); - } - - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/GetUserNameRemoteOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/GetUserNameRemoteOperation.java deleted file mode 100644 index 717fae22..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/GetUserNameRemoteOperation.java +++ /dev/null @@ -1,127 +0,0 @@ - -/* ownCloud Android client application - * Copyright (C) 2012-2013 ownCloud Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * as published by the Free Software Foundation. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - * - */ -package com.owncloud.android.oc_framework.operations.remote; - -import java.io.IOException; - -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.http.HttpStatus; -import org.json.JSONException; -import org.json.JSONObject; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; - - -/** - * @author masensio - * - * Get the UserName for a SAML connection, from a JSON with the format: - * id - * display-name - * email - */ - -public class GetUserNameRemoteOperation extends RemoteOperation { - - private static final String TAG = GetUserNameRemoteOperation.class.getSimpleName(); - - // HEADER - private static final String HEADER_OCS_API = "OCS-APIREQUEST"; - private static final String HEADER_OCS_API_VALUE = "true"; - - // OCS Route - private static final String OCS_ROUTE ="/index.php/ocs/cloud/user?format=json"; - - // JSON Node names - private static final String NODE_OCS = "ocs"; - private static final String NODE_DATA = "data"; - private static final String NODE_ID = "id"; - private static final String NODE_DISPLAY_NAME= "display-name"; - private static final String NODE_EMAIL= "email"; - - private String mUserName; - - public String getUserName() { - return mUserName; - } - - - public GetUserNameRemoteOperation() { - } - - @Override - protected RemoteOperationResult run(WebdavClient client) { - RemoteOperationResult result = null; - int status = -1; - - // Get Method - GetMethod get = new GetMethod(client.getBaseUri() + OCS_ROUTE); - Log.d(TAG, "URL ------> " + client.getBaseUri() + OCS_ROUTE); - // Add the Header - get.addRequestHeader(HEADER_OCS_API, HEADER_OCS_API_VALUE); - - //Get the user - try { - status = client.executeMethod(get); - if(isSuccess(status)) { - Log.d(TAG, "Obtain RESPONSE"); - String response = get.getResponseBodyAsString(); - - Log.d(TAG, "GET RESPONSE.................... " + response); - - // Parse the response - JSONObject respJSON = new JSONObject(response); - JSONObject respOCS = respJSON.getJSONObject(NODE_OCS); - JSONObject respData = respOCS.getJSONObject(NODE_DATA); - String id = respData.getString(NODE_ID); - String displayName = respData.getString(NODE_DISPLAY_NAME); - String email = respData.getString(NODE_EMAIL); - - // Result - result = new RemoteOperationResult(isSuccess(status), status, (get != null ? get.getResponseHeaders() : null)); - mUserName = displayName; - - Log.d(TAG, "Response: " + id + " - " + displayName + " - " + email); - - } - } catch (HttpException e) { - result = new RemoteOperationResult(e); - e.printStackTrace(); - } catch (IOException e) { - result = new RemoteOperationResult(e); - e.printStackTrace(); - } catch (JSONException e) { - result = new RemoteOperationResult(e); - e.printStackTrace(); - } finally { - get.releaseConnection(); - } - - return result; - } - - private boolean isSuccess(int status) { - return (status == HttpStatus.SC_OK); - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ReadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ReadRemoteFileOperation.java deleted file mode 100644 index 5615543e..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ReadRemoteFileOperation.java +++ /dev/null @@ -1,115 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ -package com.owncloud.android.oc_framework.operations.remote; - -import java.util.ArrayList; - -import org.apache.http.HttpStatus; -import org.apache.jackrabbit.webdav.DavConstants; -import org.apache.jackrabbit.webdav.MultiStatus; -import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavEntry; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.RemoteFile; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; - - -/** - * Remote operation performing the read a file from the ownCloud server. - * - * @author David A. Velasco - * @author masensio - */ - -public class ReadRemoteFileOperation extends RemoteOperation { - - private static final String TAG = ReadRemoteFileOperation.class.getSimpleName(); - private static final int SYNC_READ_TIMEOUT = 10000; - private static final int SYNC_CONNECTION_TIMEOUT = 5000; - - private String mRemotePath; - - - /** - * Constructor - * - * @param remotePath Remote path of the file. - */ - public ReadRemoteFileOperation(String remotePath) { - mRemotePath = remotePath; - } - - /** - * Performs the read operation. - * - * @param client Client object to communicate with the remote ownCloud server. - */ - @Override - protected RemoteOperationResult run(WebdavClient client) { - PropFindMethod propfind = null; - RemoteOperationResult result = null; - - /// take the duty of check the server for the current state of the file there - try { - propfind = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath), - DavConstants.PROPFIND_ALL_PROP, - DavConstants.DEPTH_0); - int status; - status = client.executeMethod(propfind, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT); - - boolean isMultiStatus = status == HttpStatus.SC_MULTI_STATUS; - if (isMultiStatus) { - // Parse response - MultiStatus resp = propfind.getResponseBodyAsMultiStatus(); - WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath()); - RemoteFile remoteFile = new RemoteFile(we); - ArrayList files = new ArrayList(); - files.add(remoteFile); - - // Result of the operation - result = new RemoteOperationResult(true, status, propfind.getResponseHeaders()); - result.setData(files); - - } else { - client.exhaustResponse(propfind.getResponseBodyAsStream()); - result = new RemoteOperationResult(false, status, propfind.getResponseHeaders()); - } - - } catch (Exception e) { - result = new RemoteOperationResult(e); - e.printStackTrace(); - Log.e(TAG, "Synchronizing file " + mRemotePath + ": " + result.getLogMessage(), result.getException()); - } finally { - if (propfind != null) - propfind.releaseConnection(); - } - return result; - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ReadRemoteFolderOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ReadRemoteFolderOperation.java deleted file mode 100644 index fb03449c..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/ReadRemoteFolderOperation.java +++ /dev/null @@ -1,169 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import java.util.ArrayList; - -import org.apache.http.HttpStatus; -import org.apache.jackrabbit.webdav.DavConstants; -import org.apache.jackrabbit.webdav.MultiStatus; -import org.apache.jackrabbit.webdav.client.methods.PropFindMethod; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavEntry; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.RemoteFile; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; - -/** - * Remote operation performing the read of remote file or folder in the ownCloud server. - * - * @author David A. Velasco - * @author masensio - */ - -public class ReadRemoteFolderOperation extends RemoteOperation { - - private static final String TAG = ReadRemoteFolderOperation.class.getSimpleName(); - - private String mRemotePath; - private ArrayList mFolderAndFiles; - - /** - * Constructor - * - * @param remotePath Remote path of the file. - */ - public ReadRemoteFolderOperation(String remotePath) { - mRemotePath = remotePath; - } - - /** - * Performs the read operation. - * - * @param client Client object to communicate with the remote ownCloud server. - */ - @Override - protected RemoteOperationResult run(WebdavClient client) { - RemoteOperationResult result = null; - PropFindMethod query = null; - - try { - // remote request - query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath), - DavConstants.PROPFIND_ALL_PROP, - DavConstants.DEPTH_1); - int status = client.executeMethod(query); - - // check and process response - if (isMultiStatus(status)) { - // get data from remote folder - MultiStatus dataInServer = query.getResponseBodyAsMultiStatus(); - readData(dataInServer, client); - - // Result of the operation - result = new RemoteOperationResult(true, status, query.getResponseHeaders()); - // Add data to the result - if (result.isSuccess()) { - result.setData(mFolderAndFiles); - } - } else { - // synchronization failed - client.exhaustResponse(query.getResponseBodyAsStream()); - result = new RemoteOperationResult(false, status, query.getResponseHeaders()); - } - - } catch (Exception e) { - result = new RemoteOperationResult(e); - - - } finally { - if (query != null) - query.releaseConnection(); // let the connection available for other methods - if (result.isSuccess()) { - Log.i(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage()); - } else { - if (result.isException()) { - Log.e(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage(), result.getException()); - } else { - Log.e(TAG, "Synchronized " + mRemotePath + ": " + result.getLogMessage()); - } - } - - } - return result; - } - - public boolean isMultiStatus(int status) { - return (status == HttpStatus.SC_MULTI_STATUS); - } - - /** - * Read the data retrieved from the server about the contents of the target folder - * - * - * @param dataInServer Full response got from the server with the data of the target - * folder and its direct children. - * @param client Client instance to the remote server where the data were - * retrieved. - * @return - */ - private void readData(MultiStatus dataInServer, WebdavClient client) { - mFolderAndFiles = new ArrayList(); - - // parse data from remote folder - WebdavEntry we = new WebdavEntry(dataInServer.getResponses()[0], client.getBaseUri().getPath()); - mFolderAndFiles.add(fillOCFile(we)); - - // loop to update every child - RemoteFile remoteFile = null; - for (int i = 1; i < dataInServer.getResponses().length; ++i) { - /// new OCFile instance with the data from the server - we = new WebdavEntry(dataInServer.getResponses()[i], client.getBaseUri().getPath()); - remoteFile = fillOCFile(we); - mFolderAndFiles.add(remoteFile); - } - - } - - /** - * Creates and populates a new {@link RemoteFile} object with the data read from the server. - * - * @param we WebDAV entry read from the server for a WebDAV resource (remote file or folder). - * @return New OCFile instance representing the remote resource described by we. - */ - private RemoteFile fillOCFile(WebdavEntry we) { - RemoteFile file = new RemoteFile(we.decodedPath()); - file.setCreationTimestamp(we.createTimestamp()); - file.setLength(we.contentLength()); - file.setMimeType(we.contentType()); - file.setModifiedTimestamp(we.modifiedTimestamp()); - file.setEtag(we.etag()); - return file; - } -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/RemoveRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/RemoveRemoteFileOperation.java deleted file mode 100644 index 1c3570c1..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/RemoveRemoteFileOperation.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import org.apache.commons.httpclient.HttpStatus; -import org.apache.jackrabbit.webdav.client.methods.DeleteMethod; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; - -/** - * Remote operation performing the removal of a remote file or folder in the ownCloud server. - * - * @author David A. Velasco - * @author masensio - */ -public class RemoveRemoteFileOperation extends RemoteOperation { - private static final String TAG = RemoveRemoteFileOperation.class.getSimpleName(); - - private static final int REMOVE_READ_TIMEOUT = 10000; - private static final int REMOVE_CONNECTION_TIMEOUT = 5000; - - private String mRemotePath; - - /** - * Constructor - * - * @param remotePath RemotePath of the remote file or folder to remove from the server - */ - public RemoveRemoteFileOperation(String remotePath) { - mRemotePath = remotePath; - } - - /** - * Performs the rename operation. - * - * @param client Client object to communicate with the remote ownCloud server. - */ - @Override - protected RemoteOperationResult run(WebdavClient client) { - RemoteOperationResult result = null; - DeleteMethod delete = null; - - try { - delete = new DeleteMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); - int status = client.executeMethod(delete, REMOVE_READ_TIMEOUT, REMOVE_CONNECTION_TIMEOUT); - - delete.getResponseBodyAsString(); // exhaust the response, although not interesting - result = new RemoteOperationResult((delete.succeeded() || status == HttpStatus.SC_NOT_FOUND), status, delete.getResponseHeaders()); - Log.i(TAG, "Remove " + mRemotePath + ": " + result.getLogMessage()); - - } catch (Exception e) { - result = new RemoteOperationResult(e); - Log.e(TAG, "Remove " + mRemotePath + ": " + result.getLogMessage(), e); - - } finally { - if (delete != null) - delete.releaseConnection(); - } - - return result; - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/RenameRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/RenameRemoteFileOperation.java deleted file mode 100644 index c3056e5d..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/RenameRemoteFileOperation.java +++ /dev/null @@ -1,153 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import java.io.File; - -import org.apache.jackrabbit.webdav.client.methods.DavMethodBase; - -import android.util.Log; - -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.utils.FileUtils; - - -/** - * Remote operation performing the rename of a remote file or folder in the ownCloud server. - * - * @author David A. Velasco - * @author masensio - */ -public class RenameRemoteFileOperation extends RemoteOperation { - - private static final String TAG = RenameRemoteFileOperation.class.getSimpleName(); - - private static final int RENAME_READ_TIMEOUT = 10000; - private static final int RENAME_CONNECTION_TIMEOUT = 5000; - - private String mOldName; - private String mOldRemotePath; - private String mNewName; - private String mNewRemotePath; - - - /** - * Constructor - * - * @param oldName Old name of the file. - * @param oldRemotePath Old remote path of the file. - * @param newName New name to set as the name of file. - * @param isFolder 'true' for folder and 'false' for files - */ - public RenameRemoteFileOperation(String oldName, String oldRemotePath, String newName, boolean isFolder) { - mOldName = oldName; - mOldRemotePath = oldRemotePath; - mNewName = newName; - - String parent = (new File(mOldRemotePath)).getParent(); - parent = (parent.endsWith(FileUtils.PATH_SEPARATOR)) ? parent : parent + FileUtils.PATH_SEPARATOR; - mNewRemotePath = parent + mNewName; - if (isFolder) { - mNewRemotePath += FileUtils.PATH_SEPARATOR; - } - } - - /** - * Performs the rename operation. - * - * @param client Client object to communicate with the remote ownCloud server. - */ - @Override - protected RemoteOperationResult run(WebdavClient client) { - RemoteOperationResult result = null; - - LocalMoveMethod move = null; - - boolean noInvalidChars = FileUtils.isValidPath(mNewRemotePath); - - if (noInvalidChars) { - try { - - if (mNewName.equals(mOldName)) { - return new RemoteOperationResult(ResultCode.OK); - } - - - // check if a file with the new name already exists - if (client.existsFile(mNewRemotePath)) { - return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE); - } - - move = new LocalMoveMethod( client.getBaseUri() + WebdavUtils.encodePath(mOldRemotePath), - client.getBaseUri() + WebdavUtils.encodePath(mNewRemotePath)); - int status = client.executeMethod(move, RENAME_READ_TIMEOUT, RENAME_CONNECTION_TIMEOUT); - - move.getResponseBodyAsString(); // exhaust response, although not interesting - result = new RemoteOperationResult(move.succeeded(), status, move.getResponseHeaders()); - Log.i(TAG, "Rename " + mOldRemotePath + " to " + mNewRemotePath + ": " + result.getLogMessage()); - - } catch (Exception e) { - result = new RemoteOperationResult(e); - Log.e(TAG, "Rename " + mOldRemotePath + " to " + ((mNewRemotePath==null) ? mNewName : mNewRemotePath) + ": " + result.getLogMessage(), e); - - } finally { - if (move != null) - move.releaseConnection(); - } - } else { - result = new RemoteOperationResult(ResultCode.INVALID_CHARACTER_IN_NAME); - } - - return result; - } - - /** - * Move operation - * - */ - private class LocalMoveMethod extends DavMethodBase { - - public LocalMoveMethod(String uri, String dest) { - super(uri); - addRequestHeader(new org.apache.commons.httpclient.Header("Destination", dest)); - } - - @Override - public String getName() { - return "MOVE"; - } - - @Override - protected boolean isSuccess(int status) { - return status == 201 || status == 204; - } - - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/UploadRemoteFileOperation.java b/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/UploadRemoteFileOperation.java deleted file mode 100644 index b23d1ff5..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/operations/remote/UploadRemoteFileOperation.java +++ /dev/null @@ -1,154 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.operations.remote; - -import java.io.File; -import java.io.IOException; -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.apache.commons.httpclient.HttpException; -import org.apache.commons.httpclient.methods.PutMethod; -import org.apache.commons.httpclient.methods.RequestEntity; -import org.apache.http.HttpStatus; - -import com.owncloud.android.oc_framework.network.ProgressiveDataTransferer; -import com.owncloud.android.oc_framework.network.webdav.FileRequestEntity; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.OperationCancelledException; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; - -/** - * Remote operation performing the upload of a remote file to the ownCloud server. - * - * @author David A. Velasco - * @author masensio - */ - -public class UploadRemoteFileOperation extends RemoteOperation { - - - protected String mStoragePath; - protected String mRemotePath; - protected String mMimeType; - protected PutMethod mPutMethod = null; - - private final AtomicBoolean mCancellationRequested = new AtomicBoolean(false); - protected Set mDataTransferListeners = new HashSet(); - - protected RequestEntity mEntity = null; - - public UploadRemoteFileOperation(String storagePath, String remotePath, String mimeType) { - mStoragePath = storagePath; - mRemotePath = remotePath; - mMimeType = mimeType; - } - - @Override - protected RemoteOperationResult run(WebdavClient client) { - RemoteOperationResult result = null; - - try { - // / perform the upload - synchronized (mCancellationRequested) { - if (mCancellationRequested.get()) { - throw new OperationCancelledException(); - } else { - mPutMethod = new PutMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath)); - } - } - - int status = uploadFile(client); - - result = new RemoteOperationResult(isSuccess(status), status, (mPutMethod != null ? mPutMethod.getResponseHeaders() : null)); - - } catch (Exception e) { - // TODO something cleaner with cancellations - if (mCancellationRequested.get()) { - result = new RemoteOperationResult(new OperationCancelledException()); - } else { - result = new RemoteOperationResult(e); - } - } - return result; - } - - public boolean isSuccess(int status) { - return ((status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED || status == HttpStatus.SC_NO_CONTENT)); - } - - protected int uploadFile(WebdavClient client) throws HttpException, IOException, OperationCancelledException { - int status = -1; - try { - File f = new File(mStoragePath); - mEntity = new FileRequestEntity(f, mMimeType); - synchronized (mDataTransferListeners) { - ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListeners(mDataTransferListeners); - } - mPutMethod.setRequestEntity(mEntity); - status = client.executeMethod(mPutMethod); - client.exhaustResponse(mPutMethod.getResponseBodyAsStream()); - - } finally { - mPutMethod.releaseConnection(); // let the connection available for other methods - } - return status; - } - - public Set getDataTransferListeners() { - return mDataTransferListeners; - } - - public void addDatatransferProgressListener (OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.add(listener); - } - if (mEntity != null) { - ((ProgressiveDataTransferer)mEntity).addDatatransferProgressListener(listener); - } - } - - public void removeDatatransferProgressListener(OnDatatransferProgressListener listener) { - synchronized (mDataTransferListeners) { - mDataTransferListeners.remove(listener); - } - if (mEntity != null) { - ((ProgressiveDataTransferer)mEntity).removeDatatransferProgressListener(listener); - } - } - - public void cancel() { - synchronized (mCancellationRequested) { - mCancellationRequested.set(true); - if (mPutMethod != null) - mPutMethod.abort(); - } - } - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/utils/FileUtils.java b/oc_framework/src/com/owncloud/android/oc_framework/utils/FileUtils.java deleted file mode 100644 index f6c5e81b..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/utils/FileUtils.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.utils; - -import java.io.File; - -import android.util.Log; - -public class FileUtils { - - public static final String PATH_SEPARATOR = "/"; - - - public static String getParentPath(String remotePath) { - String parentPath = new File(remotePath).getParent(); - parentPath = parentPath.endsWith(PATH_SEPARATOR) ? parentPath : parentPath + PATH_SEPARATOR; - return parentPath; - } - - /** - * Validate the fileName to detect if contains any forbidden character: / , \ , < , > , : , " , | , ? , * - * @param fileName - * @return - */ - public static boolean isValidName(String fileName) { - boolean result = true; - - Log.d("FileUtils", "fileName =======" + fileName); - if (fileName.contains(PATH_SEPARATOR) || - fileName.contains("\\") || fileName.contains("<") || fileName.contains(">") || - fileName.contains(":") || fileName.contains("\"") || fileName.contains("|") || - fileName.contains("?") || fileName.contains("*")) { - result = false; - } - return result; - } - - /** - * Validate the path to detect if contains any forbidden character: \ , < , > , : , " , | , ? , * - * @param path - * @return - */ - public static boolean isValidPath(String path) { - boolean result = true; - - Log.d("FileUtils", "path ....... " + path); - if (path.contains("\\") || path.contains("<") || path.contains(">") || - path.contains(":") || path.contains("\"") || path.contains("|") || - path.contains("?") || path.contains("*")) { - result = false; - } - return result; - } - - -} diff --git a/oc_framework/src/com/owncloud/android/oc_framework/utils/OwnCloudVersion.java b/oc_framework/src/com/owncloud/android/oc_framework/utils/OwnCloudVersion.java deleted file mode 100644 index 868b9bdc..00000000 --- a/oc_framework/src/com/owncloud/android/oc_framework/utils/OwnCloudVersion.java +++ /dev/null @@ -1,92 +0,0 @@ -/* ownCloud Android Library is available under MIT license - * Copyright (C) 2014 ownCloud (http://www.owncloud.org/) - * Copyright (C) 2012 Bartek Przybylski - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, - * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF - * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS - * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN - * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN - * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - */ - -package com.owncloud.android.oc_framework.utils; - -public class OwnCloudVersion implements Comparable { - public static final OwnCloudVersion owncloud_v1 = new OwnCloudVersion( - 0x010000); - public static final OwnCloudVersion owncloud_v2 = new OwnCloudVersion( - 0x020000); - public static final OwnCloudVersion owncloud_v3 = new OwnCloudVersion( - 0x030000); - public static final OwnCloudVersion owncloud_v4 = new OwnCloudVersion( - 0x040000); - public static final OwnCloudVersion owncloud_v4_5 = new OwnCloudVersion( - 0x040500); - - // format is in version - // 0xAABBCC - // for version AA.BB.CC - // ie version 2.0.3 will be stored as 0x030003 - private int mVersion; - private boolean mIsValid; - - public OwnCloudVersion(int version) { - mVersion = version; - mIsValid = true; - } - - public OwnCloudVersion(String version) { - mVersion = 0; - mIsValid = false; - parseVersionString(version); - } - - public String toString() { - return ((mVersion >> 16) % 256) + "." + ((mVersion >> 8) % 256) + "." - + ((mVersion) % 256); - } - - public boolean isVersionValid() { - return mIsValid; - } - - @Override - public int compareTo(OwnCloudVersion another) { - return another.mVersion == mVersion ? 0 - : another.mVersion < mVersion ? 1 : -1; - } - - private void parseVersionString(String version) { - try { - String[] nums = version.split("\\."); - if (nums.length > 0) { - mVersion += Integer.parseInt(nums[0]); - } - mVersion = mVersion << 8; - if (nums.length > 1) { - mVersion += Integer.parseInt(nums[1]); - } - mVersion = mVersion << 8; - if (nums.length > 2) { - mVersion += Integer.parseInt(nums[2]); - } - mIsValid = true; - } catch (Exception e) { - mIsValid = false; - } - } -} diff --git a/src/com/owncloud/android/authentication/AccountAuthenticator.java b/src/com/owncloud/android/authentication/AccountAuthenticator.java index 78a8575e..49a93552 100644 --- a/src/com/owncloud/android/authentication/AccountAuthenticator.java +++ b/src/com/owncloud/android/authentication/AccountAuthenticator.java @@ -28,7 +28,7 @@ import android.os.Bundle; import android.os.Handler; import android.widget.Toast; -import com.owncloud.android.oc_framework.accounts.AccountTypeUtils; +import com.owncloud.android.lib.accounts.AccountTypeUtils; import com.owncloud.android.utils.Log_OC; diff --git a/src/com/owncloud/android/authentication/AccountUtils.java b/src/com/owncloud/android/authentication/AccountUtils.java index 33c7e6a9..5f0441c5 100644 --- a/src/com/owncloud/android/authentication/AccountUtils.java +++ b/src/com/owncloud/android/authentication/AccountUtils.java @@ -19,8 +19,8 @@ package com.owncloud.android.authentication; import com.owncloud.android.MainApp; -import com.owncloud.android.oc_framework.accounts.AccountTypeUtils; -import com.owncloud.android.oc_framework.utils.OwnCloudVersion; +import com.owncloud.android.lib.accounts.AccountTypeUtils; +import com.owncloud.android.lib.utils.OwnCloudVersion; import android.accounts.Account; import android.accounts.AccountManager; diff --git a/src/com/owncloud/android/authentication/AuthenticatorActivity.java b/src/com/owncloud/android/authentication/AuthenticatorActivity.java index ad40a066..3a11ea62 100644 --- a/src/com/owncloud/android/authentication/AuthenticatorActivity.java +++ b/src/com/owncloud/android/authentication/AuthenticatorActivity.java @@ -53,23 +53,23 @@ import com.actionbarsherlock.app.SherlockDialogFragment; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener; -import com.owncloud.android.oc_framework.accounts.AccountTypeUtils; -import com.owncloud.android.oc_framework.accounts.OwnCloudAccount; -import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; +import com.owncloud.android.lib.accounts.AccountTypeUtils; +import com.owncloud.android.lib.accounts.OwnCloudAccount; +import com.owncloud.android.lib.network.OwnCloudClientFactory; +import com.owncloud.android.lib.network.OwnCloudClient; import com.owncloud.android.operations.OAuth2GetAccessToken; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; import com.owncloud.android.operations.OwnCloudServerCheckOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.operations.remote.ExistenceCheckRemoteOperation; -import com.owncloud.android.oc_framework.operations.remote.GetUserNameRemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.remote.ExistenceCheckRemoteOperation; +import com.owncloud.android.lib.operations.remote.GetUserNameRemoteOperation; import com.owncloud.android.ui.dialog.SamlWebViewDialog; import com.owncloud.android.ui.dialog.SslValidatorDialog; import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener; import com.owncloud.android.utils.Log_OC; -import com.owncloud.android.oc_framework.utils.OwnCloudVersion; +import com.owncloud.android.lib.utils.OwnCloudVersion; /** * This Activity is used to add an ownCloud account to the App @@ -524,8 +524,8 @@ implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList getString(R.string.oauth2_redirect_uri), getString(R.string.oauth2_grant_type), queryParameters); - //WebdavClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext()); - WebdavClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext(), true); + //OwnCloudClient client = OwnCloudClientUtils.createOwnCloudClient(Uri.parse(getString(R.string.oauth2_url_endpoint_access)), getApplicationContext()); + OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mOAuthTokenEndpointText.getText().toString().trim()), getApplicationContext(), true); operation.execute(client, this, mHandler); } @@ -589,7 +589,7 @@ implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList mServerStatusIcon = R.drawable.progress_small; showServerStatus(); mOcServerChkOperation = new OwnCloudServerCheckOperation(uri, this); - WebdavClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(uri), this, true); + OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(uri), this, true); mOperationThread = mOcServerChkOperation.execute(client, this, mHandler); } else { mServerStatusText = 0; @@ -716,7 +716,7 @@ implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList /// test credentials accessing the root folder mAuthCheckOperation = new ExistenceCheckRemoteOperation("", this, false); - WebdavClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true); + OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true); client.setBasicCredentials(username, password); mOperationThread = mAuthCheckOperation.execute(client, this, mHandler); } @@ -765,7 +765,7 @@ implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList /// test credentials accessing the root folder mAuthCheckOperation = new ExistenceCheckRemoteOperation("", this, false); - WebdavClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, false); + OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, false); mOperationThread = mAuthCheckOperation.execute(client, this, mHandler); } @@ -1115,7 +1115,7 @@ implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN); Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken); mAuthCheckOperation = new ExistenceCheckRemoteOperation("", this, false); - WebdavClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true); + OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl + webdav_path), this, true); client.setBearerCredentials(mAuthToken); mAuthCheckOperation.execute(client, this, mHandler); @@ -1598,7 +1598,7 @@ implements OnRemoteOperationListener, OnSslValidatorListener, OnFocusChangeList mAuthToken = sessionCookie; GetUserNameRemoteOperation getUserOperation = new GetUserNameRemoteOperation(); - WebdavClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl), getApplicationContext(), true); + OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mHostBaseUrl), getApplicationContext(), true); client.setSsoSessionCookie(mAuthToken); getUserOperation.execute(client, this, mHandler); } diff --git a/src/com/owncloud/android/files/OwnCloudFileObserver.java b/src/com/owncloud/android/files/OwnCloudFileObserver.java index 68c97e4f..ade4c61c 100644 --- a/src/com/owncloud/android/files/OwnCloudFileObserver.java +++ b/src/com/owncloud/android/files/OwnCloudFileObserver.java @@ -22,9 +22,9 @@ import java.io.File; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; import com.owncloud.android.operations.SynchronizeFileOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; import com.owncloud.android.ui.activity.ConflictsResolveActivity; import com.owncloud.android.utils.Log_OC; diff --git a/src/com/owncloud/android/files/services/FileDownloader.java b/src/com/owncloud/android/files/services/FileDownloader.java index 0dee6050..c27ec0cc 100644 --- a/src/com/owncloud/android/files/services/FileDownloader.java +++ b/src/com/owncloud/android/files/services/FileDownloader.java @@ -33,12 +33,12 @@ import com.owncloud.android.authentication.AuthenticatorActivity; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.network.OwnCloudClientFactory; +import com.owncloud.android.lib.network.OwnCloudClient; import com.owncloud.android.operations.DownloadFileOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; import com.owncloud.android.ui.activity.FileActivity; import com.owncloud.android.ui.activity.FileDisplayActivity; import com.owncloud.android.ui.preview.PreviewImageActivity; @@ -79,7 +79,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis private Looper mServiceLooper; private ServiceHandler mServiceHandler; private IBinder mBinder; - private WebdavClient mDownloadClient = null; + private OwnCloudClient mDownloadClient = null; private Account mLastAccount = null; private FileDataStorageManager mStorageManager; diff --git a/src/com/owncloud/android/files/services/FileUploader.java b/src/com/owncloud/android/files/services/FileUploader.java index 4b4de805..fdbe055e 100644 --- a/src/com/owncloud/android/files/services/FileUploader.java +++ b/src/com/owncloud/android/files/services/FileUploader.java @@ -34,18 +34,18 @@ import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.db.DbHandler; import com.owncloud.android.operations.CreateFolderOperation; -import com.owncloud.android.oc_framework.operations.RemoteFile; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteFile; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; import com.owncloud.android.operations.UploadFileOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.operations.remote.ExistenceCheckRemoteOperation; -import com.owncloud.android.oc_framework.operations.remote.ReadRemoteFileOperation; -import com.owncloud.android.oc_framework.utils.OwnCloudVersion; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.accounts.OwnCloudAccount; -import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.remote.ExistenceCheckRemoteOperation; +import com.owncloud.android.lib.operations.remote.ReadRemoteFileOperation; +import com.owncloud.android.lib.utils.OwnCloudVersion; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.accounts.OwnCloudAccount; +import com.owncloud.android.lib.network.OwnCloudClientFactory; +import com.owncloud.android.lib.network.OwnCloudClient; import com.owncloud.android.ui.activity.FailedUploadActivity; import com.owncloud.android.ui.activity.FileActivity; import com.owncloud.android.ui.activity.FileDisplayActivity; @@ -108,7 +108,7 @@ public class FileUploader extends Service implements OnDatatransferProgressListe private Looper mServiceLooper; private ServiceHandler mServiceHandler; private IBinder mBinder; - private WebdavClient mUploadClient = null; + private OwnCloudClient mUploadClient = null; private Account mLastAccount = null; private FileDataStorageManager mStorageManager; diff --git a/src/com/owncloud/android/operations/CreateFolderOperation.java b/src/com/owncloud/android/operations/CreateFolderOperation.java index 1cf1f84d..9ba118e6 100644 --- a/src/com/owncloud/android/operations/CreateFolderOperation.java +++ b/src/com/owncloud/android/operations/CreateFolderOperation.java @@ -19,11 +19,11 @@ package com.owncloud.android.operations; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.remote.CreateRemoteFolderOperation; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.remote.CreateRemoteFolderOperation; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.Log_OC; @@ -58,7 +58,7 @@ public class CreateFolderOperation extends RemoteOperation implements OnRemoteOp @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { CreateRemoteFolderOperation operation = new CreateRemoteFolderOperation(mRemotePath, mCreateFullPath); RemoteOperationResult result = operation.execute(client); diff --git a/src/com/owncloud/android/operations/DownloadFileOperation.java b/src/com/owncloud/android/operations/DownloadFileOperation.java index d9be6f04..24990a2d 100644 --- a/src/com/owncloud/android/operations/DownloadFileOperation.java +++ b/src/com/owncloud/android/operations/DownloadFileOperation.java @@ -23,11 +23,11 @@ import java.util.Iterator; import java.util.Set; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.remote.DownloadRemoteFileOperation; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.remote.DownloadRemoteFileOperation; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.Log_OC; @@ -118,7 +118,7 @@ public class DownloadFileOperation extends RemoteOperation { } @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; File newFile = null; boolean moved = true; diff --git a/src/com/owncloud/android/operations/OAuth2GetAccessToken.java b/src/com/owncloud/android/operations/OAuth2GetAccessToken.java index d3926453..57295ad6 100644 --- a/src/com/owncloud/android/operations/OAuth2GetAccessToken.java +++ b/src/com/owncloud/android/operations/OAuth2GetAccessToken.java @@ -9,10 +9,10 @@ import org.json.JSONException; import org.json.JSONObject; import com.owncloud.android.authentication.OAuth2Constants; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; import com.owncloud.android.utils.Log_OC; @@ -48,7 +48,7 @@ public class OAuth2GetAccessToken extends RemoteOperation { } @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; PostMethod postMethod = null; diff --git a/src/com/owncloud/android/operations/OwnCloudServerCheckOperation.java b/src/com/owncloud/android/operations/OwnCloudServerCheckOperation.java index 82096854..f3eca9c2 100644 --- a/src/com/owncloud/android/operations/OwnCloudServerCheckOperation.java +++ b/src/com/owncloud/android/operations/OwnCloudServerCheckOperation.java @@ -23,10 +23,10 @@ import org.json.JSONException; import org.json.JSONObject; import com.owncloud.android.authentication.AccountUtils; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.utils.OwnCloudVersion; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.utils.OwnCloudVersion; import com.owncloud.android.utils.Log_OC; import android.content.Context; @@ -55,7 +55,7 @@ public class OwnCloudServerCheckOperation extends RemoteOperation { return mOCVersion; } - private boolean tryConnection(WebdavClient wc, String urlSt) { + private boolean tryConnection(OwnCloudClient wc, String urlSt) { boolean retval = false; GetMethod get = null; try { @@ -117,7 +117,7 @@ public class OwnCloudServerCheckOperation extends RemoteOperation { } @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { if (!isOnline()) { return new RemoteOperationResult(RemoteOperationResult.ResultCode.NO_NETWORK_CONNECTION); } diff --git a/src/com/owncloud/android/operations/RemoveFileOperation.java b/src/com/owncloud/android/operations/RemoveFileOperation.java index 0ab8ac3c..5cd668cc 100644 --- a/src/com/owncloud/android/operations/RemoveFileOperation.java +++ b/src/com/owncloud/android/operations/RemoveFileOperation.java @@ -19,11 +19,11 @@ package com.owncloud.android.operations; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.operations.remote.RemoveRemoteFileOperation; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.remote.RemoveRemoteFileOperation; /** @@ -69,7 +69,7 @@ public class RemoveFileOperation extends RemoteOperation { * @param client Client object to communicate with the remote ownCloud server. */ @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; RemoveRemoteFileOperation operation = new RemoveRemoteFileOperation(mFileToRemove.getRemotePath()); diff --git a/src/com/owncloud/android/operations/RenameFileOperation.java b/src/com/owncloud/android/operations/RenameFileOperation.java index be6cdcce..d77020c6 100644 --- a/src/com/owncloud/android/operations/RenameFileOperation.java +++ b/src/com/owncloud/android/operations/RenameFileOperation.java @@ -22,11 +22,11 @@ import java.io.IOException; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.operations.remote.RenameRemoteFileOperation; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.remote.RenameRemoteFileOperation; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.Log_OC; @@ -77,7 +77,7 @@ public class RenameFileOperation extends RemoteOperation { * @param client Client object to communicate with the remote ownCloud server. */ @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; // check if the new name is valid in the local file system diff --git a/src/com/owncloud/android/operations/SynchronizeFileOperation.java b/src/com/owncloud/android/operations/SynchronizeFileOperation.java index 71d7f721..6a79e751 100644 --- a/src/com/owncloud/android/operations/SynchronizeFileOperation.java +++ b/src/com/owncloud/android/operations/SynchronizeFileOperation.java @@ -22,11 +22,11 @@ import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileDownloader; import com.owncloud.android.files.services.FileUploader; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.operations.remote.ReadRemoteFileOperation; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.remote.ReadRemoteFileOperation; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.Log_OC; @@ -72,7 +72,7 @@ public class SynchronizeFileOperation extends RemoteOperation { @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; mTransferWasRequested = false; diff --git a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java index ff387c0f..497058a0 100644 --- a/src/com/owncloud/android/operations/SynchronizeFolderOperation.java +++ b/src/com/owncloud/android/operations/SynchronizeFolderOperation.java @@ -36,13 +36,13 @@ import android.content.Intent; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.operations.remote.ReadRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.ReadRemoteFolderOperation; -import com.owncloud.android.oc_framework.operations.RemoteFile; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.remote.ReadRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.ReadRemoteFolderOperation; +import com.owncloud.android.lib.operations.common.RemoteFile; import com.owncloud.android.syncadapter.FileSyncService; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.Log_OC; @@ -155,7 +155,7 @@ public class SynchronizeFolderOperation extends RemoteOperation { * {@inheritDoc} */ @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; mFailsInFavouritesFound = 0; mConflictsFound = 0; @@ -180,7 +180,7 @@ public class SynchronizeFolderOperation extends RemoteOperation { } - private RemoteOperationResult checkForChanges(WebdavClient client) { + private RemoteOperationResult checkForChanges(OwnCloudClient client) { mRemoteFolderChanged = false; RemoteOperationResult result = null; String remotePath = null; @@ -216,7 +216,7 @@ public class SynchronizeFolderOperation extends RemoteOperation { } - private RemoteOperationResult fetchAndSyncRemoteFolder(WebdavClient client) { + private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) { String remotePath = mLocalFolder.getRemotePath(); ReadRemoteFolderOperation operation = new ReadRemoteFolderOperation(remotePath); RemoteOperationResult result = operation.execute(client); @@ -256,7 +256,7 @@ public class SynchronizeFolderOperation extends RemoteOperation { * retrieved. * @return 'True' when any change was made in the local data, 'false' otherwise. */ - private void synchronizeData(ArrayList folderAndFiles, WebdavClient client) { + private void synchronizeData(ArrayList folderAndFiles, OwnCloudClient client) { // get 'fresh data' from the database mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath()); @@ -348,7 +348,7 @@ public class SynchronizeFolderOperation extends RemoteOperation { * @param filesToSyncContents Synchronization operations to execute. * @param client Interface to the remote ownCloud server. */ - private void startContentSynchronizations(List filesToSyncContents, WebdavClient client) { + private void startContentSynchronizations(List filesToSyncContents, OwnCloudClient client) { RemoteOperationResult contentsResult = null; for (SynchronizeFileOperation op: filesToSyncContents) { contentsResult = op.execute(client); // returns without waiting for upload or download finishes diff --git a/src/com/owncloud/android/operations/UpdateOCVersionOperation.java b/src/com/owncloud/android/operations/UpdateOCVersionOperation.java index 7e330604..ca4387ce 100644 --- a/src/com/owncloud/android/operations/UpdateOCVersionOperation.java +++ b/src/com/owncloud/android/operations/UpdateOCVersionOperation.java @@ -23,12 +23,12 @@ import org.json.JSONException; import org.json.JSONObject; import com.owncloud.android.authentication.AccountUtils; -import com.owncloud.android.oc_framework.accounts.OwnCloudAccount; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.utils.OwnCloudVersion; +import com.owncloud.android.lib.accounts.OwnCloudAccount; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.utils.OwnCloudVersion; import com.owncloud.android.utils.Log_OC; import android.accounts.Account; @@ -56,7 +56,7 @@ public class UpdateOCVersionOperation extends RemoteOperation { @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { AccountManager accountMngr = AccountManager.get(mContext); String statUrl = accountMngr.getUserData(mAccount, OwnCloudAccount.Constants.KEY_OC_BASE_URL); statUrl += AccountUtils.STATUS_PATH; diff --git a/src/com/owncloud/android/operations/UploadFileOperation.java b/src/com/owncloud/android/operations/UploadFileOperation.java index 9ceb9751..faa8154b 100644 --- a/src/com/owncloud/android/operations/UploadFileOperation.java +++ b/src/com/owncloud/android/operations/UploadFileOperation.java @@ -33,16 +33,16 @@ import org.apache.commons.httpclient.methods.RequestEntity; import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.services.FileUploader; -import com.owncloud.android.oc_framework.network.ProgressiveDataTransferer; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; -import com.owncloud.android.oc_framework.operations.OperationCancelledException; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; -import com.owncloud.android.oc_framework.operations.remote.ChunkedUploadRemoteFileOperation; -import com.owncloud.android.oc_framework.operations.remote.ExistenceCheckRemoteOperation; -import com.owncloud.android.oc_framework.operations.remote.UploadRemoteFileOperation; +import com.owncloud.android.lib.network.ProgressiveDataTransferer; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.network.OwnCloudClient; +import com.owncloud.android.lib.operations.common.OperationCancelledException; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.remote.ChunkedUploadRemoteFileOperation; +import com.owncloud.android.lib.operations.remote.ExistenceCheckRemoteOperation; +import com.owncloud.android.lib.operations.remote.UploadRemoteFileOperation; import com.owncloud.android.utils.FileStorageUtils; import com.owncloud.android.utils.Log_OC; @@ -186,7 +186,7 @@ public class UploadFileOperation extends RemoteOperation { } @Override - protected RemoteOperationResult run(WebdavClient client) { + protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; boolean localCopyPassed = false, nameCheckPassed = false; File temporalFile = null, originalFile = new File(mOriginalStoragePath), expectedFile = null; @@ -376,7 +376,7 @@ public class UploadFileOperation extends RemoteOperation { * @param string * @return */ - private String getAvailableRemotePath(WebdavClient wc, String remotePath) throws Exception { + private String getAvailableRemotePath(OwnCloudClient wc, String remotePath) throws Exception { boolean check = existsFile(wc, remotePath); if (!check) { return remotePath; @@ -408,7 +408,7 @@ public class UploadFileOperation extends RemoteOperation { } } - private boolean existsFile(WebdavClient client, String remotePath){ + private boolean existsFile(OwnCloudClient client, String remotePath){ ExistenceCheckRemoteOperation existsOperation = new ExistenceCheckRemoteOperation(remotePath, mContext, false); RemoteOperationResult result = existsOperation.execute(client); return result.isSuccess(); diff --git a/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java b/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java index 74d26868..6dcf531c 100644 --- a/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/AbstractOwnCloudSyncAdapter.java @@ -25,10 +25,10 @@ import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import com.owncloud.android.datamodel.FileDataStorageManager; -import com.owncloud.android.oc_framework.accounts.AccountUtils; -import com.owncloud.android.oc_framework.accounts.AccountUtils.AccountNotFoundException; -import com.owncloud.android.oc_framework.network.webdav.OwnCloudClientFactory; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; +import com.owncloud.android.lib.accounts.AccountUtils; +import com.owncloud.android.lib.accounts.AccountUtils.AccountNotFoundException; +import com.owncloud.android.lib.network.OwnCloudClientFactory; +import com.owncloud.android.lib.network.OwnCloudClient; import android.accounts.Account; @@ -56,7 +56,7 @@ public abstract class AbstractOwnCloudSyncAdapter extends private ContentProviderClient mContentProviderClient; private FileDataStorageManager mStoreManager; - private WebdavClient mClient = null; + private OwnCloudClient mClient = null; public AbstractOwnCloudSyncAdapter(Context context, boolean autoInitialize) { super(context, autoInitialize); @@ -105,7 +105,7 @@ public abstract class AbstractOwnCloudSyncAdapter extends mClient = OwnCloudClientFactory.createOwnCloudClient(account, getContext()); } - protected WebdavClient getClient() { + protected OwnCloudClient getClient() { return mClient; } diff --git a/src/com/owncloud/android/syncadapter/ContactSyncAdapter.java b/src/com/owncloud/android/syncadapter/ContactSyncAdapter.java index db7f4c29..f80824fe 100644 --- a/src/com/owncloud/android/syncadapter/ContactSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/ContactSyncAdapter.java @@ -25,7 +25,7 @@ import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ByteArrayEntity; import com.owncloud.android.authentication.AccountUtils; -import com.owncloud.android.oc_framework.accounts.OwnCloudAccount; +import com.owncloud.android.lib.accounts.OwnCloudAccount; import android.accounts.Account; diff --git a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java index 058cfbc4..c47a251f 100644 --- a/src/com/owncloud/android/syncadapter/FileSyncAdapter.java +++ b/src/com/owncloud/android/syncadapter/FileSyncAdapter.java @@ -30,10 +30,10 @@ import com.owncloud.android.R; import com.owncloud.android.authentication.AuthenticatorActivity; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; import com.owncloud.android.operations.SynchronizeFolderOperation; import com.owncloud.android.operations.UpdateOCVersionOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; import com.owncloud.android.ui.activity.ErrorsWhileCopyingHandlerActivity; import com.owncloud.android.utils.DisplayUtils; import com.owncloud.android.utils.Log_OC; diff --git a/src/com/owncloud/android/ui/activity/AccountSelectActivity.java b/src/com/owncloud/android/ui/activity/AccountSelectActivity.java index 3632b5e4..9f8bcfdd 100644 --- a/src/com/owncloud/android/ui/activity/AccountSelectActivity.java +++ b/src/com/owncloud/android/ui/activity/AccountSelectActivity.java @@ -48,7 +48,7 @@ import com.actionbarsherlock.view.MenuInflater; import com.actionbarsherlock.view.MenuItem; import com.owncloud.android.authentication.AuthenticatorActivity; import com.owncloud.android.authentication.AccountUtils; -import com.owncloud.android.oc_framework.accounts.OwnCloudAccount; +import com.owncloud.android.lib.accounts.OwnCloudAccount; import com.owncloud.android.utils.DisplayUtils; import com.owncloud.android.utils.Log_OC; import com.owncloud.android.MainApp; diff --git a/src/com/owncloud/android/ui/activity/FileActivity.java b/src/com/owncloud/android/ui/activity/FileActivity.java index 937d45dd..3d2323fb 100644 --- a/src/com/owncloud/android/ui/activity/FileActivity.java +++ b/src/com/owncloud/android/ui/activity/FileActivity.java @@ -33,7 +33,7 @@ import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.authentication.AccountUtils; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; +import com.owncloud.android.lib.network.webdav.WebdavUtils; import com.owncloud.android.utils.Log_OC; diff --git a/src/com/owncloud/android/ui/activity/FileDisplayActivity.java b/src/com/owncloud/android/ui/activity/FileDisplayActivity.java index 04f525ed..04d0eeec 100644 --- a/src/com/owncloud/android/ui/activity/FileDisplayActivity.java +++ b/src/com/owncloud/android/ui/activity/FileDisplayActivity.java @@ -68,10 +68,10 @@ import com.owncloud.android.files.services.FileUploader; import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder; import com.owncloud.android.files.services.FileUploader.FileUploaderBinder; import com.owncloud.android.operations.CreateFolderOperation; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; import com.owncloud.android.operations.RemoveFileOperation; import com.owncloud.android.operations.RenameFileOperation; import com.owncloud.android.operations.SynchronizeFileOperation; diff --git a/src/com/owncloud/android/ui/activity/Uploader.java b/src/com/owncloud/android/ui/activity/Uploader.java index 85c9e40d..07e6e959 100644 --- a/src/com/owncloud/android/ui/activity/Uploader.java +++ b/src/com/owncloud/android/ui/activity/Uploader.java @@ -329,13 +329,13 @@ public class Uploader extends ListActivity implements OnItemClickListener, andro public void uploadFiles() { try { - //WebdavClient webdav = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext()); + //OwnCloudClient webdav = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext()); ArrayList local = new ArrayList(); ArrayList remote = new ArrayList(); /* TODO - mCreateDir can never be true at this moment; we will replace wdc.createDirectory by CreateFolderOperation when that is fixed - WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext()); + OwnCloudClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext()); // create last directory in path if necessary if (mCreateDir) { wdc.createDirectory(mUploadPath); diff --git a/src/com/owncloud/android/ui/dialog/EditNameDialog.java b/src/com/owncloud/android/ui/dialog/EditNameDialog.java index 862715fd..14a74c59 100644 --- a/src/com/owncloud/android/ui/dialog/EditNameDialog.java +++ b/src/com/owncloud/android/ui/dialog/EditNameDialog.java @@ -31,7 +31,7 @@ import android.widget.Toast; import com.actionbarsherlock.app.SherlockDialogFragment; import com.owncloud.android.R; -import com.owncloud.android.oc_framework.utils.FileUtils; +import com.owncloud.android.lib.utils.FileUtils; /** diff --git a/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java b/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java index 91c607e4..a90a7adb 100644 --- a/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java +++ b/src/com/owncloud/android/ui/dialog/SamlWebViewDialog.java @@ -38,7 +38,7 @@ import com.actionbarsherlock.app.SherlockDialogFragment; import com.owncloud.android.R; import com.owncloud.android.authentication.SsoWebViewClient; import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener; -import com.owncloud.android.oc_framework.network.webdav.WebdavClient; +import com.owncloud.android.lib.network.OwnCloudClient; import com.owncloud.android.utils.Log_OC; @@ -181,7 +181,7 @@ public class SamlWebViewDialog extends SherlockDialogFragment { webSettings.setBuiltInZoomControls(true); webSettings.setLoadWithOverviewMode(false); webSettings.setSavePassword(false); - webSettings.setUserAgentString(WebdavClient.USER_AGENT); + webSettings.setUserAgentString(OwnCloudClient.USER_AGENT); webSettings.setSaveFormData(false); return rootView; diff --git a/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java b/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java index a50ecc95..dd4046b5 100644 --- a/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java +++ b/src/com/owncloud/android/ui/dialog/SslValidatorDialog.java @@ -39,9 +39,9 @@ import android.view.Window; import android.widget.Button; import android.widget.TextView; -import com.owncloud.android.oc_framework.network.CertificateCombinedException; -import com.owncloud.android.oc_framework.network.NetworkUtils; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; +import com.owncloud.android.lib.network.CertificateCombinedException; +import com.owncloud.android.lib.network.NetworkUtils; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; import com.owncloud.android.utils.Log_OC; /** diff --git a/src/com/owncloud/android/ui/fragment/FileDetailFragment.java b/src/com/owncloud/android/ui/fragment/FileDetailFragment.java index ec43bd19..49895260 100644 --- a/src/com/owncloud/android/ui/fragment/FileDetailFragment.java +++ b/src/com/owncloud/android/ui/fragment/FileDetailFragment.java @@ -50,11 +50,11 @@ import com.owncloud.android.files.services.FileObserverService; import com.owncloud.android.files.services.FileUploader; import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder; import com.owncloud.android.files.services.FileUploader.FileUploaderBinder; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult.ResultCode; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; +import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode; import com.owncloud.android.operations.RemoveFileOperation; import com.owncloud.android.operations.RenameFileOperation; import com.owncloud.android.operations.SynchronizeFileOperation; diff --git a/src/com/owncloud/android/ui/fragment/OCFileListFragment.java b/src/com/owncloud/android/ui/fragment/OCFileListFragment.java index c75eedb4..91abe7d1 100644 --- a/src/com/owncloud/android/ui/fragment/OCFileListFragment.java +++ b/src/com/owncloud/android/ui/fragment/OCFileListFragment.java @@ -28,8 +28,8 @@ import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.files.FileHandler; import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder; import com.owncloud.android.files.services.FileUploader.FileUploaderBinder; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; -import com.owncloud.android.oc_framework.operations.RemoteOperation; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.RemoteOperation; import com.owncloud.android.operations.RemoveFileOperation; import com.owncloud.android.operations.RenameFileOperation; import com.owncloud.android.operations.SynchronizeFileOperation; diff --git a/src/com/owncloud/android/ui/preview/FileDownloadFragment.java b/src/com/owncloud/android/ui/preview/FileDownloadFragment.java index bacba8c9..8ca2be33 100644 --- a/src/com/owncloud/android/ui/preview/FileDownloadFragment.java +++ b/src/com/owncloud/android/ui/preview/FileDownloadFragment.java @@ -37,7 +37,7 @@ import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; -import com.owncloud.android.oc_framework.network.webdav.OnDatatransferProgressListener; +import com.owncloud.android.lib.network.OnDatatransferProgressListener; /** diff --git a/src/com/owncloud/android/ui/preview/PreviewImageFragment.java b/src/com/owncloud/android/ui/preview/PreviewImageFragment.java index 0ae6868b..8555fa77 100644 --- a/src/com/owncloud/android/ui/preview/PreviewImageFragment.java +++ b/src/com/owncloud/android/ui/preview/PreviewImageFragment.java @@ -52,10 +52,10 @@ import com.actionbarsherlock.view.MenuItem; import com.owncloud.android.R; import com.owncloud.android.datamodel.FileDataStorageManager; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; import com.owncloud.android.operations.RemoveFileOperation; import com.owncloud.android.ui.fragment.ConfirmationDialogFragment; import com.owncloud.android.ui.fragment.FileFragment; diff --git a/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java b/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java index b21f333a..464ea6db 100644 --- a/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java +++ b/src/com/owncloud/android/ui/preview/PreviewMediaFragment.java @@ -57,10 +57,10 @@ import com.owncloud.android.datamodel.OCFile; import com.owncloud.android.media.MediaControlView; import com.owncloud.android.media.MediaService; import com.owncloud.android.media.MediaServiceBinder; -import com.owncloud.android.oc_framework.network.webdav.WebdavUtils; -import com.owncloud.android.oc_framework.operations.OnRemoteOperationListener; -import com.owncloud.android.oc_framework.operations.RemoteOperation; -import com.owncloud.android.oc_framework.operations.RemoteOperationResult; +import com.owncloud.android.lib.network.webdav.WebdavUtils; +import com.owncloud.android.lib.operations.common.OnRemoteOperationListener; +import com.owncloud.android.lib.operations.common.RemoteOperation; +import com.owncloud.android.lib.operations.common.RemoteOperationResult; import com.owncloud.android.operations.RemoveFileOperation; import com.owncloud.android.ui.activity.FileActivity; import com.owncloud.android.ui.activity.FileDisplayActivity; diff --git a/src/com/owncloud/android/ui/preview/PreviewVideoActivity.java b/src/com/owncloud/android/ui/preview/PreviewVideoActivity.java index 59d96555..9e6a2803 100644 --- a/src/com/owncloud/android/ui/preview/PreviewVideoActivity.java +++ b/src/com/owncloud/android/ui/preview/PreviewVideoActivity.java @@ -37,8 +37,8 @@ import android.os.Bundle; import android.widget.MediaController; import android.widget.VideoView; -import com.owncloud.android.oc_framework.accounts.AccountUtils; -import com.owncloud.android.oc_framework.accounts.AccountUtils.AccountNotFoundException; +import com.owncloud.android.lib.accounts.AccountUtils; +import com.owncloud.android.lib.accounts.AccountUtils.AccountNotFoundException; /** * Activity implementing a basic video player. diff --git a/src/com/owncloud/android/utils/FileStorageUtils.java b/src/com/owncloud/android/utils/FileStorageUtils.java index d4042f50..639caef7 100644 --- a/src/com/owncloud/android/utils/FileStorageUtils.java +++ b/src/com/owncloud/android/utils/FileStorageUtils.java @@ -22,7 +22,7 @@ import java.io.File; import com.owncloud.android.MainApp; import com.owncloud.android.R; import com.owncloud.android.datamodel.OCFile; -import com.owncloud.android.oc_framework.operations.RemoteFile; +import com.owncloud.android.lib.operations.common.RemoteFile; import android.annotation.SuppressLint; import android.content.Context; diff --git a/tests/src/com/owncloud/android/test/AccountUtilsTest.java b/tests/src/com/owncloud/android/test/AccountUtilsTest.java index 03667ff7..150034bd 100644 --- a/tests/src/com/owncloud/android/test/AccountUtilsTest.java +++ b/tests/src/com/owncloud/android/test/AccountUtilsTest.java @@ -18,8 +18,8 @@ package com.owncloud.android.test; -import com.owncloud.android.oc_framework.accounts.AccountUtils; -import com.owncloud.android.oc_framework.utils.OwnCloudVersion; +import com.owncloud.android.lib.accounts.AccountUtils; +import com.owncloud.android.lib.utils.OwnCloudVersion; import android.test.AndroidTestCase;