Add actionBar
[pub/Android/ownCloud.git] / src / com / owncloud / android / authentication / AuthenticatorActivity.java
index 21aab72..3ab7690 100644 (file)
@@ -1,6 +1,11 @@
-/* ownCloud Android client application\r
+/**\r
+ *   ownCloud Android client application\r
+ *\r
+ *   @author Bartek Przybylski\r
+ *   @author David A. Velasco\r
+ *   @author masensio\r
  *   Copyright (C) 2012  Bartek Przybylski\r
- *   Copyright (C) 2012-2014 ownCloud Inc.\r
+ *   Copyright (C) 2015 ownCloud Inc.\r
  *\r
  *   This program is free software: you can redistribute it and/or modify\r
  *   it under the terms of the GNU General Public License version 2,\r
@@ -37,6 +42,7 @@ import android.os.Bundle;
 import android.os.Handler;\r
 import android.os.IBinder;\r
 import android.preference.PreferenceManager;\r
+import android.support.v4.app.DialogFragment;\r
 import android.support.v4.app.Fragment;\r
 import android.support.v4.app.FragmentManager;\r
 import android.support.v4.app.FragmentTransaction;\r
@@ -60,18 +66,20 @@ import android.widget.TextView;
 import android.widget.TextView.OnEditorActionListener;\r
 import android.widget.Toast;\r
 \r
-import com.actionbarsherlock.app.SherlockDialogFragment;\r
 import com.owncloud.android.MainApp;\r
 import com.owncloud.android.R;\r
 import com.owncloud.android.authentication.SsoWebViewClient.SsoWebViewClientListener;\r
+import com.owncloud.android.lib.common.OwnCloudCredentials;\r
+import com.owncloud.android.lib.common.OwnCloudCredentialsFactory;\r
 import com.owncloud.android.lib.common.accounts.AccountTypeUtils;\r
+import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;\r
 import com.owncloud.android.lib.common.accounts.AccountUtils.Constants;\r
 import com.owncloud.android.lib.common.network.CertificateCombinedException;\r
 import com.owncloud.android.lib.common.operations.OnRemoteOperationListener;\r
 import com.owncloud.android.lib.common.operations.RemoteOperation;\r
 import com.owncloud.android.lib.common.operations.RemoteOperationResult;\r
 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;\r
-import com.owncloud.android.lib.resources.files.ExistenceCheckRemoteOperation;\r
+import com.owncloud.android.lib.common.utils.Log_OC;\r
 import com.owncloud.android.lib.resources.status.OwnCloudVersion;\r
 import com.owncloud.android.lib.resources.users.GetRemoteUserNameOperation;\r
 import com.owncloud.android.operations.DetectAuthenticationMethodOperation.AuthenticationMethod;\r
@@ -84,18 +92,15 @@ import com.owncloud.android.ui.dialog.IndeterminateProgressDialog;
 import com.owncloud.android.ui.dialog.SamlWebViewDialog;\r
 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;\r
 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;\r
-import com.owncloud.android.utils.Log_OC;\r
+import com.owncloud.android.utils.DisplayUtils;\r
 \r
 /**\r
  * This Activity is used to add an ownCloud account to the App\r
- * \r
- * @author Bartek Przybylski\r
- * @author David A. Velasco\r
- * @author masensio\r
  */\r
 public class AuthenticatorActivity extends AccountAuthenticatorActivity\r
-implements  OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener, \r
-SsoWebViewClientListener, OnSslUntrustedCertListener {\r
+        implements  OnRemoteOperationListener, OnFocusChangeListener, OnEditorActionListener,\r
+        SsoWebViewClientListener, OnSslUntrustedCertListener,\r
+        AuthenticatorAsyncTask.OnAuthenticatorTaskListener {\r
 \r
     private static final String TAG = AuthenticatorActivity.class.getSimpleName();\r
 \r
@@ -131,6 +136,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     private static final String CREDENTIALS_DIALOG_TAG = "CREDENTIALS_DIALOG";\r
     private static final String KEY_AUTH_IS_FIRST_ATTEMPT_TAG = "KEY_AUTH_IS_FIRST_ATTEMPT";\r
 \r
+    private static final String KEY_USERNAME = "USERNAME";\r
+    private static final String KEY_PASSWORD = "PASSWORD";\r
+    private static final String KEY_ASYNC_TASK_IN_PROGRESS = "AUTH_IN_PROGRESS";\r
     \r
     /// parameters from EXTRAs in starter Intent\r
     private byte mAction;\r
@@ -174,14 +182,21 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     private int mAuthStatusText = 0, mAuthStatusIcon = 0;\r
     \r
     private String mAuthToken = "";\r
+    private AuthenticatorAsyncTask mAsyncTask;\r
 \r
     private boolean mIsFirstAuthAttempt;\r
-\r
     \r
     /// Identifier of operation in progress which result shouldn't be lost \r
     private long mWaitingForOpId = Long.MAX_VALUE;\r
 \r
-    \r
+    private final String BASIC_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypePass(\r
+            MainApp.getAccountType());\r
+    private final String OAUTH_TOKEN_TYPE = AccountTypeUtils.getAuthTokenTypeAccessToken(\r
+            MainApp.getAccountType());\r
+    private final String SAML_TOKEN_TYPE =\r
+            AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());\r
+\r
+\r
     /**\r
      * {@inheritDoc}\r
      * \r
@@ -226,7 +241,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         setContentView(R.layout.account_setup);\r
         \r
         /// initialize general UI elements\r
-        initOverallUi(savedInstanceState);\r
+        initOverallUi();\r
         \r
         mOkButton = findViewById(R.id.buttonOK);\r
 \r
@@ -246,13 +261,17 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             if (mAccount != null) {\r
                 boolean oAuthRequired = \r
                     (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2) != null);\r
-                boolean samlWebSsoRequired = \r
-                    (mAccountMgr.getUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null);\r
+                boolean samlWebSsoRequired = ( \r
+                    mAccountMgr.getUserData(\r
+                        mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO\r
+                    ) != null\r
+                );\r
                 mAuthTokenType = chooseAuthTokenType(oAuthRequired, samlWebSsoRequired);\r
                 \r
             } else {\r
                 boolean oAuthSupported = AUTH_ON.equals(getString(R.string.auth_method_oauth2));\r
-                boolean samlWebSsoSupported = AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));\r
+                boolean samlWebSsoSupported = \r
+                        AUTH_ON.equals(getString(R.string.auth_method_saml_web_sso));\r
                 mAuthTokenType = chooseAuthTokenType(oAuthSupported, samlWebSsoSupported);\r
             }\r
         }\r
@@ -260,21 +279,19 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
     private String chooseAuthTokenType(boolean oauth, boolean saml) {\r
         if (saml) {\r
-            return AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());\r
+            return SAML_TOKEN_TYPE;\r
         } else if (oauth) {\r
-             return AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());\r
+             return OAUTH_TOKEN_TYPE;\r
         } else {\r
-            return AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());\r
+            return BASIC_TOKEN_TYPE;\r
         }\r
     }\r
 \r
     \r
     /**\r
      * Configures elements in the user interface under direct control of the Activity.\r
-     * \r
-     * @param savedInstanceState        Saved activity state, as in {{@link #onCreate(Bundle)}\r
      */\r
-    private void initOverallUi(Bundle savedInstanceState) {\r
+    private void initOverallUi() {\r
         \r
         /// step 1 - load and process relevant inputs (resources, intent, savedInstanceState)\r
         boolean isWelcomeLinkVisible = getResources().getBoolean(R.bool.show_welcome_link);\r
@@ -321,7 +338,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         if (savedInstanceState == null) {\r
             if (mAccount != null) {\r
                 mServerInfo.mBaseUrl = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);\r
-                mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");   // TODO do this in a setter for mBaseUrl\r
+                // TODO do next in a setter for mBaseUrl\r
+                mServerInfo.mIsSslConn = mServerInfo.mBaseUrl.startsWith("https://");   \r
                 String ocVersion = mAccountMgr.getUserData(mAccount, Constants.KEY_OC_VERSION);\r
                 if (ocVersion != null) {\r
                     mServerInfo.mVersion = new OwnCloudVersion(ocVersion);\r
@@ -351,7 +369,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         \r
         /// step 2 - set properties of UI elements (text, visibility, enabled...)\r
         mHostUrlInput = (EditText) findViewById(R.id.hostUrlInput);\r
-        mHostUrlInput.setText(mServerInfo.mBaseUrl);\r
+        // Convert IDN to Unicode\r
+        mHostUrlInput.setText(DisplayUtils.convertIdn(mServerInfo.mBaseUrl, false));\r
         if (mAction != ACTION_CREATE) {\r
             /// lock things that should not change\r
             mHostUrlInput.setEnabled(false);\r
@@ -363,7 +382,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             findViewById(R.id.hostUrlFrame).setVisibility(View.GONE);\r
             mRefreshButton = findViewById(R.id.centeredRefreshButton);\r
         }\r
-        showRefreshButton(mServerIsChecked && !mServerIsValid && \r
+        showRefreshButton(mServerIsChecked && !mServerIsValid &&\r
                 mWaitingForOpId > Integer.MAX_VALUE);\r
         mServerStatusView = (TextView) findViewById(R.id.server_status_text);\r
         showServerStatus();\r
@@ -405,8 +424,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             @Override\r
             public boolean onTouch(View view, MotionEvent event) {\r
                 if (event.getAction() == MotionEvent.ACTION_DOWN) {\r
-                    if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&\r
-                            mHostUrlInput.hasFocus()) {\r
+                    if (\r
+                            AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(\r
+                                    MainApp.getAccountType()\r
+                            ).equals(mAuthTokenType) &&\r
+                                    mHostUrlInput.hasFocus()\r
+                            ) {\r
                         checkOcServer();\r
                     }\r
                 }\r
@@ -534,10 +557,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     /**\r
      * Saves relevant state before {@link #onPause()}\r
      * \r
-     * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, intended to defer the \r
-     * processing of the redirection caught in {@link #onNewIntent(Intent)} until {@link #onResume()} \r
+     * Do NOT save {@link #mNewCapturedUriFromOAuth2Redirection}; it keeps a temporal flag, \r
+     * intended to defer the processing of the redirection caught in \r
+     * {@link #onNewIntent(Intent)} until {@link #onResume()} \r
      * \r
-     * See {@link #loadSavedInstanceState(Bundle)}\r
+     * See {@link #onSaveInstanceState(Bundle)}\r
      */\r
     @Override\r
     protected void onSaveInstanceState(Bundle outState) {\r
@@ -569,16 +593,49 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         /// authentication\r
         outState.putBoolean(KEY_AUTH_IS_FIRST_ATTEMPT_TAG, mIsFirstAuthAttempt);\r
 \r
+        /// AsyncTask (User and password)\r
+        outState.putString(KEY_USERNAME, mUsernameInput.getText().toString());\r
+        outState.putString(KEY_PASSWORD, mPasswordInput.getText().toString());\r
+\r
+        if (mAsyncTask != null) {\r
+            mAsyncTask.cancel(true);\r
+            outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, true);\r
+        } else {\r
+            outState.putBoolean(KEY_ASYNC_TASK_IN_PROGRESS, false);\r
+        }\r
+        mAsyncTask = null;\r
+\r
         //Log_OC.wtf(TAG, "onSaveInstanceState end" );\r
     }\r
 \r
+    @Override\r
+    public void onRestoreInstanceState(Bundle savedInstanceState) {\r
+        super.onRestoreInstanceState(savedInstanceState);\r
+\r
+        // AsyncTask\r
+        boolean inProgress = savedInstanceState.getBoolean(KEY_ASYNC_TASK_IN_PROGRESS);\r
+        if (inProgress){\r
+            String username = savedInstanceState.getString(KEY_USERNAME);\r
+            String password = savedInstanceState.getString(KEY_PASSWORD);\r
+\r
+            OwnCloudCredentials credentials = null;\r
+            if (BASIC_TOKEN_TYPE.equals(mAuthTokenType)) {\r
+                credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);\r
+\r
+            } else if (OAUTH_TOKEN_TYPE.equals(mAuthTokenType)) {\r
+                credentials = OwnCloudCredentialsFactory.newBearerCredentials(mAuthToken);\r
+\r
+            }\r
+            accessRootFolder(credentials);\r
+        }\r
+    }\r
 \r
     /**\r
-     * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION request\r
-     * is caught here.\r
+     * The redirection triggered by the OAuth authentication server as response to the \r
+     * GET AUTHORIZATION request is caught here.\r
      * \r
-     * To make this possible, this activity needs to be qualified with android:launchMode = "singleTask" in the\r
-     * AndroidManifest.xml file.\r
+     * To make this possible, this activity needs to be qualified with android:launchMode = \r
+     * "singleTask" in the AndroidManifest.xml file.\r
      */\r
     @Override\r
     protected void onNewIntent (Intent intent) {\r
@@ -591,12 +648,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
 \r
     /**\r
-     * The redirection triggered by the OAuth authentication server as response to the GET AUTHORIZATION, and \r
-     * deferred in {@link #onNewIntent(Intent)}, is processed here.\r
+     * The redirection triggered by the OAuth authentication server as response to the \r
+     * GET AUTHORIZATION, and deferred in {@link #onNewIntent(Intent)}, is processed here.\r
      */\r
     @Override\r
     protected void onResume() {\r
-        //Log_OC.wtf(TAG, "onResume init" );\r
         super.onResume();\r
         \r
         // bound here to avoid spurious changes triggered by Android on device rotations\r
@@ -611,15 +667,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             doOnResumeAndBound();\r
         }\r
         \r
-        //Log_OC.wtf(TAG, "onResume end" );\r
     }\r
 \r
     \r
     @Override\r
     protected void onPause() {\r
-        //Log_OC.wtf(TAG, "onPause init" );\r
         if (mOperationsServiceBinder != null) {\r
-            //Log_OC.wtf(TAG, "unregistering to listen for operation callbacks" );\r
             mOperationsServiceBinder.removeOperationListener(this);\r
         }\r
         \r
@@ -627,7 +680,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         mHostUrlInput.setOnFocusChangeListener(null);\r
         \r
         super.onPause();\r
-        //Log_OC.wtf(TAG, "onPause end" );\r
     }\r
     \r
     @Override\r
@@ -671,7 +723,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         \r
         if (mOperationsServiceBinder != null) {\r
             //Log_OC.wtf(TAG, "getting access token..." );\r
-            mWaitingForOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);\r
+            mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);\r
         }\r
     }\r
 \r
@@ -683,14 +735,14 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     public void onFocusChange(View view, boolean hasFocus) {\r
         if (view.getId() == R.id.hostUrlInput) {   \r
             if (!hasFocus) {\r
-                onUrlInputFocusLost((TextView) view);\r
+                onUrlInputFocusLost();\r
             }\r
             else {\r
                 showRefreshButton(false);\r
             }\r
 \r
         } else if (view.getId() == R.id.account_password) {\r
-            onPasswordFocusChanged((TextView) view, hasFocus);\r
+            onPasswordFocusChanged(hasFocus);\r
         }\r
     }\r
 \r
@@ -703,10 +755,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * started. \r
      * \r
      * When hasFocus:    user 'comes back' to write again the server URL.\r
-     * \r
-     * @param hostInput     TextView with the URL input field receiving the change of focus.\r
      */\r
-    private void onUrlInputFocusLost(TextView hostInput) {\r
+    private void onUrlInputFocusLost() {\r
         if (!mServerInfo.mBaseUrl.equals(\r
                 normalizeUrl(mHostUrlInput.getText().toString(), mServerInfo.mIsSslConn))) {\r
             // check server again only if the user changed something in the field\r
@@ -725,17 +775,23 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         mOkButton.setEnabled(false);\r
         mServerInfo = new GetServerInfoOperation.ServerInfo();\r
         showRefreshButton(false);\r
-        \r
+\r
         if (uri.length() != 0) {\r
+            // Handle internationalized domain names\r
+            uri = DisplayUtils.convertIdn(uri, true);\r
+\r
             mServerStatusText = R.string.auth_testing_connection;\r
             mServerStatusIcon = R.drawable.progress_small;\r
             showServerStatus();\r
             \r
             Intent getServerInfoIntent = new Intent();\r
             getServerInfoIntent.setAction(OperationsService.ACTION_GET_SERVER_INFO);\r
-            getServerInfoIntent.putExtra(OperationsService.EXTRA_SERVER_URL, uri);\r
+            getServerInfoIntent.putExtra(\r
+                OperationsService.EXTRA_SERVER_URL, \r
+                normalizeUrlSuffix(uri)\r
+            );\r
             if (mOperationsServiceBinder != null) {\r
-                mWaitingForOpId = mOperationsServiceBinder.newOperation(getServerInfoIntent);\r
+                mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getServerInfoIntent);\r
             } else {\r
               Log_OC.wtf(TAG, "Server check tried with OperationService unbound!" );\r
             }\r
@@ -755,10 +811,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * \r
      * When (!hasFocus), the button is made invisible and the password is hidden.\r
      * \r
-     * @param passwordInput    TextView with the password input field receiving the change of focus.\r
      * @param hasFocus          'True' if focus is received, 'false' if is lost\r
      */\r
-    private void onPasswordFocusChanged(TextView passwordInput, boolean hasFocus) {\r
+    private void onPasswordFocusChanged(boolean hasFocus) {\r
         if (hasFocus) {\r
             showViewPasswordButton();\r
         } else {\r
@@ -777,7 +832,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     }\r
 \r
     private boolean isPasswordVisible() {\r
-        return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);\r
+        return ((mPasswordInput.getInputType() & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) == \r
+                InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);\r
     }\r
 \r
     private void hidePasswordButton() {\r
@@ -785,12 +841,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     }\r
 \r
     private void showPassword() {\r
-        mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);\r
+        mPasswordInput.setInputType(\r
+                InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD\r
+        );\r
         showViewPasswordButton();\r
     }\r
 \r
     private void hidePassword() {\r
-        mPasswordInput.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);\r
+        mPasswordInput.setInputType(\r
+                InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD\r
+        );\r
         showViewPasswordButton();\r
     }\r
 \r
@@ -818,13 +878,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             mServerStatusText = R.string.auth_wtf_reenter_URL;\r
             showServerStatus();\r
             mOkButton.setEnabled(false);\r
-            //Log_OC.wtf(TAG,  "The user was allowed to click 'connect' to an unchecked server!!");\r
             return;\r
         }\r
 \r
-        if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
+        if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).\r
+                equals(mAuthTokenType)) {\r
+            \r
             startOauthorization();\r
-        } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) { \r
+        } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+                equals(mAuthTokenType)) {\r
+            \r
             startSamlBasedFederatedSingleSignOnAuthorization();\r
         } else {\r
             checkBasicAuthorization();\r
@@ -847,25 +910,18 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
 \r
         /// validate credentials accessing the root folder\r
-        accessRootFolderRemoteOperation(username, password);\r
-        \r
+        OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBasicCredentials(username,\r
+                password);\r
+        accessRootFolder(credentials);\r
     }\r
 \r
-    private void accessRootFolderRemoteOperation(String username, String password) {\r
-        Intent existenceCheckIntent = new Intent();\r
-        existenceCheckIntent.setAction(OperationsService.ACTION_EXISTENCE_CHECK);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_SERVER_URL, mServerInfo.mBaseUrl);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_REMOTE_PATH, "/");\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_USERNAME, username);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_PASSWORD, password);\r
-        existenceCheckIntent.putExtra(OperationsService.EXTRA_AUTH_TOKEN, mAuthToken);\r
-        \r
-        if (mOperationsServiceBinder != null) {\r
-            //Log_OC.wtf(TAG, "starting existenceCheckRemoteOperation..." );\r
-            mWaitingForOpId = mOperationsServiceBinder.newOperation(existenceCheckIntent);\r
-        }\r
+    private void accessRootFolder(OwnCloudCredentials credentials) {\r
+        mAsyncTask = new AuthenticatorAsyncTask(this);\r
+        Object[] params = { mServerInfo.mBaseUrl, credentials };\r
+        mAsyncTask.execute(params);\r
     }\r
 \r
+\r
     /**\r
      * Starts the OAuth 'grant type' flow to get an access token, with \r
      * a GET AUTHORIZATION request to the BUILT-IN authorization server. \r
@@ -879,10 +935,18 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         // GET AUTHORIZATION request\r
         Uri uri = Uri.parse(mOAuthAuthEndpointText.getText().toString().trim());\r
         Uri.Builder uriBuilder = uri.buildUpon();\r
-        uriBuilder.appendQueryParameter(OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type));\r
-        uriBuilder.appendQueryParameter(OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri));   \r
-        uriBuilder.appendQueryParameter(OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id));\r
-        uriBuilder.appendQueryParameter(OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope));\r
+        uriBuilder.appendQueryParameter(\r
+                OAuth2Constants.KEY_RESPONSE_TYPE, getString(R.string.oauth2_response_type)\r
+        );\r
+        uriBuilder.appendQueryParameter(\r
+                OAuth2Constants.KEY_REDIRECT_URI, getString(R.string.oauth2_redirect_uri)\r
+        );   \r
+        uriBuilder.appendQueryParameter(\r
+                OAuth2Constants.KEY_CLIENT_ID, getString(R.string.oauth2_client_id)\r
+        );\r
+        uriBuilder.appendQueryParameter(\r
+                OAuth2Constants.KEY_SCOPE, getString(R.string.oauth2_scope)\r
+        );\r
         uri = uriBuilder.build();\r
         Log_OC.d(TAG, "Starting browser to view " + uri.toString());\r
         Intent i = new Intent(Intent.ACTION_VIEW, uri);\r
@@ -895,17 +959,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * in the server.\r
      */\r
     private void startSamlBasedFederatedSingleSignOnAuthorization() {\r
-        // be gentle with the user\r
+        /// be gentle with the user\r
         mAuthStatusIcon = R.drawable.progress_small;\r
         mAuthStatusText = R.string.auth_connecting_auth_server;\r
         showAuthStatus();\r
-        IndeterminateProgressDialog dialog = \r
-                IndeterminateProgressDialog.newInstance(R.string.auth_trying_to_login, true);\r
-        dialog.show(getSupportFragmentManager(), WAIT_DIALOG_TAG);\r
-\r
-        /// validate credentials accessing the root folder\r
-        accessRootFolderRemoteOperation("", "");\r
 \r
+        /// Show SAML-based SSO web dialog\r
+        String targetUrl = mServerInfo.mBaseUrl\r
+                + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
+        SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(targetUrl, targetUrl);\r
+        dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);\r
     }\r
 \r
     /**\r
@@ -925,14 +988,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         } else if (operation instanceof OAuth2GetAccessToken) {\r
             onGetOAuthAccessTokenFinish(result);\r
 \r
-        } else if (operation instanceof ExistenceCheckRemoteOperation)  {\r
-            //Log_OC.wtf(TAG, "received detection response through callback" );\r
-            if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
-                onSamlBasedFederatedSingleSignOnAuthorizationStart(result);\r
-\r
-            } else {\r
-                onAuthorizationCheckFinish(result);\r
-            }\r
         } else if (operation instanceof GetRemoteUserNameOperation) {\r
             onGetUserNameFinish(result);\r
         }\r
@@ -953,20 +1008,21 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 if (!mUsernameInput.getText().toString().equals(username)) {\r
                     // fail - not a new account, but an existing one; disallow\r
                     result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);\r
-                    /*\r
-                    OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(\r
-                            new OwnCloudAccount(\r
-                                    Uri.parse(mServerInfo.mBaseUrl),\r
-                                    OwnCloudCredentialsFactory.newSamlSsoCredentials(mAuthToken))\r
-                            );\r
-                            */\r
                     mAuthToken = "";\r
                     updateAuthStatusIconAndText(result);\r
                     showAuthStatus();\r
                     Log_OC.d(TAG, result.getLogMessage());\r
                 } else {\r
-                    updateToken();\r
-                    success = true;\r
+                    try {\r
+                        updateAccountAuthentication();\r
+                        success = true;\r
+\r
+                    } catch (AccountNotFoundException e) {\r
+                        Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);\r
+                        Toast.makeText(this, R.string.auth_account_does_not_exist,\r
+                                Toast.LENGTH_SHORT).show();\r
+                        finish();\r
+                    }\r
                 }\r
             }\r
 \r
@@ -980,36 +1036,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
     }\r
 \r
-    private void onSamlBasedFederatedSingleSignOnAuthorizationStart(RemoteOperationResult result) {\r
-        mWaitingForOpId = Long.MAX_VALUE;\r
-        dismissDialog(WAIT_DIALOG_TAG);\r
-
-        if (result.isIdPRedirection()) {
-            String url = result.getRedirectedLocation();\r
-            String targetUrl = mServerInfo.mBaseUrl \r
-                    + AccountUtils.getWebdavPath(mServerInfo.mVersion, mAuthTokenType);\r
-\r
-            // Show dialog\r
-            SamlWebViewDialog dialog = SamlWebViewDialog.newInstance(url, targetUrl);            \r
-            dialog.show(getSupportFragmentManager(), SAML_DIALOG_TAG);\r
-\r
-            mAuthStatusIcon = 0;\r
-            mAuthStatusText = 0;\r
-\r
-        } else {\r
-            mAuthStatusIcon = R.drawable.common_error;\r
-            mAuthStatusText = R.string.auth_unsupported_auth_method;\r
-\r
-        }\r
-        showAuthStatus();\r
-    }\r
-\r
-\r
     /**\r
      * Processes the result of the server check performed when the user finishes the enter of the\r
      * server URL.\r
-     * \r
-     * @param operation     Server check performed.\r
+     *\r
      * @param result        Result of the check.\r
      */\r
     private void onGetServerInfoFinish(RemoteOperationResult result) {\r
@@ -1054,16 +1084,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
 \r
     private boolean authSupported(AuthenticationMethod authMethod) {\r
-        String basic = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());\r
-        String oAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());\r
-        String saml =  AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType());\r
-        \r
-        return (( mAuthTokenType.equals(basic) && \r
-                    authMethod.equals(AuthenticationMethod.BASIC_HTTP_AUTH) ) ||\r
-                ( mAuthTokenType.equals(oAuth) && \r
-                    authMethod.equals(AuthenticationMethod.BEARER_TOKEN)) ||\r
-                ( mAuthTokenType.equals(saml)  && \r
-                    authMethod.equals(AuthenticationMethod.SAML_WEB_SSO))\r
+        return (( BASIC_TOKEN_TYPE.equals(mAuthTokenType) &&\r
+                    AuthenticationMethod.BASIC_HTTP_AUTH.equals(authMethod) ) ||\r
+                ( OAUTH_TOKEN_TYPE.equals(mAuthTokenType) &&\r
+                    AuthenticationMethod.BEARER_TOKEN.equals(authMethod)) ||\r
+                ( SAML_TOKEN_TYPE.equals(mAuthTokenType)  &&\r
+                    AuthenticationMethod.SAML_WEB_SSO.equals(authMethod))\r
         );\r
     }\r
 \r
@@ -1080,27 +1106,27 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                     url = "http://" + url;\r
                 }\r
             }\r
-            \r
-            url = trimUrlWebdav(url);\r
-\r
-            if (url.endsWith("/")) {\r
-                url = url.substring(0, url.length() - 1);\r
-            }\r
-\r
+        \r
+            url = normalizeUrlSuffix(url);\r
         }\r
         return (url != null ? url : "");\r
     }\r
+    \r
+    \r
+    private String normalizeUrlSuffix(String url) {\r
+        if (url.endsWith("/")) {\r
+            url = url.substring(0, url.length() - 1);\r
+        }\r
+        url = trimUrlWebdav(url);\r
+        return url;\r
+    }\r
 \r
 \r
     // TODO remove, if possible\r
     private String trimUrlWebdav(String url){       \r
-        if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0)){\r
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0.length());             \r
-        } else if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_2_0)){\r
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_2_0.length());             \r
-        } else if (url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_1_2)){\r
-            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_1_2.length());             \r
-        } \r
+        if(url.toLowerCase().endsWith(AccountUtils.WEBDAV_PATH_4_0_AND_LATER)){\r
+            url = url.substring(0, url.length() - AccountUtils.WEBDAV_PATH_4_0_AND_LATER.length());\r
+        }\r
         return (url != null ? url : "");\r
     }\r
 \r
@@ -1299,10 +1325,12 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             @SuppressWarnings("unchecked")\r
             Map<String, String> tokens = (Map<String, String>)(result.getData().get(0));\r
             mAuthToken = tokens.get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
-            //mAuthToken = ((OAuth2GetAccessToken)operation).getResultTokenMap().get(OAuth2Constants.KEY_ACCESS_TOKEN);\r
             Log_OC.d(TAG, "Got ACCESS TOKEN: " + mAuthToken);\r
-            \r
-            accessRootFolderRemoteOperation("", "");\r
+\r
+            /// validate token accessing to root folder / getting session\r
+            OwnCloudCredentials credentials = OwnCloudCredentialsFactory.newBearerCredentials(\r
+                    mAuthToken);\r
+            accessRootFolder(credentials);\r
 \r
         } else {\r
             updateAuthStatusIconAndText(result);\r
@@ -1316,11 +1344,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * Processes the result of the access check performed to try the user credentials.\r
      * \r
      * Creates a new account through the AccountManager.\r
-     * \r
-     * @param operation     Access check performed.\r
+     *\r
      * @param result        Result of the operation.\r
      */\r
-    private void onAuthorizationCheckFinish(RemoteOperationResult result) {\r
+    @Override\r
+    public void onAuthenticatorTaskCallback(RemoteOperationResult result) {\r
         mWaitingForOpId = Long.MAX_VALUE;\r
         dismissDialog(WAIT_DIALOG_TAG);\r
 \r
@@ -1332,15 +1360,23 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 success = createAccount();\r
 \r
             } else {\r
-                updateToken();\r
-                success = true;\r
+                try {\r
+                    updateAccountAuthentication();\r
+                    success = true;\r
+\r
+                } catch (AccountNotFoundException e) {\r
+                    Log_OC.e(TAG, "Account " + mAccount + " was removed!", e);\r
+                    Toast.makeText(this, R.string.auth_account_does_not_exist,\r
+                            Toast.LENGTH_SHORT).show();\r
+                    finish();\r
+                }\r
             }\r
 \r
             if (success) {\r
                 finish();\r
             }\r
             \r
-        } else if (result.isServerFail() || result.isException()) {
+        } else if (result.isServerFail() || result.isException()) {\r
             /// server errors or exceptions in authorization take to requiring a new check of \r
             /// the server\r
             mServerIsChecked = true;\r
@@ -1358,7 +1394,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             showRefreshButton(true);\r
             mOkButton.setEnabled(false);\r
 \r
-            // very special case (TODO: move to a common place for all the remote operations) (dangerous here?)\r
+            // very special case (TODO: move to a common place for all the remote operations)\r
             if (result.getCode() == ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED) {\r
                 showUntrustedCertDialog(result);\r
             }\r
@@ -1374,23 +1410,33 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
 \r
     /**\r
-     * Sets the proper response to get that the Account Authenticator that started this activity saves \r
-     * a new authorization token for mAccount.\r
+     * Updates the authentication token.\r
+     *\r
+     * Sets the proper response so that the AccountAuthenticator that started this activity\r
+     * saves a new authorization token for mAccount.\r
+     *\r
+     * Kills the session kept by OwnCloudClientManager so that a new one will created with\r
+     * the new credentials when needed.\r
      */\r
-    private void updateToken() {\r
+    private void updateAccountAuthentication() throws AccountNotFoundException {\r
+        \r
         Bundle response = new Bundle();\r
         response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);\r
         response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);\r
 \r
-        if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) { \r
+        if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).\r
+                equals(mAuthTokenType)) { \r
             response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
-            // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
+            // the next line is necessary, notifications are calling directly to the \r
+            // AuthenticatorActivity to update, without AccountManager intervention\r
             mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
 \r
-        } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
+        } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+                equals(mAuthTokenType)) {\r
 \r
             response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);\r
-            // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention\r
+            // the next line is necessary; by now, notifications are calling directly to the \r
+            // AuthenticatorActivity to update, without AccountManager intervention\r
             mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
 \r
         } else {\r
@@ -1411,8 +1457,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      */\r
     private boolean createAccount() {\r
         /// create and save new ownCloud account\r
-        boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);\r
-        boolean isSaml =  AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);\r
+        boolean isOAuth = AccountTypeUtils.\r
+                getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType);\r
+        boolean isSaml =  AccountTypeUtils.\r
+                getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType);\r
 \r
         Uri uri = Uri.parse(mServerInfo.mBaseUrl);\r
         String username = mUsernameInput.getText().toString().trim();\r
@@ -1434,11 +1482,21 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             mAccount = newAccount;\r
             \r
             if (isOAuth || isSaml) {\r
-                mAccountMgr.addAccountExplicitly(mAccount, "", null);  // with external authorizations, the password is never input in the app\r
+                // with external authorizations, the password is never input in the app\r
+                mAccountMgr.addAccountExplicitly(mAccount, "", null);  \r
             } else {\r
-                mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);\r
+                mAccountMgr.addAccountExplicitly(\r
+                        mAccount, mPasswordInput.getText().toString(), null\r
+                );\r
             }\r
 \r
+            // include account version with the new account\r
+            mAccountMgr.setUserData(\r
+                mAccount,\r
+                Constants.KEY_OC_ACCOUNT_VERSION,\r
+                Integer.toString(AccountUtils.ACCOUNT_VERSION)\r
+            );\r
+\r
             /// add the new account as default in preferences, if there is none already\r
             Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);\r
             if (defaultAccount == null) {\r
@@ -1449,20 +1507,24 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             }\r
 \r
             /// prepare result to return to the Authenticator\r
-            //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done\r
+            //  TODO check again what the Authenticator makes with it; probably has the same \r
+            //  effect as addAccountExplicitly, but it's not well done\r
             final Intent intent = new Intent();       \r
             intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE,    MainApp.getAccountType());\r
             intent.putExtra(AccountManager.KEY_ACCOUNT_NAME,    mAccount.name);\r
-            /*if (!isOAuth)\r
-                intent.putExtra(AccountManager.KEY_AUTHTOKEN,   MainApp.getAccountType()); */\r
             intent.putExtra(AccountManager.KEY_USERDATA,        username);\r
             if (isOAuth || isSaml) {\r
                 mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);\r
             }\r
-            /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
-            mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION,    mServerInfo.mVersion.getVersion());\r
-            mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL,   mServerInfo.mBaseUrl);\r
-
+            /// add user data to the new account; TODO probably can be done in the last parameter \r
+            //      addAccountExplicitly, or in KEY_USERDATA\r
+            mAccountMgr.setUserData(\r
+                    mAccount, Constants.KEY_OC_VERSION,    mServerInfo.mVersion.getVersion()\r
+            );\r
+            mAccountMgr.setUserData(\r
+                    mAccount, Constants.KEY_OC_BASE_URL,   mServerInfo.mBaseUrl\r
+            );\r
+\r
             if (isSaml) {\r
                 mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE"); \r
             } else if (isOAuth) {\r
@@ -1483,7 +1545,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      * @param view      'Account register' button\r
      */\r
     public void onRegisterClick(View view) {\r
-        Intent register = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url)));\r
+        Intent register = new Intent(\r
+                Intent.ACTION_VIEW, Uri.parse(getString(R.string.welcome_link_url))\r
+        );\r
         setResult(RESULT_CANCELED);\r
         startActivity(register);\r
     }\r
@@ -1492,9 +1556,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     /**\r
      * Updates the content and visibility state of the icon and text associated\r
      * to the last check on the ownCloud server.\r
-     * \r
-     * @param serverStatusText      Resource identifier of the text to show.\r
-     * @param serverStatusIcon      Resource identifier of the icon to show.\r
+     *\r
      */\r
     private void showServerStatus() {\r
         if (mServerStatusIcon == 0 && mServerStatusText == 0) {\r
@@ -1572,9 +1634,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     public void onCheckClick(View view) {\r
         CheckBox oAuth2Check = (CheckBox)view;\r
         if (oAuth2Check.isChecked()) {\r
-            mAuthTokenType = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType());\r
+            mAuthTokenType = OAUTH_TOKEN_TYPE;\r
         } else {\r
-            mAuthTokenType = AccountTypeUtils.getAuthTokenTypePass(MainApp.getAccountType());\r
+            mAuthTokenType = BASIC_TOKEN_TYPE;\r
         }\r
         updateAuthenticationPreFragmentVisibility();\r
     }\r
@@ -1583,18 +1645,21 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     /**\r
      *  Called when the 'action' button in an IME is pressed ('enter' in software keyboard).\r
      * \r
-     *  Used to trigger the authentication check when the user presses 'enter' after writing the password, \r
-     *  or to throw the server test when the only field on screen is the URL input field.\r
+     *  Used to trigger the authentication check when the user presses 'enter' after writing the \r
+     *  password, or to throw the server test when the only field on screen is the URL input field.\r
      */\r
     @Override\r
     public boolean onEditorAction(TextView inputField, int actionId, KeyEvent event) {\r
-        if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && inputField.equals(mPasswordInput)) {\r
+        if (actionId == EditorInfo.IME_ACTION_DONE && inputField != null && \r
+                inputField.equals(mPasswordInput)) {\r
             if (mOkButton.isEnabled()) {\r
                 mOkButton.performClick();\r
             }\r
 \r
-        } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && inputField.equals(mHostUrlInput)) {\r
-            if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType)) {\r
+        } else if (actionId == EditorInfo.IME_ACTION_NEXT && inputField != null && \r
+                inputField.equals(mHostUrlInput)) {\r
+            if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+                    equals(mAuthTokenType)) {\r
                 checkOcServer();\r
             }\r
         }\r
@@ -1622,8 +1687,10 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
                 final int x = (int) event.getX();\r
                 final int y = (int) event.getY();\r
                 final Rect bounds = rightDrawable.getBounds();\r
-                if (x >= (view.getRight() - bounds.width() - fuzz) && x <= (view.getRight() - view.getPaddingRight() + fuzz)\r
-                        && y >= (view.getPaddingTop() - fuzz) && y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {\r
+                if (    x >= (view.getRight() - bounds.width() - fuzz) && \r
+                        x <= (view.getRight() - view.getPaddingRight() + fuzz) && \r
+                        y >= (view.getPaddingTop() - fuzz) &&\r
+                        y <= (view.getHeight() - view.getPaddingBottom()) + fuzz) {\r
 \r
                     return onDrawableTouch(event);\r
                 }\r
@@ -1643,8 +1710,7 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         getUserNameIntent.putExtra(OperationsService.EXTRA_COOKIE, sessionCookie);\r
         \r
         if (mOperationsServiceBinder != null) {\r
-            //Log_OC.wtf(TAG, "starting getRemoteUserNameOperation..." );\r
-            mWaitingForOpId = mOperationsServiceBinder.newOperation(getUserNameIntent);\r
+            mWaitingForOpId = mOperationsServiceBinder.queueNewOperation(getUserNameIntent);\r
         }\r
     }\r
 \r
@@ -1656,8 +1722,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
             mAuthToken = sessionCookie;\r
             getRemoteUserNameOperation(sessionCookie, true);\r
             Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);\r
-            if (fd != null && fd instanceof SherlockDialogFragment) {\r
-                Dialog d = ((SherlockDialogFragment)fd).getDialog();\r
+            if (fd != null && fd instanceof DialogFragment) {\r
+                Dialog d = ((DialogFragment)fd).getDialog();\r
                 if (d != null && d.isShowing()) {\r
                     d.dismiss();\r
                 }\r
@@ -1672,7 +1738,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
     @Override\r
     public boolean onTouchEvent(MotionEvent event) {\r
-        if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).equals(mAuthTokenType) &&\r
+        if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType()).\r
+                equals(mAuthTokenType) &&\r
                 mHostUrlInput.hasFocus() && event.getAction() == MotionEvent.ACTION_DOWN) {\r
             checkOcServer();\r
         }\r
@@ -1683,13 +1750,16 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     /**\r
      * Show untrusted cert dialog \r
      */\r
-    public void showUntrustedCertDialog(X509Certificate x509Certificate, SslError error, SslErrorHandler handler) {\r
+    public void showUntrustedCertDialog(\r
+            X509Certificate x509Certificate, SslError error, SslErrorHandler handler\r
+        ) {\r
         // Show a dialog with the certificate info\r
         SslUntrustedCertDialog dialog = null;\r
         if (x509Certificate == null) {\r
             dialog = SslUntrustedCertDialog.newInstanceForEmptySslError(error, handler);\r
         } else {\r
-            dialog = SslUntrustedCertDialog.newInstanceForFullSslError(x509Certificate, error, handler);\r
+            dialog = SslUntrustedCertDialog.\r
+                    newInstanceForFullSslError(x509Certificate, error, handler);\r
         }\r
         FragmentManager fm = getSupportFragmentManager();\r
         FragmentTransaction ft = fm.beginTransaction();\r
@@ -1703,7 +1773,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
      */\r
     private void showUntrustedCertDialog(RemoteOperationResult result) {\r
         // Show a dialog with the certificate info\r
-        SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());\r
+        SslUntrustedCertDialog dialog = SslUntrustedCertDialog.\r
+                newInstanceForFullSslError((CertificateCombinedException)result.getException());\r
         FragmentManager fm = getSupportFragmentManager();\r
         FragmentTransaction ft = fm.beginTransaction();\r
         ft.addToBackStack(null);\r
@@ -1717,7 +1788,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     public void onSavedCertificate() {\r
         Fragment fd = getSupportFragmentManager().findFragmentByTag(SAML_DIALOG_TAG);\r
         if (fd == null) {\r
-            // if SAML dialog is not shown, the SslDialog was shown due to an SSL error in the server check\r
+            // if SAML dialog is not shown, \r
+            // the SslDialog was shown due to an SSL error in the server check\r
             checkOcServer();\r
         }\r
     }\r
@@ -1753,8 +1825,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     \r
     private void dismissDialog(String dialogTag){\r
         Fragment frag = getSupportFragmentManager().findFragmentByTag(dialogTag);\r
-        if (frag != null && frag instanceof SherlockDialogFragment) {\r
-            SherlockDialogFragment dialog = (SherlockDialogFragment) frag;\r
+        if (frag != null && frag instanceof DialogFragment) {\r
+            DialogFragment dialog = (DialogFragment) frag;\r
             dialog.dismiss();\r
         }\r
     }\r
@@ -1767,8 +1839,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
         @Override\r
         public void onServiceConnected(ComponentName component, IBinder service) {\r
-            if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {\r
-                //Log_OC.wtf(TAG, "Operations service connected");\r
+            if (component.equals(\r
+                    new ComponentName(AuthenticatorActivity.this, OperationsService.class)\r
+                )) {\r
                 mOperationsServiceBinder = (OperationsServiceBinder) service;\r
                 \r
                 doOnResumeAndBound();\r
@@ -1781,7 +1854,9 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
 \r
         @Override\r
         public void onServiceDisconnected(ComponentName component) {\r
-            if (component.equals(new ComponentName(AuthenticatorActivity.this, OperationsService.class))) {\r
+            if (component.equals(\r
+                    new ComponentName(AuthenticatorActivity.this, OperationsService.class)\r
+                )) {\r
                 Log_OC.e(TAG, "Operations service crashed");\r
                 mOperationsServiceBinder = null;\r
             }\r
@@ -1797,7 +1872,8 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     public void createAuthenticationDialog(WebView webView, HttpAuthHandler handler) {\r
 \r
         // Show a dialog with the certificate info\r
-        CredentialsDialogFragment dialog = CredentialsDialogFragment.newInstanceForCredentials(webView, handler);\r
+        CredentialsDialogFragment dialog = \r
+                CredentialsDialogFragment.newInstanceForCredentials(webView, handler);\r
         FragmentManager fm = getSupportFragmentManager();\r
         FragmentTransaction ft = fm.beginTransaction();\r
         ft.addToBackStack(null);\r
@@ -1805,7 +1881,11 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
         dialog.show(ft, CREDENTIALS_DIALOG_TAG);\r
 \r
         if (!mIsFirstAuthAttempt) {\r
-            Toast.makeText(getApplicationContext(), getText(R.string.saml_authentication_wrong_pass), Toast.LENGTH_LONG).show();\r
+            Toast.makeText(\r
+                    getApplicationContext(), \r
+                    getText(R.string.saml_authentication_wrong_pass), \r
+                    Toast.LENGTH_LONG\r
+            ).show();\r
         } else {\r
             mIsFirstAuthAttempt = false;\r
         }\r
@@ -1817,4 +1897,6 @@ SsoWebViewClientListener, OnSslUntrustedCertListener {
     public void doNegativeAuthenticatioDialogClick(){\r
         mIsFirstAuthAttempt = true;\r
     }\r
+\r
+\r
 }\r