Compare commits

...
Author SHA1 Message Date
tobiasKaminsky 63e8b0f0b0 Move all to result data
Signed-off-by: tobiasKaminsky <[email protected]>
2021-07-12 09:24:53 +02:00
70 changed files with 776 additions and 949 deletions

No files matched your search

+32 -1
View File
@@ -1,7 +1,38 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="ktlint" />
<inspection_tool class="JavaDoc" enabled="true" level="WARNING" enabled_by_default="true">
<option name="TOP_LEVEL_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="INNER_CLASS_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="METHOD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="@return@param@throws or @exception" />
</value>
</option>
<option name="FIELD_OPTIONS">
<value>
<option name="ACCESS_JAVADOC_REQUIRED_FOR" value="none" />
<option name="REQUIRED_TAGS" value="" />
</value>
</option>
<option name="IGNORE_DEPRECATED" value="false" />
<option name="IGNORE_JAVADOC_PERIOD" value="true" />
<option name="IGNORE_DUPLICATED_THROWS" value="false" />
<option name="IGNORE_POINT_TO_ITSELF" value="false" />
<option name="myAdditionalJavadocTags" value="return" />
</inspection_tool>
<inspection_tool class="KotlinUnusedImport" enabled="true" level="ERROR" enabled_by_default="true" />
<inspection_tool class="RedundantSemicolon" enabled="true" level="ERROR" enabled_by_default="true" />
</profile>
</component>
</component>
+1 -1
View File
@@ -60,7 +60,7 @@ ext {
markwonVersion = "4.6.2"
prismVersion = "2.0.0"
butterknifeVersion = "10.2.3"
androidLibraryVersion = "master-SNAPSHOT"
androidLibraryVersion = "resultData-SNAPSHOT"
mockitoVersion = "3.11.0"
mockkVersion = "1.10.4"
powermockVersion = "2.0.9"
@@ -229,16 +229,16 @@ public final class PushUtils {
OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton().
getClientFor(ocAccount, context);
RemoteOperationResult remoteOperationResult =
RemoteOperationResult<PushResponse> remoteOperationResult =
new RegisterAccountDeviceForNotificationsOperation(pushTokenHash,
publicKey,
context.getResources().getString(R.string.push_server_url))
.execute(client);
if (remoteOperationResult.isSuccess()) {
PushResponse pushResponse = remoteOperationResult.getPushResponseData();
PushResponse pushResponse = remoteOperationResult.getResultData();
RemoteOperationResult resultProxy = new RegisterAccountDeviceForProxyOperation(
RemoteOperationResult<Void> resultProxy = new RegisterAccountDeviceForProxyOperation(
context.getResources().getString(R.string.push_server_url),
token, pushResponse.getDeviceIdentifier(),
pushResponse.getSignature(),
@@ -245,7 +245,7 @@ class NotificationWork constructor(
val result = GetNotificationRemoteOperation(decryptedPushMessage.nid)
.execute(client)
if (result.isSuccess) {
val notification = result.notificationData[0]
val notification = result.resultData
sendNotification(notification, account)
}
} catch (e: Exception) {
@@ -128,7 +128,7 @@ class OfflineSyncWork constructor(
// update eTag
@Suppress("TooGenericExceptionCaught") // legacy code
try {
val updatedEtag = result.data[0] as String
val updatedEtag = result.resultData
ocFolder.etagOnServer = updatedEtag
storageManager.saveFile(ocFolder)
} catch (e: Exception) {
@@ -36,7 +36,7 @@ internal class LoadUrlTask(
val operation = StreamMediaFileOperation(fileId)
val result = operation.execute(client)
return when (result.isSuccess) {
true -> result.data[0] as String
true -> result.resultData
false -> null
}
}
@@ -833,7 +833,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
if (operation instanceof GetServerInfoOperation) {
if (operation.hashCode() == mWaitingForOpId) {
onGetServerInfoFinish(result);
onGetServerInfoFinish((RemoteOperationResult<GetServerInfoOperation.ServerInfo>) result);
} // else nothing ; only the last check operation is considered;
// multiple can be started if the user amends a URL quickly
@@ -878,7 +878,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
*
* @param result Result of the check.
*/
private void onGetServerInfoFinish(RemoteOperationResult result) {
private void onGetServerInfoFinish(RemoteOperationResult<GetServerInfoOperation.ServerInfo> result) {
/// update activity state
mWaitingForOpId = Long.MAX_VALUE;
@@ -888,7 +888,7 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
// 2. server is installed
// 3. we got the server version
// 4. we got the authentication method required by the server
mServerInfo = (GetServerInfoOperation.ServerInfo) (result.getData().get(0));
mServerInfo = result.getResultData();
// show outdated warning
if (getResources().getBoolean(R.bool.show_outdated_server_warning) &&
@@ -905,12 +905,11 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(Uri.parse(mServerInfo.mBaseUrl),
this,
true);
RemoteOperationResult remoteOperationResult = new GetCapabilitiesRemoteOperation().execute(client);
RemoteOperationResult<OCCapability> remoteOperationResult =
new GetCapabilitiesRemoteOperation().execute(client);
if (remoteOperationResult.isSuccess() &&
remoteOperationResult.getData() != null &&
remoteOperationResult.getData().size() > 0) {
OCCapability capability = (OCCapability) remoteOperationResult.getData().get(0);
if (remoteOperationResult.isSuccess() && remoteOperationResult.getResultData() != null) {
OCCapability capability = remoteOperationResult.getResultData();
try {
primaryColor = Color.parseColor(capability.getServerColor());
} catch (Exception e) {
@@ -75,22 +75,23 @@ public class AuthenticatorAsyncTask extends AsyncTask<Object, Void, RemoteOperat
// Operation - try credentials
ExistenceCheckRemoteOperation operation = new ExistenceCheckRemoteOperation(ROOT_PATH, SUCCESS_IF_ABSENT);
result = operation.execute(client);
RemoteOperationResult<Void> existenceResult = operation.execute(client);
if (operation.wasRedirected()) {
RedirectionPath redirectionPath = operation.getRedirectionPath();
String permanentLocation = redirectionPath.getLastPermanentLocation();
result.setLastPermanentLocation(permanentLocation);
existenceResult.setLastPermanentLocation(permanentLocation);
}
// Operation - get display name
if (result.isSuccess()) {
if (existenceResult.isSuccess()) {
GetUserInfoRemoteOperation remoteUserNameOperation = new GetUserInfoRemoteOperation();
result = remoteUserNameOperation.execute(nextcloudClient);
} else {
result = new RemoteOperationResult<>(existenceResult.getCode());
}
} else {
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.UNKNOWN_ERROR);
result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.UNKNOWN_ERROR);
}
return result;
@@ -83,8 +83,8 @@ public class FileDataStorageManager {
public static final int ROOT_PARENT_ID = 0;
public static final String NULL_STRING = "null";
private ContentResolver contentResolver;
private ContentProviderClient contentProviderClient;
private final ContentResolver contentResolver;
private final ContentProviderClient contentProviderClient;
private Account account;
public FileDataStorageManager(Account account, ContentResolver contentResolver) {
@@ -309,9 +309,9 @@ public class FileDataStorageManager {
// remote request
ReadFileRemoteOperation operation = new ReadFileRemoteOperation(parentPath);
// TODO Deprecated
RemoteOperationResult result = operation.execute(getAccount(), context);
RemoteOperationResult<RemoteFile> result = operation.execute(getAccount(), context);
if (result.isSuccess()) {
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
OCFile remoteFolder = FileStorageUtils.fillOCFile(result.getResultData());
returnFile = saveFileWithParent(remoteFolder, context);
} else {
@@ -1,95 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.files;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.Utf8PostMethod;
import org.json.JSONObject;
import java.util.ArrayList;
public class CreateFileFromTemplateOperation extends RemoteOperation {
private static final String TAG = CreateFileFromTemplateOperation.class.getSimpleName();
private static final int SYNC_READ_TIMEOUT = 40000;
private static final int SYNC_CONNECTION_TIMEOUT = 5000;
private static final String NEW_FROM_TEMPLATE_URL = "/ocs/v2.php/apps/richdocuments/api/v1/templates/new";
private String path;
private int templateId;
// JSON node names
private static final String NODE_OCS = "ocs";
private static final String NODE_DATA = "data";
private static final String JSON_FORMAT = "?format=json";
public CreateFileFromTemplateOperation(String path, int templateId) {
this.path = path;
this.templateId = templateId;
}
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
Utf8PostMethod postMethod = null;
try {
postMethod = new Utf8PostMethod(client.getBaseUri() + NEW_FROM_TEMPLATE_URL + JSON_FORMAT);
postMethod.setParameter("path", path);
postMethod.setParameter("template", String.valueOf(templateId));
// remote request
postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);
if (status == HttpStatus.SC_OK) {
String response = postMethod.getResponseBodyAsString();
// Parse the response
JSONObject respJSON = new JSONObject(response);
String url = respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).getString("url");
ArrayList<Object> templateArray = new ArrayList<>();
templateArray.add(url);
result = new RemoteOperationResult(true, postMethod);
result.setData(templateArray);
} else {
result = new RemoteOperationResult(false, postMethod);
client.exhaustResponse(postMethod.getResponseBodyAsStream());
}
} catch (Exception e) {
result = new RemoteOperationResult(e);
Log_OC.e(TAG, "Create file from template " + templateId + " failed: " + result.getLogMessage(),
result.getException());
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
}
}
return result;
}
}
@@ -33,15 +33,16 @@ import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class FetchTemplateOperation extends RemoteOperation {
public class FetchTemplateOperation extends RemoteOperation<List<Template>> {
private static final String TAG = FetchTemplateOperation.class.getSimpleName();
private static final int SYNC_READ_TIMEOUT = 40000;
private static final int SYNC_CONNECTION_TIMEOUT = 5000;
private static final String TEMPLATE_URL = "/ocs/v2.php/apps/richdocuments/api/v1/templates/";
private ChooseRichDocumentsTemplateDialogFragment.Type type;
private final ChooseRichDocumentsTemplateDialogFragment.Type type;
// JSON node names
private static final String NODE_OCS = "ocs";
@@ -52,14 +53,14 @@ public class FetchTemplateOperation extends RemoteOperation {
this.type = type;
}
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
protected RemoteOperationResult<List<Template>> run(OwnCloudClient client) {
RemoteOperationResult<List<Template>> result;
GetMethod getMethod = null;
try {
getMethod = new GetMethod(client.getBaseUri() + TEMPLATE_URL + type.toString().toLowerCase(Locale.ENGLISH) +
JSON_FORMAT);
JSON_FORMAT);
// remote request
getMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
@@ -73,7 +74,7 @@ public class FetchTemplateOperation extends RemoteOperation {
JSONObject respJSON = new JSONObject(response);
JSONArray templates = respJSON.getJSONObject(NODE_OCS).getJSONArray(NODE_DATA);
ArrayList<Object> templateArray = new ArrayList<>();
ArrayList<Template> templateArray = new ArrayList<>();
for (int i = 0; i < templates.length(); i++) {
JSONObject templateObject = templates.getJSONObject(i);
@@ -82,20 +83,20 @@ public class FetchTemplateOperation extends RemoteOperation {
templateObject.getString("name"),
templateObject.optString("preview"),
Template.parse(templateObject.getString("type")
.toUpperCase(Locale.ROOT)),
.toUpperCase(Locale.ROOT)),
templateObject.getString("extension")));
}
result = new RemoteOperationResult(true, getMethod);
result.setData(templateArray);
result = new RemoteOperationResult<>(true, getMethod);
result.setResultData(templateArray);
} else {
result = new RemoteOperationResult(false, getMethod);
result = new RemoteOperationResult<>(false, getMethod);
client.exhaustResponse(getMethod.getResponseBodyAsStream());
}
} catch (Exception e) {
result = new RemoteOperationResult(e);
result = new RemoteOperationResult<>(e);
Log_OC.e(TAG, "Get templates for typ " + type + " failed: " + result.getLogMessage(),
result.getException());
result.getException());
} finally {
if (getMethod != null) {
getMethod.releaseConnection();
@@ -29,15 +29,13 @@ import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.Utf8PostMethod;
import org.json.JSONObject;
import java.util.ArrayList;
public class StreamMediaFileOperation extends RemoteOperation {
public class StreamMediaFileOperation extends RemoteOperation<String> {
private static final String TAG = StreamMediaFileOperation.class.getSimpleName();
private static final int SYNC_READ_TIMEOUT = 40000;
private static final int SYNC_CONNECTION_TIMEOUT = 5000;
private static final String STREAM_MEDIA_URL = "/ocs/v2.php/apps/dav/api/v1/direct";
private String fileID;
private final String fileId;
// JSON node names
private static final String NODE_OCS = "ocs";
@@ -45,17 +43,17 @@ public class StreamMediaFileOperation extends RemoteOperation {
private static final String NODE_URL = "url";
private static final String JSON_FORMAT = "?format=json";
public StreamMediaFileOperation(String fileID) {
this.fileID = fileID;
public StreamMediaFileOperation(String fileId) {
this.fileId = fileId;
}
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
protected RemoteOperationResult<String> run(OwnCloudClient client) {
RemoteOperationResult<String> result;
Utf8PostMethod postMethod = null;
try {
postMethod = new Utf8PostMethod(client.getBaseUri() + STREAM_MEDIA_URL + JSON_FORMAT);
postMethod.setParameter("fileId", fileID);
postMethod.setParameter("fileId", fileId);
// remote request
postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
@@ -69,18 +67,16 @@ public class StreamMediaFileOperation extends RemoteOperation {
JSONObject respJSON = new JSONObject(response);
String url = respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).getString(NODE_URL);
result = new RemoteOperationResult(true, postMethod);
ArrayList<Object> urlArray = new ArrayList<>();
urlArray.add(url);
result.setData(urlArray);
result = new RemoteOperationResult<>(true, postMethod);
result.setResultData(url);
} else {
result = new RemoteOperationResult(false, postMethod);
result = new RemoteOperationResult<>(false, postMethod);
client.exhaustResponse(postMethod.getResponseBodyAsStream());
}
} catch (Exception e) {
result = new RemoteOperationResult(e);
Log_OC.e(TAG, "Get stream url for file with id " + fileID + " failed: " + result.getLogMessage(),
result.getException());
result = new RemoteOperationResult<>(e);
Log_OC.e(TAG, "Get stream url for file with id " + fileId + " failed: " + result.getLogMessage(),
result.getException());
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
@@ -1,39 +1,34 @@
/**
* ownCloud Android client application
*
* @author David A. Velasco
* Copyright (C) 2016 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 <http://www.gnu.org/licenses/>.
/*
* ownCloud Android client application
*
* @author David A. Velasco Copyright (C) 2016 ownCloud Inc.
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.operations;
import android.accounts.Account;
import com.nextcloud.client.account.User;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;
import com.owncloud.android.operations.common.SyncOperation;
import java.util.ArrayList;
/**
* Checks validity of currently stored credentials for a given OC account
*/
public class CheckCurrentCredentialsOperation extends SyncOperation {
public class CheckCurrentCredentialsOperation extends SyncOperation<Account> {
private final User user;
@@ -42,22 +37,21 @@ public class CheckCurrentCredentialsOperation extends SyncOperation {
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
protected RemoteOperationResult<Account> run(OwnCloudClient client) {
RemoteOperationResult<Account> result;
boolean validAccount = user.nameEquals(getStorageManager().getAccount().name);
if (!validAccount) {
result = new RemoteOperationResult(new IllegalStateException(
result = new RemoteOperationResult<>(new IllegalStateException(
"Account to validate is not the account connected to!")
);
} else {
RemoteOperation check = new ExistenceCheckRemoteOperation(OCFile.ROOT_PATH, false);
result = check.execute(client);
ArrayList<Object> data = new ArrayList<>();
data.add(user.toPlatformAccount());
result.setData(data);
RemoteOperationResult<Void> existenceResult = new ExistenceCheckRemoteOperation(OCFile.ROOT_PATH, false)
.execute(client);
result = new RemoteOperationResult<>(existenceResult.getCode());
result.setResultData(user.toPlatformAccount());
}
return result;
}
}
@@ -44,6 +44,7 @@ import com.owncloud.android.utils.FileStorageUtils;
import com.owncloud.android.utils.MimeType;
import java.io.File;
import java.util.List;
import java.util.UUID;
import androidx.annotation.NonNull;
@@ -52,17 +53,17 @@ import static com.owncloud.android.datamodel.OCFile.PATH_SEPARATOR;
import static com.owncloud.android.datamodel.OCFile.ROOT_PATH;
/**
* Access to remote operation performing the creation of a new folder in the ownCloud server.
* Save the new folder in Database.
* Access to remote operation performing the creation of a new folder in the ownCloud server. Save the new folder in
* Database.
*/
public class CreateFolderOperation extends SyncOperation implements OnRemoteOperationListener {
public class CreateFolderOperation extends SyncOperation<Void> implements OnRemoteOperationListener {
private static final String TAG = CreateFolderOperation.class.getSimpleName();
protected String remotePath;
private RemoteFile createdRemoteFolder;
private User user;
private Context context;
private final User user;
private final Context context;
/**
* Constructor
@@ -74,7 +75,7 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<Void> run(OwnCloudClient client) {
String remoteParentPath = new File(getRemotePath()).getParent();
remoteParentPath = remoteParentPath.endsWith(PATH_SEPARATOR) ?
remoteParentPath : remoteParentPath + PATH_SEPARATOR;
@@ -136,9 +137,9 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper
String encryptedFileName = createRandomFileName(metadata);
encryptedRemotePath = parent.getRemotePath() + encryptedFileName;
RemoteOperationResult result = new CreateFolderRemoteOperation(encryptedRemotePath,
true,
token)
RemoteOperationResult<Void> result = new CreateFolderRemoteOperation(encryptedRemotePath,
true,
token)
.execute(client);
if (result.isSuccess()) {
@@ -168,14 +169,14 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper
}
}
RemoteOperationResult remoteFolderOperationResult = new ReadFolderRemoteOperation(encryptedRemotePath)
.execute(client);
RemoteOperationResult<List<RemoteFile>> remoteFolderOperationResult =
new ReadFolderRemoteOperation(encryptedRemotePath).execute(client);
createdRemoteFolder = (RemoteFile) remoteFolderOperationResult.getData().get(0);
createdRemoteFolder = remoteFolderOperationResult.getResultData().get(0);
OCFile newDir = createRemoteFolderOcFile(parent, filename, createdRemoteFolder);
getStorageManager().saveFile(newDir);
RemoteOperationResult encryptionOperationResult = new ToggleEncryptionRemoteOperation(
RemoteOperationResult<Void> encryptionOperationResult = new ToggleEncryptionRemoteOperation(
newDir.getLocalId(),
newDir.getRemotePath(),
true)
@@ -209,11 +210,11 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper
}
// TODO do better
return new RemoteOperationResult(e);
return new RemoteOperationResult<>(e);
} finally {
// unlock folder
if (token != null) {
RemoteOperationResult unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
RemoteOperationResult<Void> unlockFolderResult = EncryptionUtils.unlockFolder(parent, client, token);
if (!unlockFolderResult.isSuccess()) {
// TODO do better
@@ -279,14 +280,14 @@ public class CreateFolderOperation extends SyncOperation implements OnRemoteOper
return encryptedFileName;
}
private RemoteOperationResult normalCreate(OwnCloudClient client) {
RemoteOperationResult result = new CreateFolderRemoteOperation(remotePath, true).execute(client);
private RemoteOperationResult<Void> normalCreate(OwnCloudClient client) {
RemoteOperationResult<Void> result = new CreateFolderRemoteOperation(remotePath, true).execute(client);
if (result.isSuccess()) {
RemoteOperationResult remoteFolderOperationResult = new ReadFolderRemoteOperation(remotePath)
.execute(client);
RemoteOperationResult<List<RemoteFile>> remoteFolderOperationResult =
new ReadFolderRemoteOperation(remotePath).execute(client);
createdRemoteFolder = (RemoteFile) remoteFolderOperationResult.getData().get(0);
createdRemoteFolder = remoteFolderOperationResult.getResultData().get(0);
saveFolderInDB();
} else {
Log_OC.e(TAG, remotePath + " hasn't been created");
@@ -30,15 +30,15 @@ import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.ShareType;
import com.owncloud.android.operations.common.SyncOperation;
import java.util.ArrayList;
import java.util.List;
/**
* Creates a new public share for a given file
*/
public class CreateShareViaLinkOperation extends SyncOperation {
public class CreateShareViaLinkOperation extends SyncOperation<List<OCShare>> {
private String path;
private String password;
private final String path;
private final String password;
public CreateShareViaLinkOperation(String path, String password) {
this.path = path;
@@ -46,7 +46,7 @@ public class CreateShareViaLinkOperation extends SyncOperation {
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<List<OCShare>> run(OwnCloudClient client) {
CreateShareRemoteOperation createOp = new CreateShareRemoteOperation(path,
ShareType.PUBLIC_LINK,
"",
@@ -54,20 +54,20 @@ public class CreateShareViaLinkOperation extends SyncOperation {
password,
OCShare.NO_PERMISSION);
createOp.setGetShareDetails(true);
RemoteOperationResult result = createOp.execute(client);
RemoteOperationResult<List<OCShare>> result = createOp.execute(client);
if (result.isSuccess()) {
if (result.getData().size() > 0) {
Object item = result.getData().get(0);
if (item instanceof OCShare) {
updateData((OCShare) item);
if (result.getResultData().size() > 0) {
OCShare item = result.getResultData().get(0);
if (item != null) {
updateData(item);
} else {
ArrayList<Object> data = result.getData();
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
result.setData(data);
List<OCShare> data = result.getResultData();
result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
result.setResultData(data);
}
} else {
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
}
}
@@ -77,11 +77,7 @@ public class CreateShareViaLinkOperation extends SyncOperation {
private void updateData(OCShare share) {
// Update DB with the response
share.setPath(path);
if (path.endsWith(FileUtils.PATH_SEPARATOR)) {
share.setFolder(true);
} else {
share.setFolder(false);
}
share.setFolder(path.endsWith(FileUtils.PATH_SEPARATOR));
getStorageManager().saveShare(share);
@@ -37,12 +37,12 @@ import java.util.List;
/**
* Creates a new private share for a given file.
*/
public class CreateShareWithShareeOperation extends SyncOperation {
public class CreateShareWithShareeOperation extends SyncOperation<List<OCShare>> {
private String path;
private String shareeName;
private ShareType shareType;
private int permissions;
private final String path;
private final String shareeName;
private final ShareType shareType;
private final int permissions;
private static final List<ShareType> supportedShareTypes = new ArrayList<>(Arrays.asList(ShareType.USER,
ShareType.GROUP,
@@ -72,7 +72,7 @@ public class CreateShareWithShareeOperation extends SyncOperation {
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<List<OCShare>> run(OwnCloudClient client) {
CreateShareRemoteOperation operation = new CreateShareRemoteOperation(
path,
@@ -83,11 +83,11 @@ public class CreateShareWithShareeOperation extends SyncOperation {
permissions
);
operation.setGetShareDetails(true);
RemoteOperationResult result = operation.execute(client);
RemoteOperationResult<List<OCShare>> result = operation.execute(client);
if (result.isSuccess() && result.getData().size() > 0) {
OCShare share = (OCShare) result.getData().get(0);
if (result.isSuccess() && result.getResultData().size() > 0) {
OCShare share = result.getResultData().get(0);
updateData(share);
}
@@ -1,4 +1,4 @@
/**
/*
* ownCloud Android client application
*
* @author David A. Velasco
@@ -38,15 +38,15 @@ import java.util.Locale;
/**
* Operation to find out what authentication method requires the server to access files.
*
* <p>
* Basically, tries to access to the root folder without authorization and analyzes the response.
*
* When successful, the instance of {@link RemoteOperationResult} passed through
* {@link com.owncloud.android.lib.common.operations.OnRemoteOperationListener
* #onRemoteOperationFinish(RemoteOperation, RemoteOperationResult)} returns in
* {@link RemoteOperationResult#getData()} a value of {@link AuthenticationMethod}.
* <p>
* When successful, the instance of {@link RemoteOperationResult} passed through {@link
* com.owncloud.android.lib.common.operations.OnRemoteOperationListener #onRemoteOperationFinish(RemoteOperation,
* RemoteOperationResult)} returns in {@link RemoteOperationResult#getResultData()} a value of {@link
* AuthenticationMethod}.
*/
public class DetectAuthenticationMethodOperation extends RemoteOperation {
public class DetectAuthenticationMethodOperation extends RemoteOperation<DetectAuthenticationMethodOperation.AuthenticationMethod> {
private static final String TAG = DetectAuthenticationMethodOperation.class.getSimpleName();
@@ -58,7 +58,7 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation {
BEARER_TOKEN
}
private Context mContext;
private final Context context;
/**
* Constructor
@@ -66,40 +66,39 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation {
* @param context Android context of the caller.
*/
public DetectAuthenticationMethodOperation(Context context) {
mContext = context;
this.context = context;
}
/**
* Performs the operation.
*
* Triggers a check of existence on the root folder of the server, granting
* that the request is not authenticated.
*
* Analyzes the result of check to find out what authentication method, if
* any, is requested by the server.
* Performs the operation.
* <p>
* Triggers a check of existence on the root folder of the server, granting that the request is not authenticated.
* <p>
* Analyzes the result of check to find out what authentication method, if any, is requested by the server.
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result = null;
protected RemoteOperationResult<AuthenticationMethod> run(OwnCloudClient client) {
RemoteOperationResult<AuthenticationMethod> result;
AuthenticationMethod authMethod = AuthenticationMethod.UNKNOWN;
RemoteOperation operation = new ExistenceCheckRemoteOperation("", mContext, false);
RemoteOperation<Void> existenceOperation = new ExistenceCheckRemoteOperation("", context, false);
client.clearCredentials();
client.setFollowRedirects(false);
// try to access the root folder, following redirections but not SAML SSO redirections
result = operation.execute(client);
String redirectedLocation = result.getRedirectedLocation();
while (!TextUtils.isEmpty(redirectedLocation) && !result.isIdPRedirection()) {
client.setBaseUri(Uri.parse(result.getRedirectedLocation()));
result = operation.execute(client);
redirectedLocation = result.getRedirectedLocation();
RemoteOperationResult<Void> existenceResult = existenceOperation.execute(client);
String redirectedLocation = existenceResult.getRedirectedLocation();
while (!TextUtils.isEmpty(redirectedLocation) && !existenceResult.isIdPRedirection()) {
client.setBaseUri(Uri.parse(existenceResult.getRedirectedLocation()));
existenceResult = existenceOperation.execute(client);
redirectedLocation = existenceResult.getRedirectedLocation();
}
// analyze response
if (result.getHttpCode() == HttpStatus.SC_UNAUTHORIZED || result.getHttpCode() == HttpStatus.SC_FORBIDDEN) {
ArrayList<String> authHeaders = result.getAuthenticateHeaders();
if (existenceResult.getHttpCode() == HttpStatus.SC_UNAUTHORIZED ||
existenceResult.getHttpCode() == HttpStatus.SC_FORBIDDEN) {
ArrayList<String> authHeaders = existenceResult.getAuthenticateHeaders();
for (String header : authHeaders) {
// currently we only support basic auth
@@ -110,23 +109,29 @@ public class DetectAuthenticationMethodOperation extends RemoteOperation {
}
// else - fall back to UNKNOWN
} else if (result.isSuccess()) {
} else if (existenceResult.isSuccess()) {
authMethod = AuthenticationMethod.NONE;
} else if (result.isIdPRedirection()) {
} else if (existenceResult.isIdPRedirection()) {
authMethod = AuthenticationMethod.SAML_WEB_SSO;
}
// else - fall back to UNKNOWN
Log_OC.d(TAG, "Authentication method found: " + authenticationMethodToString(authMethod));
if (authMethod != AuthenticationMethod.UNKNOWN) {
result = new RemoteOperationResult(true, result.getHttpCode(), result.getHttpPhrase(), new Header[0]);
result = new RemoteOperationResult<>(true,
existenceResult.getHttpCode(),
existenceResult.getHttpPhrase(),
new Header[0]);
} else {
result = new RemoteOperationResult<>(false,
existenceResult.getHttpCode(),
existenceResult.getHttpPhrase(),
new Header[0]);
}
ArrayList<Object> data = new ArrayList<>();
data.add(authMethod);
result.setData(data);
return result; // same result instance, so that other errors
// can be handled by the caller transparently
result.setResultData(authMethod);
return result; // same result instance, so that other errors can be handled by the caller transparently
}
private String authenticationMethodToString(AuthenticationMethod value) {
@@ -1,21 +1,17 @@
/**
* ownCloud Android client application
*
* @author masensio
* Copyright (C) 2015 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 <http://www.gnu.org/licenses/>.
* ownCloud Android client application
*
* @author masensio Copyright (C) 2015 ownCloud Inc.
* <p>
* 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.
* <p>
* 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.
* <p>
* You should have received a copy of the GNU General Public License along with this program. If not, see
* <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.operations;
@@ -29,10 +25,10 @@ import com.owncloud.android.operations.common.SyncOperation;
/**
* Get and save capabilities from the server
*/
public class GetCapabilitiesOperation extends SyncOperation {
public class GetCapabilitiesOperation extends SyncOperation<OCCapability> {
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<OCCapability> run(OwnCloudClient client) {
final FileDataStorageManager storageManager = getStorageManager();
OCCapability currentCapability = null;
@@ -40,12 +36,12 @@ public class GetCapabilitiesOperation extends SyncOperation {
currentCapability = storageManager.getCapability(storageManager.getAccount().name);
}
RemoteOperationResult result = new GetCapabilitiesRemoteOperation(currentCapability).execute(client);
RemoteOperationResult<OCCapability> result = new GetCapabilitiesRemoteOperation(currentCapability)
.execute(client);
if (result.isSuccess()
&& result.getData() != null && result.getData().size() > 0) {
if (result.isSuccess() && result.getResultData() != null) {
// Read data from the result
OCCapability capability = (OCCapability) result.getData().get(0);
OCCapability capability = result.getResultData();
// Save the capabilities into database
storageManager.saveCapabilities(capability);
@@ -31,25 +31,25 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCo
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.status.GetStatusRemoteOperation;
import com.owncloud.android.lib.resources.status.OwnCloudVersion;
import com.owncloud.android.lib.resources.status.StatusResponse;
import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;
import java.util.ArrayList;
import java.util.Locale;
/**
* Get basic information from an ownCloud server given its URL.
*
* Checks the existence of a configured ownCloud server in the URL, gets its version
* and finds out what authentication method is needed to access files in it.
* <p>
* Checks the existence of a configured ownCloud server in the URL, gets its version and finds out what authentication
* method is needed to access files in it.
*/
public class GetServerInfoOperation extends RemoteOperation {
public class GetServerInfoOperation extends RemoteOperation<GetServerInfoOperation.ServerInfo> {
private static final String TAG = GetServerInfoOperation.class.getSimpleName();
private String mUrl;
private Context mContext;
private ServerInfo mResultData;
private final String url;
private final Context context;
private final ServerInfo resultData;
/**
* Constructor.
@@ -59,53 +59,48 @@ public class GetServerInfoOperation extends RemoteOperation {
* TODO ugly dependency, get rid of it.
*/
public GetServerInfoOperation(String url, Context context) {
mUrl = trimWebdavSuffix(url);
mContext = context;
mResultData = new ServerInfo();
this.url = trimWebdavSuffix(url);
this.context = context;
resultData = new ServerInfo();
}
/**
* Performs the operation
*
* @return Result of the operation. If successful, includes an instance of
* {@link ServerInfo} with the information retrieved from the server.
* Call {@link RemoteOperationResult#getData()}.get(0) to get it.
* @return Result of the operation. If successful, includes an instance of {@link ServerInfo} with the information
* retrieved from the server. Call {@link RemoteOperationResult#getResultData()} to get it.
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
@Override
protected RemoteOperationResult<ServerInfo> run(OwnCloudClient client) {
// first: check the status of the server (including its version)
GetStatusRemoteOperation getStatus = new GetStatusRemoteOperation(mContext);
RemoteOperationResult result = getStatus.execute(client);
// first: check the status of the server (including its version)
RemoteOperationResult<StatusResponse> result = new GetStatusRemoteOperation(context).execute(client);
RemoteOperationResult<ServerInfo> finalResult = new RemoteOperationResult<>(result.getCode());
if (result.isSuccess()) {
// second: get authentication method required by the server
mResultData.mVersion = (OwnCloudVersion) result.getData().get(0);
mResultData.hasExtendedSupport = (boolean) result.getData().get(1);
mResultData.mIsSslConn = result.getCode() == ResultCode.OK_SSL;
mResultData.mBaseUrl = normalizeProtocolPrefix(mUrl, mResultData.mIsSslConn);
RemoteOperationResult detectAuthResult = detectAuthorizationMethod(client);
resultData.mVersion = result.getResultData().getNcVersion();
resultData.hasExtendedSupport = result.getResultData().getExtendedSupport();
resultData.mIsSslConn = result.getCode() == ResultCode.OK_SSL;
resultData.mBaseUrl = normalizeProtocolPrefix(url, resultData.mIsSslConn);
RemoteOperationResult<AuthenticationMethod> detectAuthResult = detectAuthorizationMethod(client);
// third: merge results
if (detectAuthResult.isSuccess()) {
mResultData.mAuthMethod = (AuthenticationMethod) detectAuthResult.getData().get(0);
ArrayList<Object> data = new ArrayList<Object>();
data.add(mResultData);
result.setData(data);
resultData.mAuthMethod = detectAuthResult.getResultData();
finalResult.setResultData(resultData);
} else {
result = detectAuthResult;
finalResult = new RemoteOperationResult<>(detectAuthResult.getCode());
}
}
return result;
return finalResult;
}
private RemoteOperationResult detectAuthorizationMethod(OwnCloudClient client) {
private RemoteOperationResult<AuthenticationMethod> detectAuthorizationMethod(OwnCloudClient client) {
Log_OC.d(TAG, "Trying empty authorization to detect authentication method");
DetectAuthenticationMethodOperation operation =
new DetectAuthenticationMethodOperation(mContext);
return operation.execute(client);
return new DetectAuthenticationMethodOperation(context).execute(client);
}
@@ -28,7 +28,7 @@ import com.owncloud.android.lib.resources.shares.GetSharesForFileRemoteOperation
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.operations.common.SyncOperation;
import java.util.ArrayList;
import java.util.List;
/**
* Provide a list shares for a specific file.
@@ -58,20 +58,14 @@ public class GetSharesForFileOperation extends SyncOperation {
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
GetSharesForFileRemoteOperation operation = new GetSharesForFileRemoteOperation(mPath,
mReshares, mSubfiles);
RemoteOperationResult result = operation.execute(client);
RemoteOperationResult<List<OCShare>> result = new GetSharesForFileRemoteOperation(mPath, mReshares, mSubfiles)
.execute(client);
if (result.isSuccess()) {
// Update DB with the response
Log_OC.d(TAG, "File = " + mPath + " Share list size " + result.getData().size());
ArrayList<OCShare> shares = new ArrayList<OCShare>();
for(Object obj: result.getData()) {
shares.add((OCShare) obj);
}
getStorageManager().saveSharesDB(shares);
Log_OC.d(TAG, "File = " + mPath + " Share list size " + result.getResultData().size());
getStorageManager().saveSharesDB(result.getResultData());
} else if (result.getCode() == RemoteOperationResult.ResultCode.SHARE_NOT_FOUND) {
// no share on the file - remove local shares
@@ -46,6 +46,7 @@ import com.owncloud.android.lib.resources.files.model.RemoteFile;
import com.owncloud.android.lib.resources.shares.GetSharesForFileRemoteOperation;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.ShareType;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.lib.resources.users.GetPredefinedStatusesRemoteOperation;
import com.owncloud.android.lib.resources.users.PredefinedStatus;
import com.owncloud.android.syncadapter.FileSyncAdapter;
@@ -87,20 +88,28 @@ public class RefreshFolderOperation extends RemoteOperation {
public static final String EVENT_SINGLE_FOLDER_SHARES_SYNCED =
RefreshFolderOperation.class.getName() + ".EVENT_SINGLE_FOLDER_SHARES_SYNCED";
/** Time stamp for the synchronization process in progress */
private long mCurrentSyncTime;
/**
* Time stamp for the synchronization process in progress
*/
private final long mCurrentSyncTime;
/** Remote folder to synchronize */
private OCFile mLocalFolder;
/** Access to the local database */
private FileDataStorageManager mStorageManager;
/**
* Access to the local database
*/
private final FileDataStorageManager mStorageManager;
/** Account where the file to synchronize belongs */
private Account mAccount;
/**
* Account where the file to synchronize belongs
*/
private final Account mAccount;
/** Android context; necessary to send requests to the download service */
private Context mContext;
/**
* Android context; necessary to send requests to the download service
*/
private final Context mContext;
/** Files and folders contained in the synchronized folder after a successful operation */
private List<OCFile> mChildren;
@@ -112,28 +121,28 @@ public class RefreshFolderOperation extends RemoteOperation {
private int mFailsInKeptInSyncFound;
/**
* Map of remote and local paths to files that where locally stored in a location
* out of the ownCloud folder and couldn't be copied automatically into it
* Map of remote and local paths to files that where locally stored in a location out of the ownCloud folder and
* couldn't be copied automatically into it
**/
private Map<String, String> mForgottenLocalFiles;
private final Map<String, String> mForgottenLocalFiles;
/**
* 'True' means that this operation is part of a full account synchronization
*/
private boolean mSyncFullAccount;
private final boolean mSyncFullAccount;
/** 'True' means that the remote folder changed and should be fetched */
private boolean mRemoteFolderChanged;
/** 'True' means that Etag will be ignored */
private boolean mIgnoreETag;
private final boolean mIgnoreETag;
/**
* 'True' means that no share and no capabilities will be updated
*/
private boolean mOnlyFileMetadata;
private final boolean mOnlyFileMetadata;
private List<SynchronizeFileOperation> mFilesToSyncContents;
private final List<SynchronizeFileOperation> mFilesToSyncContents;
// this will be used for every file when 'folder synchronization' replaces 'folder download'
@@ -216,11 +225,11 @@ public class RefreshFolderOperation extends RemoteOperation {
/**
* Performs the synchronization.
*
* <p>
* {@inheritDoc}
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<Void> run(OwnCloudClient client) {
RemoteOperationResult result;
mFailsInKeptInSyncFound = 0;
mConflictsFound = 0;
@@ -272,8 +281,7 @@ public class RefreshFolderOperation extends RemoteOperation {
}
private void updateOCVersion(OwnCloudClient client) {
UpdateOCVersionOperation update = new UpdateOCVersionOperation(mAccount, mContext);
RemoteOperationResult result = update.execute(client);
RemoteOperationResult<Void> result = new UpdateOCVersionOperation(mAccount, mContext).execute(client);
if (result.isSuccess()) {
// Update Capabilities for this account
updateCapabilities();
@@ -301,8 +309,7 @@ public class RefreshFolderOperation extends RemoteOperation {
String oldDirectEditingEtag = arbitraryDataProvider.getValue(mAccount,
ArbitraryDataProvider.DIRECT_EDITING_ETAG);
GetCapabilitiesOperation getCapabilities = new GetCapabilitiesOperation();
RemoteOperationResult result = getCapabilities.execute(mStorageManager, mContext);
RemoteOperationResult<OCCapability> result = new GetCapabilitiesOperation().execute(mStorageManager, mContext);
if (result.isSuccess()) {
String newDirectEditingEtag = mStorageManager.getCapability(mAccount.name).getDirectEditingEtag();
@@ -355,9 +362,9 @@ public class RefreshFolderOperation extends RemoteOperation {
}
}
private RemoteOperationResult checkForChanges(OwnCloudClient client) {
private RemoteOperationResult<RemoteFile> checkForChanges(OwnCloudClient client) {
mRemoteFolderChanged = true;
RemoteOperationResult result;
RemoteOperationResult<RemoteFile> result;
String remotePath = mLocalFolder.getRemotePath();
Log_OC.d(TAG, "Checking changes in " + mAccount.name + remotePath);
@@ -366,7 +373,7 @@ public class RefreshFolderOperation extends RemoteOperation {
result = new ReadFileRemoteOperation(remotePath).execute(client);
if (result.isSuccess()) {
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
OCFile remoteFolder = FileStorageUtils.fillOCFile(result.getResultData());
if (!mIgnoreETag) {
// check if remote and local folder are different
@@ -378,7 +385,7 @@ public class RefreshFolderOperation extends RemoteOperation {
}
}
result = new RemoteOperationResult(ResultCode.OK);
result = new RemoteOperationResult<>(ResultCode.OK);
Log_OC.i(TAG, "Checked " + mAccount.name + remotePath + " : " +
(mRemoteFolderChanged ? "changed" : "not changed"));
@@ -401,15 +408,15 @@ public class RefreshFolderOperation extends RemoteOperation {
}
private RemoteOperationResult fetchAndSyncRemoteFolder(OwnCloudClient client) {
private RemoteOperationResult<List<RemoteFile>> fetchAndSyncRemoteFolder(OwnCloudClient client) {
String remotePath = mLocalFolder.getRemotePath();
RemoteOperationResult result = new ReadFolderRemoteOperation(remotePath).execute(client);
RemoteOperationResult<List<RemoteFile>> result = new ReadFolderRemoteOperation(remotePath).execute(client);
Log_OC.d(TAG, "Synchronizing " + mAccount.name + remotePath);
if (result.isSuccess()) {
synchronizeData(result.getData());
synchronizeData(result.getResultData());
if (mConflictsFound > 0 || mFailsInKeptInSyncFound > 0) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
result = new RemoteOperationResult<>(ResultCode.SYNC_CONFLICT);
// should be a different result code, but will do the job
}
} else {
@@ -429,25 +436,25 @@ public class RefreshFolderOperation extends RemoteOperation {
mLocalFolder,
true,
mLocalFolder.isDown() && mLocalFolder.getStoragePath().startsWith(currentSavePath)
);
);
}
}
/**
* Synchronizes the data retrieved from the server about the contents of the target folder
* with the current data in the local database.
*
* Synchronizes the data retrieved from the server about the contents of the target folder with the current data in
* the local database.
* <p>
* Grants that mChildren is updated with fresh data after execution.
*
* @param folderAndFiles Remote folder and children files in Folder
*/
private void synchronizeData(List<Object> folderAndFiles) {
private void synchronizeData(List<RemoteFile> folderAndFiles) {
// get 'fresh data' from the database
mLocalFolder = mStorageManager.getFileByPath(mLocalFolder.getRemotePath());
// parse data from remote folder
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
OCFile remoteFolder = FileStorageUtils.fillOCFile(folderAndFiles.get(0));
remoteFolder.setParentId(mLocalFolder.getParentId());
remoteFolder.setFileId(mLocalFolder.getFileId());
@@ -487,7 +494,7 @@ public class RefreshFolderOperation extends RemoteOperation {
for (int i = 1; i < folderAndFiles.size(); i++) {
/// new OCFile instance with the data from the server
remote = (RemoteFile) folderAndFiles.get(i);
remote = folderAndFiles.get(i);
remoteFile = FileStorageUtils.fillOCFile(remote);
// new OCFile instance to merge fresh data from server with local state
@@ -678,25 +685,21 @@ public class RefreshFolderOperation extends RemoteOperation {
/**
* Syncs the Share resources for the files contained in the folder refreshed (children, not deeper descendants).
*
* @param client Handler of a session with an OC server.
* @return The result of the remote operation retrieving the Share resources in the folder refreshed by
* the operation.
* @param client Handler of a session with an OC server.
* @return The result of the remote operation retrieving the Share resources in the folder refreshed by the
* operation.
*/
private RemoteOperationResult refreshSharesForFolder(OwnCloudClient client) {
RemoteOperationResult result;
private RemoteOperationResult<List<OCShare>> refreshSharesForFolder(OwnCloudClient client) {
// remote request
GetSharesForFileRemoteOperation operation =
new GetSharesForFileRemoteOperation(mLocalFolder.getRemotePath(), true, true);
result = operation.execute(client);
RemoteOperationResult<List<OCShare>> result = new GetSharesForFileRemoteOperation(mLocalFolder.getRemotePath(),
true,
true)
.execute(client);
if (result.isSuccess()) {
// update local database
ArrayList<OCShare> shares = new ArrayList<>();
OCShare share;
for (Object obj : result.getData()) {
share = (OCShare) obj;
for (OCShare share : result.getResultData()) {
if (!ShareType.NO_SHARED.equals(share.getShareType())) {
shares.add(share);
}
@@ -56,18 +56,18 @@ import javax.crypto.NoSuchPaddingException;
/**
* Remote operation performing the removal of a remote encrypted file or folder
*/
public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
public class RemoveRemoteEncryptedFileOperation extends RemoteOperation<Void> {
private static final String TAG = RemoveRemoteEncryptedFileOperation.class.getSimpleName();
private static final int REMOVE_READ_TIMEOUT = 30000;
private static final int REMOVE_CONNECTION_TIMEOUT = 5000;
private String remotePath;
private String parentId;
private Account account;
private final String remotePath;
private final String parentId;
private final Account account;
private ArbitraryDataProvider arbitraryDataProvider;
private String fileName;
private final ArbitraryDataProvider arbitraryDataProvider;
private final String fileName;
/**
* Constructor
@@ -92,8 +92,8 @@ public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
* Performs the remove operation.
*/
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
protected RemoteOperationResult<Void> run(OwnCloudClient client) {
RemoteOperationResult<Void> result;
DeleteMethod delete = null;
String token = null;
DecryptedFolderMetadata metadata;
@@ -102,10 +102,10 @@ public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
try {
// Lock folder
RemoteOperationResult lockFileOperationResult = new LockFileRemoteOperation(parentId).execute(client);
RemoteOperationResult<String> lockFileOperationResult = new LockFileRemoteOperation(parentId).execute(client);
if (lockFileOperationResult.isSuccess()) {
token = (String) lockFileOperationResult.getData().get(0);
token = lockFileOperationResult.getResultData();
} else if (lockFileOperationResult.getHttpCode() == HttpStatus.SC_FORBIDDEN) {
throw new RemoteOperationFailedException("Forbidden! Please try again later.)");
} else {
@@ -113,15 +113,16 @@ public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
}
// refresh metadata
RemoteOperationResult getMetadataOperationResult = new GetMetadataRemoteOperation(parentId).execute(client);
RemoteOperationResult<String> getMetadataOperationResult =
new GetMetadataRemoteOperation(parentId).execute(client);
if (getMetadataOperationResult.isSuccess()) {
// decrypt metadata
String serializedEncryptedMetadata = (String) getMetadataOperationResult.getData().get(0);
String serializedEncryptedMetadata = getMetadataOperationResult.getResultData();
EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.deserializeJSON(
serializedEncryptedMetadata, new TypeToken<EncryptedFolderMetadata>() {
});
serializedEncryptedMetadata, new TypeToken<EncryptedFolderMetadata>() {
});
metadata = EncryptionUtils.decryptFolderMetaData(encryptedFolderMetadata, privateKey);
} else {
@@ -134,7 +135,7 @@ public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
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, delete);
result = new RemoteOperationResult<>(delete.succeeded() || status == HttpStatus.SC_NOT_FOUND, delete);
Log_OC.i(TAG, "Remove " + remotePath + ": " + result.getLogMessage());
// remove file from metadata
@@ -145,7 +146,7 @@ public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
String serializedFolderMetadata = EncryptionUtils.serializeJSON(encryptedFolderMetadata);
// upload metadata
RemoteOperationResult uploadMetadataOperationResult =
RemoteOperationResult<String> uploadMetadataOperationResult =
new UpdateMetadataRemoteOperation(parentId,
serializedFolderMetadata, token).execute(client);
@@ -163,7 +164,7 @@ public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
BadPaddingException |
IllegalBlockSizeException |
InvalidKeySpecException e) {
result = new RemoteOperationResult(e);
result = new RemoteOperationResult<>(e);
Log_OC.e(TAG, "Remove " + remotePath + ": " + result.getLogMessage(), e);
} finally {
@@ -173,7 +174,7 @@ public class RemoveRemoteEncryptedFileOperation extends RemoteOperation {
// unlock file
if (token != null) {
RemoteOperationResult unlockFileOperationResult = new UnlockFileRemoteOperation(parentId, token)
RemoteOperationResult<Void> unlockFileOperationResult = new UnlockFileRemoteOperation(parentId, token)
.execute(client);
if (!unlockFileOperationResult.isSuccess()) {
@@ -33,7 +33,7 @@ import org.json.JSONObject;
* Create asset for RichDocuments app from file, which is already stored on Nextcloud server
*/
public class RichDocumentsCreateAssetOperation extends RemoteOperation {
public class RichDocumentsCreateAssetOperation extends RemoteOperation<String> {
private static final String TAG = RichDocumentsCreateAssetOperation.class.getSimpleName();
private static final int SYNC_READ_TIMEOUT = 40000;
private static final int SYNC_CONNECTION_TIMEOUT = 5000;
@@ -44,14 +44,14 @@ public class RichDocumentsCreateAssetOperation extends RemoteOperation {
private static final String PARAMETER_FORMAT = "format";
private static final String PARAMETER_FORMAT_VALUE = "json";
private String path;
private final String path;
public RichDocumentsCreateAssetOperation(String path) {
this.path = path;
}
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
protected RemoteOperationResult<String> run(OwnCloudClient client) {
RemoteOperationResult<String> result;
Utf8PostMethod postMethod = null;
try {
@@ -71,16 +71,16 @@ public class RichDocumentsCreateAssetOperation extends RemoteOperation {
JSONObject respJSON = new JSONObject(response);
String url = respJSON.getString(NODE_URL);
result = new RemoteOperationResult(true, postMethod);
result.setSingleData(url);
result = new RemoteOperationResult<>(true, postMethod);
result.setResultData(url);
} else {
result = new RemoteOperationResult(false, postMethod);
result = new RemoteOperationResult<>(false, postMethod);
client.exhaustResponse(postMethod.getResponseBodyAsStream());
}
} catch (Exception e) {
result = new RemoteOperationResult(e);
result = new RemoteOperationResult<>(e);
Log_OC.e(TAG, "Create asset for richdocuments with path " + path + " failed: " + result.getLogMessage(),
result.getException());
result.getException());
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
@@ -1,98 +0,0 @@
/*
* Nextcloud Android client application
*
* @author Tobias Kaminsky
* Copyright (C) 2018 Tobias Kaminsky
* Copyright (C) 2018 Nextcloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.operations;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.utils.NextcloudServer;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.Utf8PostMethod;
import org.json.JSONObject;
/**
* Edit a file with Richdocuments. Returns URL which can be shown in WebView.
*/
public class RichDocumentsUrlOperation extends RemoteOperation {
/**
* TODO move to library
*/
private static final String TAG = RichDocumentsUrlOperation.class.getSimpleName();
private static final int SYNC_READ_TIMEOUT = 40000;
private static final int SYNC_CONNECTION_TIMEOUT = 5000;
private static final String DOCUMENT_URL = "/ocs/v2.php/apps/richdocuments/api/v1/document";
private static final String FILE_ID = "fileId";
// JSON node names
private static final String NODE_OCS = "ocs";
private static final String NODE_DATA = "data";
private static final String NODE_URL = "url";
private static final String JSON_FORMAT = "?format=json";
private String fileID;
public RichDocumentsUrlOperation(String fileID) {
this.fileID = fileID;
}
@NextcloudServer(max = 18)
protected RemoteOperationResult run(OwnCloudClient client) {
RemoteOperationResult result;
Utf8PostMethod postMethod = null;
try {
postMethod = new Utf8PostMethod(client.getBaseUri() + DOCUMENT_URL + JSON_FORMAT);
postMethod.setParameter(FILE_ID, fileID);
// remote request
postMethod.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE);
int status = client.executeMethod(postMethod, SYNC_READ_TIMEOUT, SYNC_CONNECTION_TIMEOUT);
if (status == HttpStatus.SC_OK) {
String response = postMethod.getResponseBodyAsString();
// Parse the response
JSONObject respJSON = new JSONObject(response);
String url = respJSON.getJSONObject(NODE_OCS).getJSONObject(NODE_DATA).getString(NODE_URL);
result = new RemoteOperationResult(true, postMethod);
result.setSingleData(url);
} else {
result = new RemoteOperationResult(false, postMethod);
client.exhaustResponse(postMethod.getResponseBodyAsStream());
}
} catch (Exception e) {
result = new RemoteOperationResult(e);
Log_OC.e(TAG, "Get rich document url for file with id " + fileID + " failed: " + result.getLogMessage(),
result.getException());
} finally {
if (postMethod != null) {
postMethod.releaseConnection();
}
}
return result;
}
}
@@ -42,24 +42,23 @@ import com.owncloud.android.utils.FileStorageUtils;
/**
* Remote operation performing the read of remote file in the ownCloud server.
*/
public class SynchronizeFileOperation extends SyncOperation {
public class SynchronizeFileOperation extends SyncOperation<RemoteFile> {
private static final String TAG = SynchronizeFileOperation.class.getSimpleName();
private OCFile mLocalFile;
private String mRemotePath;
private OCFile mServerFile;
private User mUser;
private boolean mSyncFileContents;
private Context mContext;
private boolean mTransferWasRequested;
private OCFile localFile;
private final String remotePath;
private OCFile serverFile;
private final User user;
private final boolean syncFileContents;
private final Context context;
private boolean transferWasRequested;
/**
* When 'false', uploads to the server are not done; only downloads or conflict detection.
* This is a temporal field.
* When 'false', uploads to the server are not done; only downloads or conflict detection. This is a temporal field.
* TODO Remove when 'folder synchronization' replaces 'folder download'.
*/
private boolean mAllowUploads;
private boolean allowUploads;
/**
@@ -82,13 +81,13 @@ public class SynchronizeFileOperation extends SyncOperation {
boolean syncFileContents,
Context context) {
mRemotePath = remotePath;
mLocalFile = null;
mServerFile = null;
mUser = user;
mSyncFileContents = syncFileContents;
mContext = context;
mAllowUploads = true;
this.remotePath = remotePath;
localFile = null;
serverFile = null;
this.user = user;
this.syncFileContents = syncFileContents;
this.context = context;
allowUploads = true;
}
@@ -118,23 +117,23 @@ public class SynchronizeFileOperation extends SyncOperation {
boolean syncFileContents,
Context context) {
mLocalFile = localFile;
mServerFile = serverFile;
if (mLocalFile != null) {
mRemotePath = mLocalFile.getRemotePath();
if (mServerFile != null && !mServerFile.getRemotePath().equals(mRemotePath)) {
this.localFile = localFile;
this.serverFile = serverFile;
if (this.localFile != null) {
remotePath = this.localFile.getRemotePath();
if (this.serverFile != null && !this.serverFile.getRemotePath().equals(remotePath)) {
throw new IllegalArgumentException("serverFile and localFile do not correspond" +
" to the same OC file");
" to the same OC file");
}
} else if (mServerFile != null) {
mRemotePath = mServerFile.getRemotePath();
} else if (this.serverFile != null) {
remotePath = this.serverFile.getRemotePath();
} else {
throw new IllegalArgumentException("Both serverFile and localFile are NULL");
}
mUser = user;
mSyncFileContents = syncFileContents;
mContext = context;
mAllowUploads = true;
this.user = user;
this.syncFileContents = syncFileContents;
this.context = context;
allowUploads = true;
}
@@ -170,61 +169,61 @@ public class SynchronizeFileOperation extends SyncOperation {
Context context) {
this(localFile, serverFile, user, syncFileContents, context);
mAllowUploads = allowUploads;
this.allowUploads = allowUploads;
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<RemoteFile> run(OwnCloudClient client) {
RemoteOperationResult result = null;
mTransferWasRequested = false;
RemoteOperationResult<RemoteFile> result = null;
transferWasRequested = false;
if (mLocalFile == null) {
if (localFile == null) {
// Get local file from the DB
mLocalFile = getStorageManager().getFileByPath(mRemotePath);
localFile = getStorageManager().getFileByPath(remotePath);
}
if (!mLocalFile.isDown()) {
if (!localFile.isDown()) {
/// easy decision
requestForDownload(mLocalFile);
result = new RemoteOperationResult(ResultCode.OK);
requestForDownload(localFile);
result = new RemoteOperationResult<>(ResultCode.OK);
} else {
/// local copy in the device -> need to think a bit more before do anything
if (mServerFile == null) {
ReadFileRemoteOperation operation = new ReadFileRemoteOperation(mRemotePath);
if (serverFile == null) {
ReadFileRemoteOperation operation = new ReadFileRemoteOperation(remotePath);
result = operation.execute(client);
if (result.isSuccess()) {
mServerFile = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
mServerFile.setLastSyncDateForProperties(System.currentTimeMillis());
serverFile = FileStorageUtils.fillOCFile(result.getResultData());
serverFile.setLastSyncDateForProperties(System.currentTimeMillis());
} else if (result.getCode() != ResultCode.FILE_NOT_FOUND) {
return result;
}
}
if (mServerFile != null) {
if (serverFile != null) {
/// check changes in server and local file
boolean serverChanged;
if (TextUtils.isEmpty(mLocalFile.getEtag())) {
if (TextUtils.isEmpty(localFile.getEtag())) {
// file uploaded (null) or downloaded ("") before upgrade to version 1.8.0; check the old condition
serverChanged = mServerFile.getModificationTimestamp() !=
mLocalFile.getModificationTimestampAtLastSyncForData();
serverChanged = serverFile.getModificationTimestamp() !=
localFile.getModificationTimestampAtLastSyncForData();
} else {
serverChanged = !mServerFile.getEtag().equals(mLocalFile.getEtag());
serverChanged = !serverFile.getEtag().equals(localFile.getEtag());
}
boolean localChanged =
mLocalFile.getLocalModificationTimestamp() > mLocalFile.getLastSyncDateForData();
localFile.getLocalModificationTimestamp() > localFile.getLastSyncDateForData();
/// decide action to perform depending upon changes
//if (!mLocalFile.getEtag().isEmpty() && localChanged && serverChanged) {
if (localChanged && serverChanged) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
getStorageManager().saveConflict(mLocalFile, mServerFile.getEtag());
result = new RemoteOperationResult<>(ResultCode.SYNC_CONFLICT);
getStorageManager().saveConflict(localFile, serverFile.getEtag());
} else if (localChanged) {
if (mSyncFileContents && mAllowUploads) {
requestForUpload(mLocalFile);
if (syncFileContents && allowUploads) {
requestForUpload(localFile);
// the local update of file properties will be done by the FileUploader
// service when the upload finishes
} else {
@@ -235,43 +234,43 @@ public class SynchronizeFileOperation extends SyncOperation {
// that an upload is necessary (for instance, in FileObserverService).
Log_OC.d(TAG, "Nothing to do here");
}
result = new RemoteOperationResult(ResultCode.OK);
result = new RemoteOperationResult<>(ResultCode.OK);
} else if (serverChanged) {
mLocalFile.setRemoteId(mServerFile.getRemoteId());
localFile.setRemoteId(serverFile.getRemoteId());
if (mSyncFileContents) {
requestForDownload(mLocalFile); // local, not server; we won't to keep
if (syncFileContents) {
requestForDownload(localFile); // local, not server; we won't to keep
// the value of favorite!
// the update of local data will be done later by the FileUploader
// service when the upload finishes
} else {
// TODO CHECK: is this really useful in some point in the code?
mServerFile.setFavorite(mLocalFile.isFavorite());
mServerFile.setLastSyncDateForData(mLocalFile.getLastSyncDateForData());
mServerFile.setStoragePath(mLocalFile.getStoragePath());
mServerFile.setParentId(mLocalFile.getParentId());
mServerFile.setEtag(mLocalFile.getEtag());
getStorageManager().saveFile(mServerFile);
serverFile.setFavorite(localFile.isFavorite());
serverFile.setLastSyncDateForData(localFile.getLastSyncDateForData());
serverFile.setStoragePath(localFile.getStoragePath());
serverFile.setParentId(localFile.getParentId());
serverFile.setEtag(localFile.getEtag());
getStorageManager().saveFile(serverFile);
}
result = new RemoteOperationResult(ResultCode.OK);
result = new RemoteOperationResult<>(ResultCode.OK);
} else {
// nothing changed, nothing to do
result = new RemoteOperationResult(ResultCode.OK);
result = new RemoteOperationResult<>(ResultCode.OK);
}
// safe blanket: sync'ing a not in-conflict file will clean wrong conflict markers in ancestors
if (result.getCode() != ResultCode.SYNC_CONFLICT) {
getStorageManager().saveConflict(mLocalFile, null);
getStorageManager().saveConflict(localFile, null);
}
} else {
// remote file does not exist, deleting local copy
boolean deleteResult = getStorageManager().removeFile(mLocalFile, true, true);
boolean deleteResult = getStorageManager().removeFile(localFile, true, true);
if (deleteResult) {
result = new RemoteOperationResult(ResultCode.FILE_NOT_FOUND);
result = new RemoteOperationResult<>(ResultCode.FILE_NOT_FOUND);
} else {
Log_OC.e(TAG, "Removal of local copy failed (remote file does not exist any longer).");
}
@@ -279,8 +278,8 @@ public class SynchronizeFileOperation extends SyncOperation {
}
Log_OC.i(TAG, "Synchronizing " + mUser.getAccountName() + ", file " + mLocalFile.getRemotePath() +
": " + result.getLogMessage());
Log_OC.i(TAG, "Synchronizing " + user.getAccountName() + ", file " + localFile.getRemotePath() +
": " + result.getLogMessage());
return result;
}
@@ -293,14 +292,14 @@ public class SynchronizeFileOperation extends SyncOperation {
*/
private void requestForUpload(OCFile file) {
FileUploader.uploadUpdateFile(
mContext,
mUser.toPlatformAccount(),
file,
FileUploader.LOCAL_BEHAVIOUR_MOVE,
NameCollisionPolicy.OVERWRITE
);
context,
user.toPlatformAccount(),
file,
FileUploader.LOCAL_BEHAVIOUR_MOVE,
NameCollisionPolicy.OVERWRITE
);
mTransferWasRequested = true;
transferWasRequested = true;
}
@@ -310,26 +309,26 @@ public class SynchronizeFileOperation extends SyncOperation {
* @param file OCFile object representing the file to download
*/
private void requestForDownload(OCFile file) {
Intent i = new Intent(mContext, FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_USER, mUser);
Intent i = new Intent(context, FileDownloader.class);
i.putExtra(FileDownloader.EXTRA_USER, user);
i.putExtra(FileDownloader.EXTRA_FILE, file);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
mContext.startForegroundService(i);
context.startForegroundService(i);
} else {
mContext.startService(i);
context.startService(i);
}
mTransferWasRequested = true;
transferWasRequested = true;
}
public boolean transferWasRequested() {
return mTransferWasRequested;
return transferWasRequested;
}
public OCFile getLocalFile() {
return mLocalFile;
return localFile;
}
}
@@ -168,15 +168,14 @@ public class SynchronizeFolderOperation extends SyncOperation {
}
// remote request
ReadFileRemoteOperation operation = new ReadFileRemoteOperation(mRemotePath);
RemoteOperationResult result = operation.execute(client);
RemoteOperationResult<RemoteFile> result = new ReadFileRemoteOperation(mRemotePath).execute(client);
if (result.isSuccess()) {
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
OCFile remoteFolder = FileStorageUtils.fillOCFile(result.getResultData());
// check if remote and local folder are different
mRemoteFolderChanged = !(remoteFolder.getEtag().equalsIgnoreCase(mLocalFolder.getEtag()));
result = new RemoteOperationResult(ResultCode.OK);
result = new RemoteOperationResult<>(ResultCode.OK);
Log_OC.i(TAG, "Checked " + user.getAccountName() + mRemotePath + " : " +
(mRemoteFolderChanged ? "changed" : "not changed"));
@@ -206,13 +205,13 @@ public class SynchronizeFolderOperation extends SyncOperation {
}
ReadFolderRemoteOperation operation = new ReadFolderRemoteOperation(mRemotePath);
RemoteOperationResult result = operation.execute(client);
RemoteOperationResult<List<RemoteFile>> result = operation.execute(client);
Log_OC.d(TAG, "Synchronizing " + user.getAccountName() + mRemotePath);
if (result.isSuccess()) {
synchronizeData(result.getData());
synchronizeData(result.getResultData());
if (mConflictsFound > 0 || mFailsInFileSyncsFound > 0) {
result = new RemoteOperationResult(ResultCode.SYNC_CONFLICT);
result = new RemoteOperationResult<>(ResultCode.SYNC_CONFLICT);
// should be a different result code, but will do the job
}
} else {
@@ -240,16 +239,16 @@ public class SynchronizeFolderOperation extends SyncOperation {
/**
* Synchronizes the data retrieved from the server about the contents of the target folder
* with the current data in the local database.
* Synchronizes the data retrieved from the server about the contents of the target folder with the current data in
* the local database.
*
* @param folderAndFiles Remote folder and children files in Folder
*/
private void synchronizeData(List<Object> folderAndFiles) throws OperationCancelledException {
private void synchronizeData(List<RemoteFile> folderAndFiles) throws OperationCancelledException {
// parse data from remote folder
OCFile remoteFolder = FileStorageUtils.fillOCFile((RemoteFile) folderAndFiles.get(0));
OCFile remoteFolder = FileStorageUtils.fillOCFile(folderAndFiles.get(0));
remoteFolder.setParentId(mLocalFolder.getParentId());
remoteFolder.setFileId(mLocalFolder.getFileId());
@@ -294,7 +293,7 @@ public class SynchronizeFolderOperation extends SyncOperation {
for (int i = 1; i < folderAndFiles.size(); i++) {
/// new OCFile instance with the data from the server
remote = (RemoteFile) folderAndFiles.get(i);
remote = folderAndFiles.get(i);
remoteFile = FileStorageUtils.fillOCFile(remote);
/// new OCFile instance to merge fresh data from server with local state
@@ -29,14 +29,16 @@ import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.UpdateShareRemoteOperation;
import com.owncloud.android.operations.common.SyncOperation;
import java.util.List;
/**
* Updates a note of a private share.
*/
public class UpdateNoteForShareOperation extends SyncOperation {
public class UpdateNoteForShareOperation extends SyncOperation<List<OCShare>> {
private long shareId;
private String note;
private final long shareId;
private final String note;
public UpdateNoteForShareOperation(long shareId, String note) {
this.shareId = shareId;
@@ -44,23 +46,23 @@ public class UpdateNoteForShareOperation extends SyncOperation {
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<List<OCShare>> run(OwnCloudClient client) {
OCShare share = getStorageManager().getShareById(shareId);
if (share == null) {
return new RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
return new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
}
UpdateShareRemoteOperation updateOperation = new UpdateShareRemoteOperation(share.getRemoteId());
updateOperation.setNote(note);
RemoteOperationResult result = updateOperation.execute(client);
RemoteOperationResult<List<OCShare>> result = updateOperation.execute(client);
if (result.isSuccess()) {
RemoteOperation getShareOp = new GetShareRemoteOperation(share.getRemoteId());
RemoteOperation<List<OCShare>> getShareOp = new GetShareRemoteOperation(share.getRemoteId());
result = getShareOp.execute(client);
if (result.isSuccess()) {
getStorageManager().saveShare((OCShare) result.getData().get(0));
getStorageManager().saveShare(result.getResultData().get(0));
}
}
@@ -1,4 +1,4 @@
/**
/*
* ownCloud Android client application
*
* @author David A. Velasco
@@ -41,30 +41,30 @@ import org.json.JSONObject;
/**
* Remote operation that checks the version of an ownCloud server and stores it locally
*/
public class UpdateOCVersionOperation extends RemoteOperation {
public class UpdateOCVersionOperation extends RemoteOperation<Void> {
private static final String TAG = UpdateOCVersionOperation.class.getSimpleName();
private static final String STATUS_PATH = "/status.php";
private Account mAccount;
private Context mContext;
private final Account account;
private final Context context;
private OwnCloudVersion mOwnCloudVersion;
public UpdateOCVersionOperation(Account account, Context context) {
mAccount = account;
mContext = context;
this.account = account;
this.context = context;
mOwnCloudVersion = null;
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
AccountManager accountMngr = AccountManager.get(mContext);
String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
protected RemoteOperationResult<Void> run(OwnCloudClient client) {
AccountManager accountManager = AccountManager.get(context);
String statUrl = accountManager.getUserData(account, Constants.KEY_OC_BASE_URL);
statUrl += STATUS_PATH;
RemoteOperationResult result = null;
RemoteOperationResult<Void> result = null;
GetMethod getMethod = null;
String webDav = client.getWebdavUri().toString();
@@ -73,31 +73,29 @@ public class UpdateOCVersionOperation extends RemoteOperation {
getMethod = new GetMethod(statUrl);
int status = client.executeMethod(getMethod);
if (status != HttpStatus.SC_OK) {
result = new RemoteOperationResult(false, getMethod);
result = new RemoteOperationResult<>(false, getMethod);
client.exhaustResponse(getMethod.getResponseBodyAsStream());
} else {
String response = getMethod.getResponseBodyAsString();
if (response != null) {
JSONObject json = new JSONObject(response);
if (json.getString("version") != null) {
if (json.has("version")) {
String version = json.getString("version");
mOwnCloudVersion = new OwnCloudVersion(version);
if (mOwnCloudVersion.isVersionValid()) {
accountMngr.setUserData(mAccount, Constants.KEY_OC_VERSION, mOwnCloudVersion.getVersion());
accountManager.setUserData(account, Constants.KEY_OC_VERSION, mOwnCloudVersion.getVersion());
Log_OC.d(TAG, "Got new OC version " + mOwnCloudVersion.toString());
result = new RemoteOperationResult(ResultCode.OK);
result = new RemoteOperationResult<>(ResultCode.OK);
} else {
Log_OC.w(TAG, "Invalid version number received from server: " + json.getString("version"));
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
}
}
}
if (result == null) {
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
}
}
@@ -105,11 +103,11 @@ public class UpdateOCVersionOperation extends RemoteOperation {
Log_OC.i(TAG, "Check for update of Nextcloud server version at " + webDav + ": " + result.getLogMessage());
} catch (JSONException e) {
result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
result = new RemoteOperationResult<>(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
Log_OC.e(TAG, "Check for update of Nextcloud server version at " + webDav + ": " + result.getLogMessage(), e);
} catch (Exception e) {
result = new RemoteOperationResult(e);
result = new RemoteOperationResult<>(e);
Log_OC.e(TAG, "Check for update of Nextcloud server version at " + webDav + ": " + result.getLogMessage(), e);
} finally {
@@ -24,7 +24,6 @@ package com.owncloud.android.operations;
import android.text.TextUtils;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.lib.resources.shares.GetShareRemoteOperation;
@@ -32,13 +31,15 @@ import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.UpdateShareRemoteOperation;
import com.owncloud.android.operations.common.SyncOperation;
import java.util.List;
/**
* Updates an existing private share for a given file.
*/
public class UpdateSharePermissionsOperation extends SyncOperation {
public class UpdateSharePermissionsOperation extends SyncOperation<List<OCShare>> {
private long shareId;
private final long shareId;
private int permissions;
private long expirationDateInMillis;
private String password;
@@ -57,13 +58,13 @@ public class UpdateSharePermissionsOperation extends SyncOperation {
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<List<OCShare>> run(OwnCloudClient client) {
OCShare share = getStorageManager().getShareById(shareId); // ShareType.USER | ShareType.GROUP
if (share == null) {
// TODO try to get remote share before failing?
return new RemoteOperationResult(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
return new RemoteOperationResult<>(RemoteOperationResult.ResultCode.SHARE_NOT_FOUND);
}
path = share.getPath();
@@ -73,13 +74,12 @@ public class UpdateSharePermissionsOperation extends SyncOperation {
updateOp.setPassword(password);
updateOp.setPermissions(permissions);
updateOp.setExpirationDate(expirationDateInMillis);
RemoteOperationResult result = updateOp.execute(client);
RemoteOperationResult<List<OCShare>> result = updateOp.execute(client);
if (result.isSuccess()) {
RemoteOperation getShareOp = new GetShareRemoteOperation(share.getRemoteId());
result = getShareOp.execute(client);
result = new GetShareRemoteOperation(share.getRemoteId()).execute(client);
if (result.isSuccess()) {
share = (OCShare) result.getData().get(0);
share = result.getResultData().get(0);
// TODO check permissions are being saved
updateData(share);
}
@@ -91,12 +91,7 @@ public class UpdateSharePermissionsOperation extends SyncOperation {
private void updateData(OCShare share) {
// Update DB with the response
share.setPath(path); // TODO - check if may be moved to UpdateRemoteShareOperation
if (path.endsWith(FileUtils.PATH_SEPARATOR)) {
share.setFolder(true);
} else {
share.setFolder(false);
}
share.setFolder(path.endsWith(FileUtils.PATH_SEPARATOR));
share.setPasswordProtected(!TextUtils.isEmpty(password));
getStorageManager().saveShare(share);
}
@@ -21,22 +21,23 @@
package com.owncloud.android.operations;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.resources.shares.GetShareRemoteOperation;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.shares.UpdateShareRemoteOperation;
import com.owncloud.android.operations.common.SyncOperation;
import java.util.List;
/**
* Updates an existing public share for a given file
*/
public class UpdateShareViaLinkOperation extends SyncOperation {
public class UpdateShareViaLinkOperation extends SyncOperation<List<OCShare>> {
private String password;
private Boolean hideFileDownload;
private long expirationDateInMillis;
private long shareId;
private final long shareId;
private String label;
public UpdateShareViaLinkOperation(long shareId) {
@@ -45,7 +46,7 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
}
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
protected RemoteOperationResult<List<OCShare>> run(OwnCloudClient client) {
OCShare publicShare = getStorageManager().getShareById(shareId);
UpdateShareRemoteOperation updateOp = new UpdateShareRemoteOperation(publicShare.getRemoteId());
@@ -54,14 +55,13 @@ public class UpdateShareViaLinkOperation extends SyncOperation {
updateOp.setHideFileDownload(hideFileDownload);
updateOp.setLabel(label);
RemoteOperationResult result = updateOp.execute(client);
RemoteOperationResult<List<OCShare>> result = updateOp.execute(client);
if (result.isSuccess()) {
// Retrieve updated share / save directly with password? -> no; the password is not to be saved
RemoteOperation getShareOp = new GetShareRemoteOperation(publicShare.getRemoteId());
result = getShareOp.execute(client);
result = new GetShareRemoteOperation(publicShare.getRemoteId()).execute(client);
if (result.isSuccess()) {
OCShare share = (OCShare) result.getData().get(0);
OCShare share = result.getResultData().get(0);
getStorageManager().saveShare(share);
}
}
@@ -1320,9 +1320,9 @@ public class UploadFileOperation extends SyncOperation {
}
ReadFileRemoteOperation operation = new ReadFileRemoteOperation(path);
RemoteOperationResult result = operation.execute(client);
RemoteOperationResult<RemoteFile> result = operation.execute(client);
if (result.isSuccess()) {
updateOCFile(file, (RemoteFile) result.getData().get(0));
updateOCFile(file, result.getResultData());
file.setLastSyncDateForProperties(syncDate);
} else {
Log_OC.e(TAG, "Error reading properties of file after successful upload; this is gonna hurt...");
@@ -38,29 +38,29 @@ import androidx.annotation.NonNull;
* <p>
* Provides methods to execute the operation both synchronously or asynchronously.
*/
public abstract class SyncOperation extends RemoteOperation {
public abstract class SyncOperation<T> extends RemoteOperation<T> {
private FileDataStorageManager storageManager;
/**
* Synchronously executes the operation on the received ownCloud account.
*
* <p>
* Do not call this method from the main thread.
* <p>
* This method should be used whenever an ownCloud account is available, instead of {@link #execute(OwnCloudClient,
* com.owncloud.android.datamodel.FileDataStorageManager)}.
*
* This method should be used whenever an ownCloud account is available, instead of
* {@link #execute(OwnCloudClient, com.owncloud.android.datamodel.FileDataStorageManager)}.
*
* @param storageManager
* @param context Android context for the component calling the method.
* @return Result of the operation.
* @param storageManager storageManager of account
* @param context Android context for the component calling the method.
* @return Result of the operation.
*/
public RemoteOperationResult execute(FileDataStorageManager storageManager, Context context) {
public RemoteOperationResult<T> execute(FileDataStorageManager storageManager, Context context) {
if (storageManager == null) {
throw new IllegalArgumentException("Trying to execute a sync operation with a " +
"NULL storage manager");
"NULL storage manager");
}
if (storageManager.getAccount() == null) {
throw new IllegalArgumentException("Trying to execute a sync operation with a " +
"storage manager for a NULL account");
"storage manager for a NULL account");
}
this.storageManager = storageManager;
return super.execute(this.storageManager.getAccount(), context);
@@ -68,17 +68,16 @@ public abstract class SyncOperation extends RemoteOperation {
/**
* Synchronously executes the remote operation
*
* Synchronously executes the remote operation
* <p>
* Do not call this method from the main thread.
*
* @param client Client object to reach an ownCloud server during the execution of the o
* peration.
* @param storageManager
* @return Result of the operation.
* @param client Client object to reach an ownCloud server during the execution of the operation.
* @param storageManager storageManager of account
* @return Result of the operation.
*/
public RemoteOperationResult execute(OwnCloudClient client,
FileDataStorageManager storageManager) {
public RemoteOperationResult<T> execute(OwnCloudClient client,
FileDataStorageManager storageManager) {
if (storageManager == null) {
throw new IllegalArgumentException("Trying to execute a sync operation with a " +
"NULL storage manager");
@@ -87,7 +86,7 @@ public abstract class SyncOperation extends RemoteOperation {
return super.execute(client);
}
public RemoteOperationResult execute(@NonNull NextcloudClient client, FileDataStorageManager storageManager) {
public RemoteOperationResult<T> execute(@NonNull NextcloudClient client, FileDataStorageManager storageManager) {
if (storageManager == null) {
throw new IllegalArgumentException("Trying to execute a sync operation with a NULL storage manager");
}
@@ -97,7 +96,7 @@ public abstract class SyncOperation extends RemoteOperation {
}
/**
/*
* Asynchronously executes the remote operation
*
* This method should be used whenever an ownCloud account is available, instead of
@@ -150,7 +149,7 @@ public abstract class SyncOperation extends RemoteOperation {
}
@Override
public RemoteOperationResult execute(OwnCloudClient client) {
public RemoteOperationResult<T> execute(OwnCloudClient client) {
throw new IllegalArgumentException("Trying to execute a sync operation without storage provider! Please use " +
"execute(OwnCloudClient client, FileDataStorageManager storageManager)" +
" instead");
@@ -207,13 +207,11 @@ public class UsersAndGroupsSearchProvider extends ContentProvider {
// request to the OC server about users and groups matching userQuery
GetShareesRemoteOperation searchRequest = new GetShareesRemoteOperation(userQuery, REQUESTED_PAGE,
RESULTS_PER_PAGE);
RemoteOperationResult result = searchRequest.execute(user.toPlatformAccount(), getContext());
RemoteOperationResult<List<JSONObject>> result = searchRequest.execute(user.toPlatformAccount(), getContext());
List<JSONObject> names = new ArrayList<>();
if (result.isSuccess()) {
for (Object o : result.getData()) {
names.add((JSONObject) o);
}
names.addAll(result.getResultData());
} else {
showErrorMessage(result);
}
@@ -29,6 +29,7 @@ import com.owncloud.android.R;
import com.owncloud.android.databinding.ActivityListLayoutBinding;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.activities.model.Activity;
import com.owncloud.android.lib.resources.activities.model.RichObject;
import com.owncloud.android.lib.resources.files.FileUtils;
import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository;
@@ -176,7 +177,7 @@ public class ActivitiesActivity extends DrawerActivity implements ActivityListIn
}
@Override
public void showActivities(List<Object> activities, NextcloudClient client, int lastGiven) {
public void showActivities(List<Activity> activities, NextcloudClient client, int lastGiven) {
boolean clear = false;
if (this.lastGiven == ActivitiesContract.ActionListener.UNDEFINED) {
clear = true;
@@ -20,6 +20,7 @@ package com.owncloud.android.ui.activities;
import com.nextcloud.common.NextcloudClient;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.resources.activities.model.Activity;
import com.owncloud.android.ui.activity.BaseActivity;
import java.util.List;
@@ -27,7 +28,8 @@ import java.util.List;
public interface ActivitiesContract {
interface View {
void showActivities(List<Object> activities, NextcloudClient client, int lastGiven);
void showActivities(List<Activity> activities, NextcloudClient client, int lastGiven);
void showActivitiesLoadError(String error);
void showActivityDetailUI(OCFile ocFile);
void showActivityDetailUIIsNull();
@@ -21,6 +21,7 @@ package com.owncloud.android.ui.activities;
import com.nextcloud.common.NextcloudClient;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.resources.activities.model.Activity;
import com.owncloud.android.ui.activities.data.activities.ActivitiesRepository;
import com.owncloud.android.ui.activities.data.files.FilesRepository;
import com.owncloud.android.ui.activity.BaseActivity;
@@ -55,7 +56,7 @@ public class ActivitiesPresenter implements ActivitiesContract.ActionListener {
}
activitiesRepository.getActivities(lastGiven, new ActivitiesRepository.LoadActivitiesCallback() {
@Override
public void onActivitiesLoaded(List<Object> activities, NextcloudClient client, int lastGiven) {
public void onActivitiesLoaded(List<Activity> activities, NextcloudClient client, int lastGiven) {
if (!activityStopped) {
activitiesView.setProgressIndicatorState(false);
@@ -19,6 +19,7 @@
package com.owncloud.android.ui.activities.data.activities;
import com.nextcloud.common.NextcloudClient;
import com.owncloud.android.lib.resources.activities.model.Activity;
import java.util.List;
@@ -29,7 +30,8 @@ import androidx.annotation.NonNull;
*/
public interface ActivitiesRepository {
interface LoadActivitiesCallback {
void onActivitiesLoaded(List<Object> activities, NextcloudClient client, int lastGiven);
void onActivitiesLoaded(List<Activity> activities, NextcloudClient client, int lastGiven);
void onActivitiesLoadedError(String error);
}
@@ -35,6 +35,6 @@ public interface ActivitiesServiceApi {
void onError (String error);
}
void getAllActivities(int lastGiven, ActivitiesServiceApi.ActivitiesServiceCallback<List<Object>> callback);
void getAllActivities(int lastGiven, ActivitiesServiceApi.ActivitiesServiceCallback<List<Activity>> callback);
}
@@ -36,7 +36,9 @@ import com.owncloud.android.lib.common.OwnCloudAccount;
import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.activities.ActivitiesResponse;
import com.owncloud.android.lib.resources.activities.GetActivitiesRemoteOperation;
import com.owncloud.android.lib.resources.activities.model.Activity;
import org.apache.commons.httpclient.HttpStatus;
@@ -57,7 +59,7 @@ public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
}
@Override
public void getAllActivities(int lastGiven, ActivitiesServiceCallback<List<Object>> callback) {
public void getAllActivities(int lastGiven, ActivitiesServiceCallback<List<Activity>> callback) {
GetActivityListTask getActivityListTask = new GetActivityListTask(accountManager.getUser().toPlatformAccount(),
lastGiven,
callback);
@@ -66,8 +68,8 @@ public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
private static class GetActivityListTask extends AsyncTask<Void, Void, Boolean> {
private final ActivitiesServiceCallback<List<Object>> callback;
private List<Object> activities;
private final ActivitiesServiceCallback<List<Activity>> callback;
private List<Activity> activities;
private Account account;
private int lastGiven;
private String errorMessage;
@@ -75,7 +77,7 @@ public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
private GetActivityListTask(Account account,
int lastGiven,
ActivitiesServiceCallback<List<Object>> callback) {
ActivitiesServiceCallback<List<Activity>> callback) {
this.account = account;
this.lastGiven = lastGiven;
this.callback = callback;
@@ -99,13 +101,11 @@ public class ActivitiesServiceApiImpl implements ActivitiesServiceApi {
getRemoteActivitiesOperation = new GetActivitiesRemoteOperation();
}
final RemoteOperationResult result = getRemoteActivitiesOperation.execute(client);
final RemoteOperationResult<ActivitiesResponse> result = getRemoteActivitiesOperation.execute(client);
if (result.isSuccess() && result.getData() != null) {
final ArrayList<Object> data = result.getData();
activities = (ArrayList) data.get(0);
lastGiven = (int) data.get(1);
if (result.isSuccess()) {
activities = result.getResultData().getActivities();
lastGiven = result.getResultData().getLastGiven();
return Boolean.TRUE;
} else {
Log_OC.d(TAG, result.getLogMessage());
@@ -19,6 +19,7 @@
package com.owncloud.android.ui.activities.data.activities;
import com.nextcloud.common.NextcloudClient;
import com.owncloud.android.lib.resources.activities.model.Activity;
import java.util.List;
@@ -36,16 +37,16 @@ public class RemoteActivitiesRepository implements ActivitiesRepository {
@Override
public void getActivities(int lastGiven, @NonNull LoadActivitiesCallback callback) {
activitiesServiceApi.getAllActivities(lastGiven,
new ActivitiesServiceApi.ActivitiesServiceCallback<List<Object>>() {
@Override
public void onLoaded(List<Object> activities, NextcloudClient client, int lastGiven) {
callback.onActivitiesLoaded(activities, client, lastGiven);
}
new ActivitiesServiceApi.ActivitiesServiceCallback<List<Activity>>() {
@Override
public void onLoaded(List<Activity> activities, NextcloudClient client, int lastGiven) {
callback.onActivitiesLoaded(activities, client, lastGiven);
}
@Override
public void onError(String error) {
callback.onActivitiesLoadedError(error);
}
});
@Override
public void onError(String error) {
callback.onActivitiesLoadedError(error);
}
});
}
}
@@ -98,10 +98,11 @@ public class FilesServiceApiImpl implements FilesServiceApi {
try {
OwnCloudClient ownCloudClient = clientFactory.create(user);
// always update file as it could be an old state saved in database
RemoteOperationResult resultRemoteFileOp = new ReadFileRemoteOperation(fileUrl).execute(ownCloudClient);
RemoteOperationResult<RemoteFile> resultRemoteFileOp = new ReadFileRemoteOperation(fileUrl)
.execute(ownCloudClient);
if (resultRemoteFileOp.isSuccess()) {
OCFile temp = FileStorageUtils.fillOCFile((RemoteFile) resultRemoteFileOp.getData().get(0));
OCFile temp = FileStorageUtils.fillOCFile(resultRemoteFileOp.getResultData());
remoteOcFile = baseActivity.getStorageManager().saveFileWithParent(temp, context);
if (remoteOcFile.isFolder()) {
@@ -189,10 +189,10 @@ public class ConflictsResolveActivity extends FileActivity implements OnConflict
new Thread(() -> {
try {
RemoteOperationResult result = operation.execute(getAccount(), this);
RemoteOperationResult<RemoteFile> result = operation.execute(getAccount(), this);
if (result.isSuccess()) {
existingFile = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
existingFile = FileStorageUtils.fillOCFile(result.getResultData());
existingFile.setLastSyncDateForProperties(System.currentTimeMillis());
startDialog();
@@ -86,7 +86,6 @@ import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
import com.owncloud.android.lib.common.Quota;
import com.owncloud.android.lib.common.UserInfo;
import com.owncloud.android.lib.common.accounts.ExternalLinksOperation;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
@@ -121,7 +120,6 @@ import org.parceler.Parcels;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
@@ -1158,13 +1156,13 @@ public abstract class DrawerActivity extends ToolbarActivity
FileActivity.APP_OPENED_COUNT, "0");
Log_OC.d("ExternalLinks", "update via api");
RemoteOperation getExternalLinksOperation = new ExternalLinksOperation();
RemoteOperationResult result = getExternalLinksOperation.execute(user.toPlatformAccount(), this);
RemoteOperationResult<List<ExternalLink>> result = new ExternalLinksOperation()
.execute(user.toPlatformAccount(), this);
if (result.isSuccess() && result.getData() != null) {
if (result.isSuccess() && result.getResultData() != null) {
externalLinksProvider.deleteAllExternalLinks();
ArrayList<ExternalLink> externalLinks = (ArrayList<ExternalLink>) (Object) result.getData();
List<ExternalLink> externalLinks = result.getResultData();
for (ExternalLink link : externalLinks) {
externalLinksProvider.storeExternalLink(link);
@@ -1172,7 +1170,8 @@ public abstract class DrawerActivity extends ToolbarActivity
}
} else {
arbitraryDataProvider.storeOrUpdateKeyValue(FilesSyncHelper.GLOBAL,
FileActivity.APP_OPENED_COUNT, String.valueOf(count + 1));
FileActivity.APP_OPENED_COUNT,
String.valueOf(count + 1));
}
} else {
externalLinksProvider.deleteAllExternalLinks();
@@ -93,6 +93,7 @@ import com.owncloud.android.utils.theme.ThemeToolbarUtils;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
@@ -779,7 +780,7 @@ public abstract class FileActivity extends DrawerActivity
}
private void onCreateShareViaLinkOperationFinish(CreateShareViaLinkOperation operation,
RemoteOperationResult result) {
RemoteOperationResult<List<OCShare>> result) {
FileDetailSharingFragment sharingFragment = getShareFileFragment();
if (result.isSuccess()) {
@@ -789,8 +790,7 @@ public abstract class FileActivity extends DrawerActivity
// therefore filtering for public_link
String link = "";
OCFile file = null;
for (Object object : result.getData()) {
OCShare shareLink = (OCShare) object;
for (OCShare shareLink : result.getResultData()) {
if (TAG_PUBLIC_LINK.equalsIgnoreCase(shareLink.getShareType().name())) {
link = shareLink.getShareLink();
file = getStorageManager().getFileByPath(shareLink.getPath());
@@ -39,7 +39,6 @@ import com.owncloud.android.R;
import com.owncloud.android.databinding.NotificationsLayoutBinding;
import com.owncloud.android.datamodel.ArbitraryDataProvider;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperation;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.notifications.GetNotificationsRemoteOperation;
@@ -223,13 +222,10 @@ public class NotificationsActivity extends DrawerActivity implements Notificatio
Thread t = new Thread(() -> {
initializeAdapter();
RemoteOperation getRemoteNotificationOperation = new GetNotificationsRemoteOperation();
final RemoteOperationResult result = getRemoteNotificationOperation.execute(client);
RemoteOperationResult<List<Notification>> result = new GetNotificationsRemoteOperation().execute(client);
if (result.isSuccess() && result.getNotificationData() != null) {
final List<Notification> notifications = result.getNotificationData();
runOnUiThread(() -> populateList(notifications));
if (result.isSuccess() && result.getResultData() != null) {
runOnUiThread(() -> populateList(result.getResultData()));
} else {
Log_OC.d(TAG, result.getLogMessage());
// show error
@@ -181,11 +181,11 @@ public class RichDocumentsEditorWebView extends EditorWebView {
new Thread(() -> {
User user = currentAccountProvider.getUser();
RichDocumentsCreateAssetOperation operation = new RichDocumentsCreateAssetOperation(file.getRemotePath());
RemoteOperationResult result = operation.execute(user.toPlatformAccount(), this);
RemoteOperationResult<String> result = new RichDocumentsCreateAssetOperation(file.getRemotePath())
.execute(user.toPlatformAccount(), this);
if (result.isSuccess()) {
String asset = (String) result.getSingleData();
String asset = result.getResultData();
runOnUiThread(() -> webview.evaluateJavascript("OCA.RichDocuments.documentsMain.postAsset('" +
file.getFileName() + "', '" + asset + "');", null));
@@ -287,7 +287,7 @@ public class UploadListActivity extends FileActivity {
// Do not call super in this case; more refactoring needed around onRemoteOperationFinish :'(
getFileOperationsHelper().setOpIdWaitingFor(Long.MAX_VALUE);
dismissLoadingDialog();
Account account = (Account) result.getData().get(0);
Account account = ((RemoteOperationResult<Account>) result).getResultData();
if (!result.isSuccess()) {
requestCredentialsUpdate(this, account);
@@ -114,7 +114,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
this.isDetailView = isDetailView;
}
public void setActivityItems(List<Object> activityItems, NextcloudClient client, boolean clear) {
public void setActivityItems(List<Activity> activityItems, NextcloudClient client, boolean clear) {
this.client = client;
String sTime = "";
@@ -122,8 +122,7 @@ public class ActivityListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
values.clear();
}
for (Object o : activityItems) {
Activity activity = (Activity) o;
for (Activity activity : activityItems) {
String time;
if (activity.getDatetime() != null) {
time = getHeaderDateString(context, activity.getDatetime().getTime()).toString();
@@ -835,8 +835,8 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
}
public void setData(List<Object> objects,
public void setData(List<OCShare> ocShares,
List<RemoteFile> remoteFiles,
ExtendedListFragment.SearchType searchType,
FileDataStorageManager storageManager,
@Nullable OCFile folder,
@@ -872,11 +872,13 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
}
// early exit
if (objects.size() > 0 && mStorageManager != null) {
if (searchType == ExtendedListFragment.SearchType.SHARED_FILTER) {
parseShares(objects);
} else {
parseVirtuals(objects, searchType);
if (mStorageManager != null) {
if (!ocShares.isEmpty() && searchType == ExtendedListFragment.SearchType.SHARED_FILTER) {
parseShares(ocShares);
}
if (!remoteFiles.isEmpty() && searchType != ExtendedListFragment.SearchType.SHARED_FILTER) {
parseVirtuals(remoteFiles, searchType);
}
}
@@ -894,52 +896,48 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
new Handler(Looper.getMainLooper()).post(this::notifyDataSetChanged);
}
private void parseShares(List<Object> objects) {
private void parseShares(List<OCShare> ocShares) {
List<OCShare> shares = new ArrayList<>();
for (Object shareObject : objects) {
for (OCShare ocShare : ocShares) {
// check type before cast as of long running data fetch it is possible that old result is filled
if (shareObject instanceof OCShare) {
OCShare ocShare = (OCShare) shareObject;
shares.add(ocShare);
shares.add(ocShare);
// get ocFile from Server to have an up-to-date copy
RemoteOperationResult<RemoteFile> result = new ReadFileRemoteOperation(ocShare.getPath())
.execute(user.toPlatformAccount(), activity);
// get ocFile from Server to have an up-to-date copy
RemoteOperationResult result = new ReadFileRemoteOperation(ocShare.getPath()).execute(user.toPlatformAccount(),
activity);
if (result.isSuccess()) {
OCFile file = FileStorageUtils.fillOCFile(result.getResultData());
FileStorageUtils.searchForLocalFileInDefaultPath(file, user.toPlatformAccount());
file = mStorageManager.saveFileWithParent(file, activity);
if (result.isSuccess()) {
OCFile file = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
FileStorageUtils.searchForLocalFileInDefaultPath(file, user.toPlatformAccount());
file = mStorageManager.saveFileWithParent(file, activity);
ShareType newShareType = ocShare.getShareType();
if (newShareType == ShareType.PUBLIC_LINK) {
file.setSharedViaLink(true);
} else if (newShareType == ShareType.USER ||
newShareType == ShareType.GROUP ||
newShareType == ShareType.EMAIL ||
newShareType == ShareType.FEDERATED ||
newShareType == ShareType.ROOM ||
newShareType == ShareType.CIRCLE) {
file.setSharedWithSharee(true);
}
mStorageManager.saveFile(file);
if (!mFiles.contains(file)) {
mFiles.add(file);
}
} else {
Log_OC.e(TAG, "Error in getting prop for file: " + ocShare.getPath());
ShareType newShareType = ocShare.getShareType();
if (newShareType == ShareType.PUBLIC_LINK) {
file.setSharedViaLink(true);
} else if (newShareType == ShareType.USER ||
newShareType == ShareType.GROUP ||
newShareType == ShareType.EMAIL ||
newShareType == ShareType.FEDERATED ||
newShareType == ShareType.ROOM ||
newShareType == ShareType.CIRCLE) {
file.setSharedWithSharee(true);
}
mStorageManager.saveFile(file);
if (!mFiles.contains(file)) {
mFiles.add(file);
}
} else {
Log_OC.e(TAG, "Error in getting prop for file: " + ocShare.getPath());
}
}
mStorageManager.saveShares(shares);
}
private void parseVirtuals(List<Object> objects, ExtendedListFragment.SearchType searchType) {
private void parseVirtuals(List<RemoteFile> remoteFiles, ExtendedListFragment.SearchType searchType) {
VirtualFolderType type;
boolean onlyMedia = false;
@@ -951,14 +949,14 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
type = VirtualFolderType.GALLERY;
onlyMedia = true;
int lastPosition = objects.size() - 1;
int lastPosition = remoteFiles.size() - 1;
if (lastPosition < 0) {
lastTimestamp = -1;
break;
}
RemoteFile lastFile = (RemoteFile) objects.get(lastPosition);
RemoteFile lastFile = remoteFiles.get(lastPosition);
lastTimestamp = lastFile.getModifiedTimestamp() / 1000;
break;
default:
@@ -968,8 +966,8 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
List<ContentValues> contentValues = new ArrayList<>();
for (Object remoteFile : objects) {
OCFile ocFile = FileStorageUtils.fillOCFile((RemoteFile) remoteFile);
for (RemoteFile remoteFile : remoteFiles) {
OCFile ocFile = FileStorageUtils.fillOCFile(remoteFile);
FileStorageUtils.searchForLocalFileInDefaultPath(ocFile, user.toPlatformAccount());
try {
@@ -86,17 +86,15 @@ public class TrashbinListAdapter extends RecyclerView.Adapter<RecyclerView.ViewH
this.context = context;
}
public void setTrashbinFiles(List<Object> trashbinFiles, boolean clear) {
public void setTrashbinFiles(List<TrashbinFile> trashbinFiles, boolean clear) {
if (clear) {
files.clear();
}
for (Object file : trashbinFiles) {
files.add((TrashbinFile) file);
}
files.addAll(trashbinFiles);
files = preferences.getSortOrderByType(FileSortOrder.Type.trashBinView,
FileSortOrder.sort_new_to_old).sortTrashbinFiles(files);
FileSortOrder.sort_new_to_old).sortTrashbinFiles(files);
notifyDataSetChanged();
}
@@ -40,13 +40,15 @@ import com.owncloud.android.ui.fragment.OCFileListFragment;
import com.owncloud.android.utils.DisplayUtils;
import com.owncloud.android.utils.FileStorageUtils;
import java.util.List;
import static com.owncloud.android.lib.resources.files.SearchRemoteOperation.SearchType.FILE_ID_SEARCH;
public class FetchRemoteFileTask extends AsyncTask<Void, Void, String> {
private Account account;
private String fileId;
private FileDataStorageManager storageManager;
private FileDisplayActivity fileDisplayActivity;
private final Account account;
private final String fileId;
private final FileDataStorageManager storageManager;
private final FileDisplayActivity fileDisplayActivity;
public FetchRemoteFileTask(Account account,
String fileId,
@@ -62,19 +64,19 @@ public class FetchRemoteFileTask extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... voids) {
SearchRemoteOperation searchRemoteOperation = new SearchRemoteOperation(fileId,
FILE_ID_SEARCH,
false);
RemoteOperationResult remoteOperationResult = searchRemoteOperation.execute(account, fileDisplayActivity);
RemoteOperationResult<List<RemoteFile>> remoteOperationResult = new SearchRemoteOperation(fileId,
FILE_ID_SEARCH,
false)
.execute(account, fileDisplayActivity);
if (remoteOperationResult.isSuccess() && remoteOperationResult.getData() != null) {
if (remoteOperationResult.getData().isEmpty()) {
if (remoteOperationResult.isSuccess() && remoteOperationResult.getResultData() != null) {
if (remoteOperationResult.getResultData().isEmpty()) {
return fileDisplayActivity.getString(R.string.remote_file_fetch_failed);
}
String remotePath = ((RemoteFile) remoteOperationResult.getData().get(0)).getRemotePath();
String remotePath = remoteOperationResult.getResultData().get(0).getRemotePath();
ReadFileRemoteOperation operation = new ReadFileRemoteOperation(remotePath);
RemoteOperationResult result = operation.execute(account, fileDisplayActivity);
RemoteOperationResult<RemoteFile> result = new ReadFileRemoteOperation(remotePath)
.execute(account, fileDisplayActivity);
if (!result.isSuccess()) {
Exception exception = result.getException();
@@ -87,7 +89,7 @@ public class FetchRemoteFileTask extends AsyncTask<Void, Void, String> {
}
}
RemoteFile remoteFile = (RemoteFile) result.getData().get(0);
RemoteFile remoteFile = result.getResultData();
OCFile ocFile = FileStorageUtils.fillOCFile(remoteFile);
FileStorageUtils.searchForLocalFileInDefaultPath(ocFile, account);
@@ -28,13 +28,16 @@ import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
import com.owncloud.android.lib.resources.files.model.RemoteFile;
import com.owncloud.android.ui.adapter.OCFileListAdapter;
import com.owncloud.android.ui.fragment.ExtendedListFragment;
import com.owncloud.android.ui.fragment.GalleryFragment;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
public class GallerySearchTask extends AsyncTask<Void, Void, RemoteOperationResult> {
public class GallerySearchTask extends AsyncTask<Void, Void, RemoteOperationResult<List<RemoteFile>>> {
private int columnCount;
private User user;
@@ -67,15 +70,15 @@ public class GallerySearchTask extends AsyncTask<Void, Void, RemoteOperationResu
}
@Override
protected RemoteOperationResult doInBackground(Void... voids) {
protected RemoteOperationResult<List<RemoteFile>> doInBackground(Void... voids) {
if (photoFragmentWeakReference.get() == null) {
return new RemoteOperationResult(new Exception("Photo fragment is null"));
return new RemoteOperationResult<>(new Exception("Photo fragment is null"));
}
GalleryFragment photoFragment = photoFragmentWeakReference.get();
OCFileListAdapter adapter = photoFragment.getAdapter();
if (isCancelled()) {
return new RemoteOperationResult(new Exception("Cancelled"));
return new RemoteOperationResult<>(new Exception("Cancelled"));
} else {
limit = 15 * columnCount;
@@ -90,34 +93,37 @@ public class GallerySearchTask extends AsyncTask<Void, Void, RemoteOperationResu
if (photoFragment.getContext() != null) {
return searchRemoteOperation.execute(user.toPlatformAccount(), photoFragment.getContext());
} else {
return new RemoteOperationResult(new IllegalStateException("No context available"));
return new RemoteOperationResult<>(new IllegalStateException("No context available"));
}
}
}
@Override
protected void onPostExecute(RemoteOperationResult result) {
protected void onPostExecute(RemoteOperationResult<List<RemoteFile>> result) {
if (photoFragmentWeakReference.get() != null) {
GalleryFragment photoFragment = photoFragmentWeakReference.get();
if (result.isSuccess() && result.getData() != null && !isCancelled()) {
if (result.getData() == null || result.getData().size() == 0) {
if (result.isSuccess() && result.getResultData() != null && !isCancelled()) {
if (result.getResultData() == null || result.getResultData().size() == 0) {
photoFragment.setSearchDidNotFindNewPhotos(true);
} else {
OCFileListAdapter adapter = photoFragment.getAdapter();
if (result.getData().size() < limit) {
if (result.getResultData().size() < limit) {
// stop loading spinner
photoFragment.setSearchDidNotFindNewPhotos(true);
}
adapter.setData(result.getData(),
adapter.setData(new ArrayList<>(),
result.getResultData(),
ExtendedListFragment.SearchType.GALLERY_SEARCH,
storageManager,
null,
false);
adapter.notifyDataSetChanged();
Log_OC.d(this, "Search: count: " + result.getData().size() + " total: " + adapter.getFiles().size());
Log_OC.d(this,
"Search: count: " + result.getResultData().size() + " total: " + adapter.getFiles().size());
}
}
@@ -24,19 +24,19 @@ package com.owncloud.android.ui.asynctasks;
import android.accounts.Account;
import android.os.AsyncTask;
import com.nextcloud.android.lib.resources.richdocuments.RichDocumentsUrlRemoteOperation;
import com.nextcloud.client.account.User;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.operations.RichDocumentsUrlOperation;
import com.owncloud.android.ui.activity.EditorWebView;
import java.lang.ref.WeakReference;
public class RichDocumentsLoadUrlTask extends AsyncTask<Void, Void, String> {
private Account account;
private WeakReference<EditorWebView> editorWebViewWeakReference;
private OCFile file;
private final Account account;
private final WeakReference<EditorWebView> editorWebViewWeakReference;
private final OCFile file;
public RichDocumentsLoadUrlTask(EditorWebView editorWebView, User user, OCFile file) {
this.account = user.toPlatformAccount();
@@ -52,13 +52,14 @@ public class RichDocumentsLoadUrlTask extends AsyncTask<Void, Void, String> {
return "";
}
RemoteOperationResult result = new RichDocumentsUrlOperation(file.getLocalId()).execute(account, editorWebView);
RemoteOperationResult<String> result = new RichDocumentsUrlRemoteOperation(file.getLocalId())
.execute(account, editorWebView);
if (!result.isSuccess()) {
return "";
}
return (String) result.getData().get(0);
return result.getResultData();
}
@Override
@@ -61,7 +61,7 @@ public class TextEditorLoadUrlTask extends AsyncTask<Void, Void, String> {
return "";
}
RemoteOperationResult result = new DirectEditingOpenFileRemoteOperation(file.getRemotePath(), editor.id)
RemoteOperationResult<String> result = new DirectEditingOpenFileRemoteOperation(file.getRemotePath(), editor.id)
.execute(account, editorWebViewWeakReference.get());
@@ -69,7 +69,7 @@ public class TextEditorLoadUrlTask extends AsyncTask<Void, Void, String> {
return "";
}
return (String) result.getData().get(0);
return result.getResultData();
}
@Override
@@ -33,6 +33,7 @@ import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import com.nextcloud.android.lib.resources.richdocuments.CreateFileFromTemplateRemoteOperation;
import com.nextcloud.client.account.CurrentAccountProvider;
import com.nextcloud.client.account.User;
import com.nextcloud.client.di.Injectable;
@@ -43,7 +44,6 @@ import com.owncloud.android.databinding.ChooseTemplateBinding;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.datamodel.Template;
import com.owncloud.android.files.CreateFileFromTemplateOperation;
import com.owncloud.android.files.FetchTemplateOperation;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
@@ -254,11 +254,11 @@ public class ChooseRichDocumentsTemplateDialogFragment extends DialogFragment im
}
private static class CreateFileFromTemplateTask extends AsyncTask<Void, Void, String> {
private OwnCloudClient client;
private WeakReference<ChooseRichDocumentsTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
private Template template;
private String path;
private User user;
private final OwnCloudClient client;
private final WeakReference<ChooseRichDocumentsTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
private final Template template;
private final String path;
private final User user;
private OCFile file;
CreateFileFromTemplateTask(ChooseRichDocumentsTemplateDialogFragment chooseTemplateDialogFragment,
@@ -266,7 +266,7 @@ public class ChooseRichDocumentsTemplateDialogFragment extends DialogFragment im
Template template,
String path,
User user
) {
) {
this.client = client;
this.chooseTemplateDialogFragmentWeakReference = new WeakReference<>(chooseTemplateDialogFragment);
this.template = template;
@@ -276,14 +276,15 @@ public class ChooseRichDocumentsTemplateDialogFragment extends DialogFragment im
@Override
protected String doInBackground(Void... voids) {
RemoteOperationResult result = new CreateFileFromTemplateOperation(path, template.getId()).execute(client);
RemoteOperationResult<String> result = new CreateFileFromTemplateRemoteOperation(path, template.getId())
.execute(client);
if (result.isSuccess()) {
// get file
RemoteOperationResult newFileResult = new ReadFileRemoteOperation(path).execute(client);
RemoteOperationResult<RemoteFile> newFileResult = new ReadFileRemoteOperation(path).execute(client);
if (newFileResult.isSuccess()) {
OCFile temp = FileStorageUtils.fillOCFile((RemoteFile) newFileResult.getData().get(0));
OCFile temp = FileStorageUtils.fillOCFile(newFileResult.getResultData());
if (chooseTemplateDialogFragmentWeakReference.get() != null) {
FileDataStorageManager storageManager = new FileDataStorageManager(
@@ -292,7 +293,7 @@ public class ChooseRichDocumentsTemplateDialogFragment extends DialogFragment im
storageManager.saveFile(temp);
file = storageManager.getFileByPath(path);
return result.getData().get(0).toString();
return result.getResultData();
} else {
return "";
}
@@ -330,8 +331,8 @@ public class ChooseRichDocumentsTemplateDialogFragment extends DialogFragment im
private static class FetchTemplateTask extends AsyncTask<Type, Void, List<Template>> {
private OwnCloudClient client;
private WeakReference<ChooseRichDocumentsTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
private final OwnCloudClient client;
private final WeakReference<ChooseRichDocumentsTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
FetchTemplateTask(ChooseRichDocumentsTemplateDialogFragment chooseTemplateDialogFragment, OwnCloudClient client) {
this.client = client;
@@ -340,15 +341,14 @@ public class ChooseRichDocumentsTemplateDialogFragment extends DialogFragment im
@Override
protected List<Template> doInBackground(Type... type) {
FetchTemplateOperation fetchTemplateOperation = new FetchTemplateOperation(type[0]);
RemoteOperationResult result = fetchTemplateOperation.execute(client);
RemoteOperationResult<List<Template>> result = new FetchTemplateOperation(type[0]).execute(client);
if (!result.isSuccess()) {
return new ArrayList<>();
}
List<Template> templateList = new ArrayList<>();
for (Object object : result.getData()) {
for (Object object : result.getResultData()) {
templateList.add((Template) object);
}
@@ -279,12 +279,12 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements View
}
private static class CreateFileFromTemplateTask extends AsyncTask<Void, Void, String> {
private ClientFactory clientFactory;
private WeakReference<ChooseTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
private Template template;
private String path;
private Creator creator;
private User user;
private final ClientFactory clientFactory;
private final WeakReference<ChooseTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
private final Template template;
private final String path;
private final Creator creator;
private final User user;
private OCFile file;
CreateFileFromTemplateTask(ChooseTemplateDialogFragment chooseTemplateDialogFragment,
@@ -293,7 +293,7 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements View
Template template,
String path,
Creator creator
) {
) {
this.clientFactory = clientFactory;
this.chooseTemplateDialogFragmentWeakReference = new WeakReference<>(chooseTemplateDialogFragment);
this.template = template;
@@ -316,7 +316,7 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements View
return "";
}
RemoteOperationResult newFileResult = new ReadFileRemoteOperation(path).execute(client);
RemoteOperationResult<RemoteFile> newFileResult = new ReadFileRemoteOperation(path).execute(client);
if (!newFileResult.isSuccess()) {
return "";
}
@@ -335,7 +335,7 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements View
FileDataStorageManager storageManager = new FileDataStorageManager(user.toPlatformAccount(),
context.getContentResolver());
OCFile temp = FileStorageUtils.fillOCFile((RemoteFile) newFileResult.getData().get(0));
OCFile temp = FileStorageUtils.fillOCFile(newFileResult.getResultData());
storageManager.saveFile(temp);
file = storageManager.getFileByPath(path);
@@ -372,10 +372,10 @@ public class ChooseTemplateDialogFragment extends DialogFragment implements View
private static class FetchTemplateTask extends AsyncTask<Void, Void, TemplateList> {
private User user;
private ClientFactory clientFactory;
private WeakReference<ChooseTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
private Creator creator;
private final User user;
private final ClientFactory clientFactory;
private final WeakReference<ChooseTemplateDialogFragment> chooseTemplateDialogFragmentWeakReference;
private final Creator creator;
FetchTemplateTask(ChooseTemplateDialogFragment chooseTemplateDialogFragment,
ClientFactory clientFactory,
@@ -274,14 +274,13 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
// if available
// - store public key
// - decrypt private key, store unencrypted private key in database
GetPublicKeyOperation publicKeyOperation = new GetPublicKeyOperation();
RemoteOperationResult publicKeyResult = publicKeyOperation.execute(user.toPlatformAccount(), getContext());
RemoteOperationResult<String> publicKeyResult = new GetPublicKeyOperation()
.execute(user.toPlatformAccount(), getContext());
if (publicKeyResult.isSuccess()) {
Log_OC.d(TAG, "public key successful downloaded for " + user.getAccountName());
String publicKeyFromServer = (String) publicKeyResult.getData().get(0);
String publicKeyFromServer = publicKeyResult.getResultData();
arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(),
EncryptionUtils.PUBLIC_KEY,
publicKeyFromServer);
@@ -348,12 +347,12 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
String userId = accountManager.getUserData(user.toPlatformAccount(), AccountUtils.Constants.KEY_USER_ID);
String urlEncoded = CsrHelper.generateCsrPemEncodedString(keyPair, userId);
SendCSROperation operation = new SendCSROperation(urlEncoded);
RemoteOperationResult result = operation.execute(user.toPlatformAccount(), getContext());
RemoteOperationResult<String> result = new SendCSROperation(urlEncoded)
.execute(user.toPlatformAccount(), getContext());
if (result.isSuccess()) {
Log_OC.d(TAG, "public key success");
publicKey = (String) result.getData().get(0);
publicKey = result.getResultData();
} else {
keyResult = KEY_FAILED;
return "";
@@ -363,24 +362,23 @@ public class SetupEncryptionDialogFragment extends DialogFragment {
String privateKeyString = EncryptionUtils.encodeBytesToBase64String(privateKey.getEncoded());
String privatePemKeyString = EncryptionUtils.privateKeyToPEM(privateKey);
String encryptedPrivateKey = EncryptionUtils.encryptPrivateKey(privatePemKeyString,
generateMnemonicString(false));
generateMnemonicString(false));
// upload encryptedPrivateKey
StorePrivateKeyOperation storePrivateKeyOperation = new StorePrivateKeyOperation(encryptedPrivateKey);
RemoteOperationResult storePrivateKeyResult = storePrivateKeyOperation.execute(user.toPlatformAccount(),
getContext());
RemoteOperationResult<String> storePrivateKeyResult = new StorePrivateKeyOperation(encryptedPrivateKey)
.execute(user.toPlatformAccount(), getContext());
if (storePrivateKeyResult.isSuccess()) {
Log_OC.d(TAG, "private key success");
arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.PRIVATE_KEY,
privateKeyString);
privateKeyString);
arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.PUBLIC_KEY, publicKey);
arbitraryDataProvider.storeOrUpdateKeyValue(user.getAccountName(), EncryptionUtils.MNEMONIC,
generateMnemonicString(true));
generateMnemonicString(true));
keyResult = KEY_CREATED;
return (String) storePrivateKeyResult.getData().get(0);
return storePrivateKeyResult.getResultData();
} else {
DeletePublicKeyOperation deletePublicKeyOperation = new DeletePublicKeyOperation();
deletePublicKeyOperation.execute(user.toPlatformAccount(), getContext());
@@ -45,6 +45,7 @@ import com.owncloud.android.datamodel.OCFile;
import com.owncloud.android.lib.common.OwnCloudClient;
import com.owncloud.android.lib.common.operations.RemoteOperationResult;
import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.activities.ActivitiesResponse;
import com.owncloud.android.lib.resources.activities.GetActivitiesRemoteOperation;
import com.owncloud.android.lib.resources.activities.model.RichObject;
import com.owncloud.android.lib.resources.comments.MarkCommentsAsReadRemoteOperation;
@@ -66,7 +67,6 @@ import com.owncloud.android.utils.theme.ThemeTextInputUtils;
import org.apache.commons.httpclient.HttpStatus;
import org.greenrobot.eventbus.EventBus;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
@@ -294,34 +294,30 @@ public class FileDetailActivitiesFragment extends Fragment implements
isLoadingActivities = true;
GetActivitiesRemoteOperation getRemoteNotificationOperation;
GetActivitiesRemoteOperation getActivitiesRemoteOperation;
if (lastGiven > 0) {
getRemoteNotificationOperation = new GetActivitiesRemoteOperation(file.getLocalId(), lastGiven);
getActivitiesRemoteOperation = new GetActivitiesRemoteOperation(file.getLocalId(), lastGiven);
} else {
getRemoteNotificationOperation = new GetActivitiesRemoteOperation(file.getLocalId());
getActivitiesRemoteOperation = new GetActivitiesRemoteOperation(file.getLocalId());
}
Log_OC.d(TAG, "BEFORE getRemoteActivitiesOperation.execute");
RemoteOperationResult result = nextcloudClient.execute(getRemoteNotificationOperation);
RemoteOperationResult<ActivitiesResponse> result = nextcloudClient.execute(getActivitiesRemoteOperation);
ArrayList<Object> versions = null;
List<FileVersion> versions = null;
if (restoreFileVersionSupported) {
ReadFileVersionsRemoteOperation readFileVersionsOperation = new ReadFileVersionsRemoteOperation(
file.getLocalId());
RemoteOperationResult<List<FileVersion>> fileVersionResult =
new ReadFileVersionsRemoteOperation(file.getLocalId()).execute(ownCloudClient);
RemoteOperationResult result1 = readFileVersionsOperation.execute(ownCloudClient);
if (result1.isSuccess()) {
versions = result1.getData();
if (fileVersionResult.isSuccess()) {
versions = fileVersionResult.getResultData();
}
}
if (result.isSuccess() && result.getData() != null) {
final List<Object> data = result.getData();
final List<Object> activitiesAndVersions = (ArrayList) data.get(0);
this.lastGiven = (int) data.get(1);
if (result.isSuccess() && result.getResultData() != null) {
final List<Object> activitiesAndVersions = (List) result.getResultData().getActivities();
this.lastGiven = result.getResultData().getLastGiven();
if (activitiesAndVersions.isEmpty()) {
this.lastGiven = END_REACHED;
@@ -366,7 +362,7 @@ public class FileDetailActivitiesFragment extends Fragment implements
if (file.getUnreadCommentsCount() > 0) {
MarkCommentsAsReadRemoteOperation unreadOperation = new MarkCommentsAsReadRemoteOperation(
file.getLocalId());
RemoteOperationResult remoteOperationResult = unreadOperation.execute(ownCloudClient);
RemoteOperationResult<Void> remoteOperationResult = unreadOperation.execute(ownCloudClient);
if (remoteOperationResult.isSuccess()) {
EventBus.getDefault().post(new CommentsEvent(file.getRemoteId()));
@@ -459,10 +455,10 @@ public class FileDetailActivitiesFragment extends Fragment implements
private static class SubmitCommentTask extends AsyncTask<Void, Void, Boolean> {
private String message;
private String fileId;
private VersionListInterface.CommentCallback callback;
private OwnCloudClient client;
private final String message;
private final String fileId;
private final VersionListInterface.CommentCallback callback;
private final OwnCloudClient client;
private SubmitCommentTask(String message, String fileId, VersionListInterface.CommentCallback callback,
OwnCloudClient client) {
@@ -134,6 +134,7 @@ public class GalleryFragment extends OCFileListFragment {
if (refresh || preferences.getPhotoSearchTimestamp() == 0 ||
System.currentTimeMillis() - preferences.getPhotoSearchTimestamp() >= 30 * 1000) {
mAdapter.setData(
new ArrayList<>(),
new ArrayList<>(),
SearchType.GALLERY_SEARCH,
mContainerActivity.getStorageManager(),
@@ -69,7 +69,9 @@ import com.owncloud.android.lib.common.utils.Log_OC;
import com.owncloud.android.lib.resources.e2ee.ToggleEncryptionRemoteOperation;
import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
import com.owncloud.android.lib.resources.files.ToggleFavoriteRemoteOperation;
import com.owncloud.android.lib.resources.files.model.RemoteFile;
import com.owncloud.android.lib.resources.shares.GetSharesRemoteOperation;
import com.owncloud.android.lib.resources.shares.OCShare;
import com.owncloud.android.lib.resources.status.OCCapability;
import com.owncloud.android.ui.activity.FileActivity;
import com.owncloud.android.ui.activity.FileDisplayActivity;
@@ -210,7 +212,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
protected MenuItemAddRemove menuItemAddRemoveValue = MenuItemAddRemove.ADD_GRID_AND_SORT_WITH_SEARCH;
private List<MenuItem> mOriginalMenuItems = new ArrayList<>();
private final List<MenuItem> mOriginalMenuItems = new ArrayList<>();
@Override
public void onCreate(Bundle savedInstanceState) {
@@ -485,11 +487,11 @@ public class OCFileListFragment extends ExtendedListFragment implements
@Override
public void createRichWorkspace() {
new Thread(() -> {
RemoteOperationResult result = new RichWorkspaceDirectEditingRemoteOperation(mFile.getRemotePath())
RemoteOperationResult<String> result = new RichWorkspaceDirectEditingRemoteOperation(mFile.getRemotePath())
.execute(accountManager.getUser().toPlatformAccount(), requireContext());
if (result.isSuccess()) {
String url = (String) result.getSingleData();
String url = result.getResultData();
mContainerActivity.getFileOperationsHelper().openRichWorkspaceWithTextEditor(mFile,
url,
requireContext());
@@ -590,7 +592,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
/**
* Selected items in list when action mode is closed by drawer
*/
private Set<OCFile> mSelectionWhenActionModeClosedByDrawer = new HashSet<>();
private final Set<OCFile> mSelectionWhenActionModeClosedByDrawer = new HashSet<>();
@Override
public void onDrawerSlide(@NonNull View drawerView, float slideOffset) {
@@ -1296,12 +1298,8 @@ public class OCFileListFragment extends ExtendedListFragment implements
setGridSwitchButton();
}
if (mHideFab) {
setFabVisible(false);
} else {
setFabVisible(true);
// registerFabListener();
}
// registerFabListener();
setFabVisible(!mHideFab);
// FAB
setFabEnabled(mFile != null && mFile.canWrite());
@@ -1513,7 +1511,12 @@ public class OCFileListFragment extends ExtendedListFragment implements
prepareCurrentSearch(event);
searchFragment = true;
setEmptyListLoadingMessage();
mAdapter.setData(new ArrayList<>(), SearchType.NO_SEARCH, mContainerActivity.getStorageManager(), mFile, true);
mAdapter.setData(new ArrayList<>(),
new ArrayList<>(),
SearchType.NO_SEARCH,
mContainerActivity.getStorageManager(),
mFile,
true);
setFabVisible(false);
@@ -1530,7 +1533,9 @@ public class OCFileListFragment extends ExtendedListFragment implements
final User currentUser = accountManager.getUser();
final RemoteOperation remoteOperation;
if (currentSearchType != SearchType.SHARED_FILTER) {
if (currentSearchType == SearchType.SHARED_FILTER) {
remoteOperation = new GetSharesRemoteOperation();
} else {
boolean searchOnlyFolders = false;
if (getArguments() != null && getArguments().getBoolean(ARG_SEARCH_ONLY_FOLDER, false)) {
searchOnlyFolders = true;
@@ -1538,8 +1543,6 @@ public class OCFileListFragment extends ExtendedListFragment implements
remoteOperation = new SearchRemoteOperation(event.getSearchQuery(), event.getSearchType(),
searchOnlyFolders);
} else {
remoteOperation = new GetSharesRemoteOperation();
}
remoteOperationAsyncTask = new AsyncTask<Void, Void, Boolean>() {
@@ -1560,11 +1563,21 @@ public class OCFileListFragment extends ExtendedListFragment implements
if (remoteOperationResult.getResultData() == null || ((List) remoteOperationResult.getResultData()).isEmpty()) {
setEmptyView(event);
} else {
mAdapter.setData(((RemoteOperationResult<List>) remoteOperationResult).getResultData(),
currentSearchType,
storageManager,
mFile,
true);
if (currentSearchType == SearchType.SHARED_FILTER) {
mAdapter.setData(((RemoteOperationResult<List<OCShare>>) remoteOperationResult).getResultData(),
new ArrayList<>(),
currentSearchType,
storageManager,
mFile,
true);
} else {
mAdapter.setData(new ArrayList<>(),
((RemoteOperationResult<List<RemoteFile>>) remoteOperationResult).getResultData(),
currentSearchType,
storageManager,
mFile,
true);
}
searchEvent = event;
}
@@ -1867,7 +1880,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
private void resetHeaderScrollingState() {
if (requireActivity() instanceof FileDisplayActivity) {
AppBarLayout appBarLayout = ((FileDisplayActivity) requireActivity()).findViewById(R.id.appbar);
AppBarLayout appBarLayout = requireActivity().findViewById(R.id.appbar);
if (appBarLayout != null) {
appBarLayout.setExpanded(true);
@@ -433,8 +433,8 @@ public class FileOperationsHelper {
fileActivity.showLoadingDialog(fileActivity.getString(R.string.wait_a_moment));
final User user = currentAccount.getUser();
new Thread(() -> {
StreamMediaFileOperation sfo = new StreamMediaFileOperation(file.getLocalId());
RemoteOperationResult result = sfo.execute(user.toPlatformAccount(), fileActivity);
RemoteOperationResult<String> result = new StreamMediaFileOperation(file.getLocalId())
.execute(user.toPlatformAccount(), fileActivity);
fileActivity.dismissLoadingDialog();
@@ -444,7 +444,7 @@ public class FileOperationsHelper {
}
Intent openFileWithIntent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse((String) result.getData().get(0));
Uri uri = Uri.parse(result.getResultData());
openFileWithIntent.setDataAndType(uri, file.getMimeType());
@@ -493,14 +493,13 @@ public class PreviewMediaFragment extends FileFragment implements OnTouchListene
return null;
}
StreamMediaFileOperation sfo = new StreamMediaFileOperation(fileId[0]);
RemoteOperationResult result = sfo.execute(client);
RemoteOperationResult<String> result = new StreamMediaFileOperation(fileId[0]).execute(client);
if (!result.isSuccess()) {
return null;
}
return Uri.parse((String) result.getData().get(0));
return Uri.parse(result.getResultData());
}
@Override
@@ -141,11 +141,12 @@ public class PreviewTextStringFragment extends PreviewTextFragment {
private void edit() {
new Thread(() -> {
RemoteOperationResult result = new RichWorkspaceDirectEditingRemoteOperation(getFile().getRemotePath())
.execute(accountManager.getUser().toPlatformAccount(), getContext());
RemoteOperationResult<String> result =
new RichWorkspaceDirectEditingRemoteOperation(getFile().getRemotePath())
.execute(accountManager.getUser().toPlatformAccount(), getContext());
if (result.isSuccess()) {
String url = (String) result.getSingleData();
String url = result.getResultData();
containerActivity.getFileOperationsHelper().openRichWorkspaceWithTextEditor(getFile(),
url,
getContext());
@@ -57,10 +57,10 @@ public class RemoteTrashbinRepository implements TrashbinRepository {
private static class RemoveTrashbinFileTask extends AsyncTask<Void, Void, Boolean> {
private User user;
private ClientFactory clientFactory;
private TrashbinFile file;
private OperationCallback callback;
private final User user;
private final ClientFactory clientFactory;
private final TrashbinFile file;
private final OperationCallback callback;
private RemoveTrashbinFileTask(User user,
ClientFactory clientFactory,
@@ -99,9 +99,9 @@ public class RemoteTrashbinRepository implements TrashbinRepository {
private static class EmptyTrashbinTask extends AsyncTask<Void, Void, Boolean> {
private User user;
private ClientFactory clientFactory;
private OperationCallback callback;
private final User user;
private final ClientFactory clientFactory;
private final OperationCallback callback;
private EmptyTrashbinTask(User user, ClientFactory clientFactory, OperationCallback callback) {
this.user = user;
@@ -137,10 +137,10 @@ public class RemoteTrashbinRepository implements TrashbinRepository {
private static class RestoreTrashbinFileTask extends AsyncTask<Void, Void, Boolean> {
private TrashbinFile file;
private User user;
private ClientFactory clientFactory;
private TrashbinRepository.OperationCallback callback;
private final TrashbinFile file;
private final User user;
private final ClientFactory clientFactory;
private final TrashbinRepository.OperationCallback callback;
private RestoreTrashbinFileTask(TrashbinFile file, User user, ClientFactory clientFactory,
TrashbinRepository.OperationCallback callback) {
@@ -179,11 +179,11 @@ public class RemoteTrashbinRepository implements TrashbinRepository {
private static class ReadRemoteTrashbinFolderTask extends AsyncTask<Void, Void, Boolean> {
private String remotePath;
private User user;
private ClientFactory clientFactory;
private List<Object> trashbinFiles;
private LoadFolderCallback callback;
private final String remotePath;
private final User user;
private final ClientFactory clientFactory;
private List<TrashbinFile> trashbinFiles;
private final LoadFolderCallback callback;
private ReadRemoteTrashbinFolderTask(String remotePath, User user, ClientFactory clientFactory,
LoadFolderCallback callback) {
@@ -197,9 +197,10 @@ public class RemoteTrashbinRepository implements TrashbinRepository {
protected Boolean doInBackground(Void... voids) {
try {
OwnCloudClient client = clientFactory.create(user);
RemoteOperationResult result = new ReadTrashbinFolderRemoteOperation(remotePath).execute(client);
RemoteOperationResult<List<TrashbinFile>> result =
new ReadTrashbinFolderRemoteOperation(remotePath).execute(client);
if (result.isSuccess()) {
trashbinFiles = result.getData();
trashbinFiles = result.getResultData();
return Boolean.TRUE;
} else {
return Boolean.FALSE;
@@ -248,7 +248,7 @@ public class TrashbinActivity extends DrawerActivity implements
}
@Override
public void showTrashbinFolder(List<Object> trashbinFiles) {
public void showTrashbinFolder(List<TrashbinFile> trashbinFiles) {
if (active) {
trashbinListAdapter.setTrashbinFiles(trashbinFiles, true);
binding.swipeContainingList.setRefreshing(false);
@@ -30,7 +30,7 @@ import java.util.List;
public interface TrashbinContract {
interface View {
void showTrashbinFolder(List<Object> trashbinFiles);
void showTrashbinFolder(List<TrashbinFile> trashbinFiles);
void showSnackbarError(int message, TrashbinFile file);
@@ -70,7 +70,7 @@ public class TrashbinPresenter implements TrashbinContract.Presenter {
public void loadFolder() {
trashbinRepository.getFolder(currentPath, new TrashbinRepository.LoadFolderCallback() {
@Override
public void onSuccess(List<Object> files) {
public void onSuccess(List<TrashbinFile> files) {
trashbinView.showTrashbinFolder(files);
}
@@ -29,7 +29,7 @@ import java.util.List;
*/
public interface TrashbinRepository {
interface LoadFolderCallback {
void onSuccess(List<Object> files);
void onSuccess(List<TrashbinFile> files);
void onError(int error);
}
@@ -98,7 +98,7 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
* Utils for encryption
*/
public final class EncryptionUtils {
private static String TAG = EncryptionUtils.class.getSimpleName();
private static final String TAG = EncryptionUtils.class.getSimpleName();
public static final String PUBLIC_KEY = "PUBLIC_KEY";
public static final String PRIVATE_KEY = "PRIVATE_KEY";
@@ -224,7 +224,7 @@ public final class EncryptionUtils {
public static @Nullable
DecryptedFolderMetadata downloadFolderMetadata(OCFile folder, OwnCloudClient client,
Context context, Account account) {
RemoteOperationResult getMetadataOperationResult = new GetMetadataRemoteOperation(folder.getLocalId())
RemoteOperationResult<String> getMetadataOperationResult = new GetMetadataRemoteOperation(folder.getLocalId())
.execute(client);
if (!getMetadataOperationResult.isSuccess()) {
@@ -233,7 +233,7 @@ public final class EncryptionUtils {
// decrypt metadata
ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
String serializedEncryptedMetadata = (String) getMetadataOperationResult.getData().get(0);
String serializedEncryptedMetadata = getMetadataOperationResult.getResultData();
String privateKey = arbitraryDataProvider.getValue(account.name, EncryptionUtils.PRIVATE_KEY);
EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.deserializeJSON(
@@ -795,12 +795,12 @@ public final class EncryptionUtils {
public static String lockFolder(OCFile parentFile, OwnCloudClient client) throws UploadException {
// Lock folder
LockFileRemoteOperation lockFileOperation = new LockFileRemoteOperation(parentFile.getLocalId());
RemoteOperationResult lockFileOperationResult = lockFileOperation.execute(client);
RemoteOperationResult<String> lockFileOperationResult = new LockFileRemoteOperation(parentFile.getLocalId())
.execute(client);
if (lockFileOperationResult.isSuccess() &&
!TextUtils.isEmpty((String) lockFileOperationResult.getData().get(0))) {
return (String) lockFileOperationResult.getData().get(0);
!TextUtils.isEmpty(lockFileOperationResult.getResultData())) {
return lockFileOperationResult.getResultData();
} else if (lockFileOperationResult.getHttpCode() == HttpStatus.SC_FORBIDDEN) {
throw new UploadException("Forbidden! Please try again later.)");
} else {
@@ -818,14 +818,14 @@ public final class EncryptionUtils {
String publicKey) throws UploadException,
InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, BadPaddingException,
IllegalBlockSizeException, InvalidKeyException, InvalidKeySpecException, CertificateException {
GetMetadataRemoteOperation getMetadataOperation = new GetMetadataRemoteOperation(parentFile.getLocalId());
RemoteOperationResult getMetadataOperationResult = getMetadataOperation.execute(client);
RemoteOperationResult<String> getMetadataOperationResult = new GetMetadataRemoteOperation(
parentFile.getLocalId()).execute(client);
DecryptedFolderMetadata metadata;
if (getMetadataOperationResult.isSuccess()) {
// decrypt metadata
String serializedEncryptedMetadata = (String) getMetadataOperationResult.getData().get(0);
String serializedEncryptedMetadata = getMetadataOperationResult.getResultData();
EncryptedFolderMetadata encryptedFolderMetadata = EncryptionUtils.deserializeJSON(
@@ -855,7 +855,7 @@ public final class EncryptionUtils {
String token,
OwnCloudClient client,
boolean metadataExists) throws UploadException {
RemoteOperationResult uploadMetadataOperationResult;
RemoteOperationResult<String> uploadMetadataOperationResult;
if (metadataExists) {
// update metadata
UpdateMetadataRemoteOperation storeMetadataOperation = new UpdateMetadataRemoteOperation(
@@ -873,11 +873,11 @@ public final class EncryptionUtils {
}
}
public static RemoteOperationResult unlockFolder(OCFile parentFolder, OwnCloudClient client, String token) {
public static RemoteOperationResult<Void> unlockFolder(OCFile parentFolder, OwnCloudClient client, String token) {
if (token != null) {
return new UnlockFileRemoteOperation(parentFolder.getLocalId(), token).execute(client);
} else {
return new RemoteOperationResult(new Exception("No token available"));
return new RemoteOperationResult<>(new Exception("No token available"));
}
}
}
@@ -19,6 +19,7 @@
package com.owncloud.android.ui.activities.data.activities;
import com.nextcloud.common.NextcloudClient;
import com.owncloud.android.lib.resources.activities.model.Activity;
import org.junit.Before;
import org.junit.Test;
@@ -49,7 +50,7 @@ public class RemoteActivitiesRepositoryTest {
private ActivitiesRepository mActivitiesRepository;
private List<Object> activitiesList;
private List<Activity> activitiesList;
@Before
public void setUpActivitiesRepository() {