Quellcode durchsuchen

Merge pull request #2669 from nextcloud/codacy

Codacy fixes
Andy Scherzinger vor 7 Jahren
Ursprung
Commit
258aae1c8d

+ 37 - 34
src/main/java/com/owncloud/android/authentication/AuthenticatorActivity.java

@@ -168,7 +168,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     private static final String AUTH_OPTIONAL = "optional";
 
     public static final byte ACTION_CREATE = 0;
-    public static final byte ACTION_UPDATE_TOKEN = 1;               // requested by the user
     public static final byte ACTION_UPDATE_EXPIRED_TOKEN = 2;       // detected by the app
 
     private static final String UNTRUSTED_CERT_DIALOG_TAG = "UNTRUSTED_CERT_DIALOG";
@@ -195,7 +194,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     private Account mAccount;
     private String mAuthTokenType;
 
-
     /// activity-level references / state
     private final Handler mHandler = new Handler();
     private ServiceConnection mOperationsServiceConnection = null;
@@ -203,7 +201,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
     private AccountManager mAccountMgr;
     private Uri mNewCapturedUriFromOAuth2Redirection;
 
-
     /// Server PRE-Fragment elements 
     private CustomEditText mHostUrlInput;
     private View mRefreshButton;
@@ -218,7 +215,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
     private GetServerInfoOperation.ServerInfo mServerInfo = new GetServerInfoOperation.ServerInfo();
 
-
     /// Authentication PRE-Fragment elements 
     private CheckBox mOAuth2Check;
     private TextView mOAuthAuthEndpointText;
@@ -274,7 +270,6 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         //getWindow().requestFeature(Window.FEATURE_NO_TITLE);
         if (getSupportActionBar() != null) {
             getSupportActionBar().hide();
-
             getSupportActionBar().setDisplayHomeAsUpEnabled(false);
             getSupportActionBar().setDisplayShowHomeEnabled(false);
             getSupportActionBar().setDisplayShowTitleEnabled(false);
@@ -590,31 +585,23 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         mOkButton = findViewById(R.id.buttonOK);
         mOkButton.setOnClickListener(v -> onOkClick());
 
-        /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)
-        boolean isWelcomeLinkVisible = getResources().getBoolean(R.bool.show_welcome_link);
-
-        String instructionsMessageText = null;
-        if (mAction == ACTION_UPDATE_EXPIRED_TOKEN) {
-            if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType(this)).equals(mAuthTokenType)) {
-                instructionsMessageText = getString(R.string.auth_expired_oauth_token_toast);
+        setupWelcomeLink();
+        setupInstructionMessage();
 
-            } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType(this))
-                    .equals(mAuthTokenType)) {
-                instructionsMessageText = getString(R.string.auth_expired_saml_sso_token_toast);
-
-            } else {
-                instructionsMessageText = getString(R.string.auth_expired_basic_auth_toast);
-            }
-        }
+        mTestServerButton.setVisibility(mAction == ACTION_CREATE ? View.VISIBLE : View.GONE);
+    }
 
-        /// step 2 - set properties of UI elements (text, visibility, enabled...)
+    private void setupWelcomeLink() {
         Button welcomeLink = findViewById(R.id.welcome_link);
-        welcomeLink.setVisibility(mAction == ACTION_CREATE && isWelcomeLinkVisible ? View.VISIBLE : View.GONE);
+        welcomeLink.setVisibility(mAction == ACTION_CREATE &&
+                getResources().getBoolean(R.bool.show_welcome_link) ? View.VISIBLE : View.GONE);
         welcomeLink.setText(getString(R.string.auth_register));
+    }
 
-        mTestServerButton.setVisibility(mAction == ACTION_CREATE ? View.VISIBLE : View.GONE);
-
+    private void setupInstructionMessage() {
+        String instructionsMessageText = calculateInstructionMessageText(mAction, mAuthTokenType);
         TextView instructionsView = findViewById(R.id.instructions_message);
+
         if (instructionsMessageText != null) {
             instructionsView.setVisibility(View.VISIBLE);
             instructionsView.setText(instructionsMessageText);
@@ -623,6 +610,24 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
         }
     }
 
+    @Nullable
+    private String calculateInstructionMessageText(byte action, String authTokenType) {
+        if (action == ACTION_UPDATE_EXPIRED_TOKEN) {
+            if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType(this)).equals(authTokenType)) {
+                return getString(R.string.auth_expired_oauth_token_toast);
+
+            } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType(this))
+                    .equals(authTokenType)) {
+                return getString(R.string.auth_expired_saml_sso_token_toast);
+
+            } else {
+                return getString(R.string.auth_expired_basic_auth_toast);
+            }
+        }
+
+        return null;
+    }
+
     public void onTestServerConnectionClick(View v) {
         checkOcServer();
     }
@@ -1425,18 +1430,14 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
                 checkBasicAuthorization(webViewUser, webViewPassword);
             } else if (webViewLoginMethod) {
                 // hide old login
-                mOkButton.setVisibility(View.GONE);
-                mUsernameInputLayout.setVisibility(View.GONE);
-                mPasswordInputLayout.setVisibility(View.GONE);
+                setOldLoginVisibility(View.GONE);
 
                 setContentView(R.layout.account_setup_webview);
                 mLoginWebView = findViewById(R.id.login_webview);
                 initWebViewLogin(mServerInfo.mBaseUrl);
             } else {
                 // show old login
-                mOkButton.setVisibility(View.VISIBLE);
-                mUsernameInputLayout.setVisibility(View.VISIBLE);
-                mPasswordInputLayout.setVisibility(View.VISIBLE);
+                setOldLoginVisibility(View.VISIBLE);
             }
 
             if (!authSupported(mServerInfo.mAuthMethod)) {
@@ -1464,18 +1465,20 @@ public class AuthenticatorActivity extends AccountAuthenticatorActivity
 
         if (!mServerIsValid) {
             // hide old login
-            mOkButton.setVisibility(View.GONE);
-            mUsernameInputLayout.setVisibility(View.GONE);
-            mPasswordInputLayout.setVisibility(View.GONE);
+            setOldLoginVisibility(View.GONE);
         }
 
-
         /// very special case (TODO: move to a common place for all the remote operations)
         if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {
             showUntrustedCertDialog(result);
         }
     }
 
+    private void setOldLoginVisibility(int visible) {
+        mOkButton.setVisibility(visible);
+        mUsernameInputLayout.setVisibility(visible);
+        mPasswordInputLayout.setVisibility(visible);
+    }
 
     private boolean authSupported(AuthenticationMethod authMethod) {
         return ((basicTokenType.equals(mAuthTokenType) &&

+ 18 - 14
src/main/java/com/owncloud/android/files/services/FileDownloader.java

@@ -95,7 +95,7 @@ public class FileDownloader extends Service
     private Account mCurrentAccount = null;
     private FileDataStorageManager mStorageManager;
 
-    private IndexedForest<DownloadFileOperation> mPendingDownloads = new IndexedForest<DownloadFileOperation>();
+    private IndexedForest<DownloadFileOperation> mPendingDownloads = new IndexedForest<>();
 
     private DownloadFileOperation mCurrentDownload = null;
 
@@ -597,6 +597,7 @@ public class FileDownloader extends Service
         if (mNotificationManager != null) {
             mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);
         }
+
         if (!downloadResult.isCancelled()) {
             int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker :
                     R.string.downloader_download_failed_ticker;
@@ -613,20 +614,8 @@ public class FileDownloader extends Service
                     .setProgress(0, 0, false);
 
             if (needsToUpdateCredentials) {
+                configureUpdateCredentialsNotification(download.getAccount());
 
-                // let the user update credentials with one click
-                Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
-                updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT,
-                        download.getAccount());
-                updateAccountCredentials.putExtra(
-                        AuthenticatorActivity.EXTRA_ACTION,
-                        AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
-                );
-                updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
-                updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
-                updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
-                mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
-                        updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
             } else {
                 // TODO put something smart in showDetailsIntent
                 Intent showDetailsIntent = new Intent();
@@ -650,6 +639,21 @@ public class FileDownloader extends Service
         }
     }
 
+    private void configureUpdateCredentialsNotification(Account account) {
+        // let the user update credentials with one click
+        Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
+        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
+        updateAccountCredentials.putExtra(
+                AuthenticatorActivity.EXTRA_ACTION,
+                AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN
+        );
+        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
+        updateAccountCredentials.addFlags(Intent.FLAG_FROM_BACKGROUND);
+        mNotificationBuilder.setContentIntent(PendingIntent.getActivity(this, (int) System.currentTimeMillis(),
+                updateAccountCredentials, PendingIntent.FLAG_ONE_SHOT));
+    }
+
 
     /**
      * Sends a broadcast when a download finishes in order to the interested activities can

+ 3 - 7
src/main/java/com/owncloud/android/files/services/FileUploader.java

@@ -66,7 +66,6 @@ import com.owncloud.android.lib.common.operations.RemoteOperationResult;
 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
 import com.owncloud.android.lib.common.utils.Log_OC;
 import com.owncloud.android.lib.resources.files.FileUtils;
-import com.owncloud.android.lib.resources.status.OwnCloudVersion;
 import com.owncloud.android.operations.UploadFileOperation;
 import com.owncloud.android.ui.activity.FileActivity;
 import com.owncloud.android.ui.activity.UploadListActivity;
@@ -533,9 +532,6 @@ public class FileUploader extends Service
             return Service.START_NOT_STICKY;
         }
 
-        boolean retry = intent.getBooleanExtra(KEY_RETRY, false);
-        AbstractList<String> requestedUploads = new Vector<String>();
-
         if (!intent.hasExtra(KEY_ACCOUNT)) {
             Log_OC.e(TAG, "Not enough information provided in intent");
             return Service.START_NOT_STICKY;
@@ -545,10 +541,11 @@ public class FileUploader extends Service
         if (!AccountUtils.exists(account, getApplicationContext())) {
             return Service.START_NOT_STICKY;
         }
-        OwnCloudVersion ocv = AccountUtils.getServerVersion(account);
 
-        boolean chunked = ocv.isChunkedUploadSupported();
+        boolean retry = intent.getBooleanExtra(KEY_RETRY, false);
+        AbstractList<String> requestedUploads = new Vector<>();
 
+        boolean chunked = AccountUtils.getServerVersion(account).isChunkedUploadSupported();
         boolean onWifiOnly = intent.getBooleanExtra(KEY_WHILE_ON_WIFI_ONLY, false);
         boolean whileChargingOnly = intent.getBooleanExtra(KEY_WHILE_CHARGING_ONLY, false);
 
@@ -629,7 +626,6 @@ public class FileUploader extends Service
                     ocUpload.setLocalAction(localAction);
                     ocUpload.setUseWifiOnly(onWifiOnly);
                     ocUpload.setWhileChargingOnly(whileChargingOnly);
-
                     ocUpload.setUploadStatus(UploadStatus.UPLOAD_IN_PROGRESS);
 
 

+ 50 - 46
src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java

@@ -32,6 +32,7 @@ import android.content.pm.PackageManager;
 import android.content.pm.ResolveInfo;
 import android.net.Uri;
 import android.os.Build;
+import android.support.annotation.NonNull;
 import android.support.annotation.Nullable;
 import android.support.design.widget.Snackbar;
 import android.support.v4.app.FragmentManager;
@@ -239,56 +240,12 @@ public class FileOperationsHelper {
 
     public void openFile(OCFile file) {
         if (file != null) {
-            String storagePath = file.getStoragePath();
-
-            String[] officeExtensions = MainApp.getAppContext().getResources().getStringArray(R.array
-                    .ms_office_extensions);
-
-            Uri fileUri;
-
-            if (file.getFileName().contains(".") &&
-                    Arrays.asList(officeExtensions).contains(file.getFileName().substring(file.getFileName().
-                            lastIndexOf(".") + 1, file.getFileName().length())) &&
-                    !file.getStoragePath().startsWith(MainApp.getAppContext().getFilesDir().getAbsolutePath())) {
-                fileUri = file.getLegacyExposedFileUri(mFileActivity);
-            } else {
-                fileUri = file.getExposedFileUri(mFileActivity);
-            }
-
-            Intent openFileWithIntent = null;
-            int lastIndexOfDot = storagePath.lastIndexOf('.');
-            if (lastIndexOfDot >= 0) {
-                String fileExt = storagePath.substring(lastIndexOfDot + 1);
-                String guessedMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExt);
-                if (guessedMimeType != null) {
-                    openFileWithIntent = new Intent(Intent.ACTION_VIEW);
-                    openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
-                    openFileWithIntent.setDataAndType(
-                            fileUri,
-                            guessedMimeType
-                    );
-                }
-            }
-
-            if (openFileWithIntent == null) {
-                openFileWithIntent = createIntentFromFile(storagePath);
-            }
-
-            if (openFileWithIntent == null) {
-                openFileWithIntent = new Intent(Intent.ACTION_VIEW);
-                openFileWithIntent.setDataAndType(
-                        fileUri,
-                        file.getMimetype()
-                );
-            }
-
-            openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+            final Intent openFileWithIntent = createOpenFileIntent(file);
 
             List<ResolveInfo> launchables = mFileActivity.getPackageManager().
                     queryIntentActivities(openFileWithIntent, PackageManager.GET_RESOLVED_FILTER);
 
             mFileActivity.showLoadingDialog(mFileActivity.getResources().getString(R.string.sync_in_progress));
-            Intent finalOpenFileWithIntent = openFileWithIntent;
             new Thread(new Runnable() {
                 @Override
                 public void run() {
@@ -324,7 +281,7 @@ public class FileOperationsHelper {
 
                                 mFileActivity.startActivity(
                                         Intent.createChooser(
-                                                finalOpenFileWithIntent,
+                                                openFileWithIntent,
                                                 mFileActivity.getString(R.string.actionbar_open_with)
                                         )
                                 );
@@ -344,6 +301,53 @@ public class FileOperationsHelper {
         }
     }
 
+    @NonNull
+    private Intent createOpenFileIntent(OCFile file) {
+        String storagePath = file.getStoragePath();
+        Uri fileUri = getFileUri(file, MainApp.getAppContext().getResources().getStringArray(R.array
+                .ms_office_extensions));
+        Intent openFileWithIntent = null;
+        int lastIndexOfDot = storagePath.lastIndexOf('.');
+        if (lastIndexOfDot >= 0) {
+            String fileExt = storagePath.substring(lastIndexOfDot + 1);
+            String guessedMimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExt);
+            if (guessedMimeType != null) {
+                openFileWithIntent = new Intent(Intent.ACTION_VIEW);
+                openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+                openFileWithIntent.setDataAndType(
+                        fileUri,
+                        guessedMimeType
+                );
+            }
+        }
+
+        if (openFileWithIntent == null) {
+            openFileWithIntent = createIntentFromFile(storagePath);
+        }
+
+        if (openFileWithIntent == null) {
+            openFileWithIntent = new Intent(Intent.ACTION_VIEW);
+            openFileWithIntent.setDataAndType(
+                    fileUri,
+                    file.getMimetype()
+            );
+        }
+
+        openFileWithIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
+        return openFileWithIntent;
+    }
+
+    private Uri getFileUri(OCFile file, String[] officeExtensions) {
+        if (file.getFileName().contains(".") &&
+                Arrays.asList(officeExtensions).contains(file.getFileName().substring(file.getFileName().
+                        lastIndexOf(".") + 1, file.getFileName().length())) &&
+                !file.getStoragePath().startsWith(MainApp.getAppContext().getFilesDir().getAbsolutePath())) {
+            return file.getLegacyExposedFileUri(mFileActivity);
+        } else {
+            return file.getExposedFileUri(mFileActivity);
+        }
+    }
+
     /**
      * Helper method to share a file via a public link. Starts a request to do it in {@link OperationsService}
      *

+ 0 - 4
src/main/java/com/owncloud/android/utils/FileSortOrderByDate.java

@@ -24,15 +24,11 @@ import com.owncloud.android.datamodel.OCFile;
 
 import java.io.File;
 import java.util.Collections;
-import java.util.Comparator;
 import java.util.List;
 
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-
 /**
  * Created by srkunze on 28.08.17.
  */
-
 public class FileSortOrderByDate extends FileSortOrder {
 
     FileSortOrderByDate(String name, boolean ascending) {

+ 0 - 1
src/main/java/com/owncloud/android/utils/FileSortOrderByName.java

@@ -24,7 +24,6 @@ import com.owncloud.android.datamodel.OCFile;
 
 import java.io.File;
 import java.util.Collections;
-import java.util.Comparator;
 import java.util.List;
 import java.util.Locale;
 

+ 0 - 3
src/main/java/com/owncloud/android/utils/FileSortOrderBySize.java

@@ -24,15 +24,12 @@ import com.owncloud.android.datamodel.OCFile;
 
 import java.io.File;
 import java.util.Collections;
-import java.util.Comparator;
 import java.util.List;
 
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 
 /**
  * Sorts files by sizes
  */
-
 public class FileSortOrderBySize extends FileSortOrder {
 
     FileSortOrderBySize(String name, boolean ascending) {