Example usage for android.accounts AccountManager setUserData

List of usage examples for android.accounts AccountManager setUserData

Introduction

In this page you can find the example usage for android.accounts AccountManager setUserData.

Prototype

public void setUserData(final Account account, final String key, final String value) 

Source Link

Document

Sets one userdata key for an account.

Usage

From source file:org.alfresco.mobile.android.platform.SessionManager.java

@Subscribe
public void onSessionRequested(RequestSessionEvent event) {
    if (event.requestReload) {
        if (event.networkId != null) {
            android.accounts.Account acc = accountManager.getAndroidAccount(event.accountToLoad.getId());
            AccountManager manager = AccountManager.get(appContext);
            manager.setUserData(acc, AlfrescoAccount.ACCOUNT_REPOSITORY_ID, event.networkId);
        }//from  w  w w  .  j  a va 2 s .co m
        createSession(event.accountToLoad);
        return;
    }

    if (event.data != null) {
        loadSession(event.accountToLoad, event.data);
    } else {
        loadSession(event.accountToLoad);
    }
}

From source file:org.klnusbaum.udj.auth.Authenticator.java

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) {//from www.  j a v a2s. c  om
    final AccountManager am = AccountManager.get(context);
    final String password = am.getPassword(account);
    if (password != null) {
        try {
            final ServerConnection.AuthResult authResult = ServerConnection.authenticate(account.name,
                    password);
            if (!TextUtils.isEmpty(authResult.ticketHash)) {
                am.setUserData(account, Constants.USER_ID_DATA, authResult.userId);
                return bundleUpAuthToken(account, authResult.ticketHash);
            }
        } catch (AuthenticationException e) {
            //TODO actually do something with this exception 
        } catch (IOException e) {
            //TODO actually do something with this exception 
        } catch (JSONException e) {
            //TODO actually do something with this exception 
        } catch (APIVersionException e) {
            final Intent intent = new Intent(context, NeedUpdateActivity.class);
            intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
            intent.putExtra(AccountManager.KEY_ERROR_CODE, Constants.AUTH_API_VERSION_ERROR);
            final Bundle bundle = new Bundle();
            bundle.putParcelable(AccountManager.KEY_INTENT, intent);
            return bundle;
        }
    }

    //Oh snap, they're username and password didn't work. O well, better have
    // them sort it out.
    final Intent intent = new Intent(context, AuthActivity.class);
    intent.putExtra(AuthActivity.PARAM_USERNAME, account.name);
    intent.putExtra(AuthActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

From source file:org.alfresco.mobile.android.application.fragments.preferences.AccountSettingsFragment.java

@Override
public void onTextEdited(int id, String newValue) {
    Account androidAccount = AlfrescoAccountManager.getInstance(getActivity()).getAndroidAccount(accountId);
    AccountManager manager = AccountManager.get(getActivity());
    manager.setUserData(androidAccount, AlfrescoAccount.ACCOUNT_NAME, newValue);
    account = AlfrescoAccountManager.getInstance(getActivity()).retrieveAccount(accountId);
    SessionManager.getInstance(getActivity()).saveSession(account,
            SessionManager.getInstance(getActivity()).getSession(account.getId()));
    SessionManager.getInstance(getActivity()).saveAccount(account);
    setCurrentAccount(account);//from   w w w .j  a  v  a2 s  . c o  m

    AnalyticsHelper.reportOperationEvent(getActivity(), AnalyticsManager.CATEGORY_ACCOUNT,
            AnalyticsManager.ACTION_EDIT, AnalyticsManager.LABEL_NAME, 1, false);

    recreate();
}

From source file:com.ntsync.android.sync.shared.SyncUtils.java

/**
 * Get a stored PaymentConfirmation (has to be verified on the server).
 * //from   w w  w .  ja  v  a2 s. c  om
 * @param account
 * @param accountManager
 * @return null if none is available.
 */
public static PaymentData getPayment(Account account, AccountManager accountManager) {
    PaymentData payment = null;
    String paymentData = accountManager.getUserData(account, LAST_PAYMENT);
    if (paymentData != null) {
        int pos1 = paymentData.indexOf(';');
        int pos2 = paymentData.lastIndexOf(';');
        int startTimePos = pos2 + 1;
        if (pos1 > 0 && pos2 > 0 && pos2 > pos1 && startTimePos < paymentData.length()) {
            try {
                long paymentSaveDate = Long.parseLong(paymentData.substring(startTimePos));
                UUID priceId = UUID.fromString(paymentData.substring(0, pos1));
                JSONObject obj = new JSONObject(paymentData.substring(pos1 + 1, pos2));
                payment = new PaymentData(priceId, paymentSaveDate, obj);
            } catch (JSONException ex) {
                Log.w(TAG, "Invalid PaymentConfirmation data. Data Ignored", ex);
            } catch (IllegalArgumentException ex) {
                Log.w(TAG, "Invalid PaymentConfirmation data. Data Ignored", ex);
            }
        }
        if (payment == null) {
            // Remove invalid PaymentData
            accountManager.setUserData(account, LAST_PAYMENT, null);
        }
    }

    return payment;
}

From source file:org.alfresco.mobile.android.application.fragments.preferences.AccountSettingsFragment.java

@Override
public void onTextClear(int valueId) {
    Account androidAccount = AlfrescoAccountManager.getInstance(getActivity()).getAndroidAccount(accountId);
    AccountManager manager = AccountManager.get(getActivity());
    if (account.getTypeId() == AlfrescoAccount.TYPE_ALFRESCO_CLOUD) {
        manager.setUserData(androidAccount, AlfrescoAccount.ACCOUNT_NAME,
                getString(R.string.account_default_cloud));
    } else if (account.getTypeId() == AlfrescoAccount.TYPE_ALFRESCO_CMIS) {
        manager.setUserData(androidAccount, AlfrescoAccount.ACCOUNT_NAME,
                getString(R.string.account_default_onpremise));
    }/*from w  ww .  j ava 2s  . co m*/
    manager.setUserData(androidAccount, AlfrescoAccount.ACCOUNT_NAME,
            getString(R.string.account_default_onpremise));
    account = AlfrescoAccountManager.getInstance(getActivity()).retrieveAccount(accountId);
    SessionManager.getInstance(getActivity()).saveSession(account,
            SessionManager.getInstance(getActivity()).getSession(account.getId()));
    SessionManager.getInstance(getActivity()).saveAccount(account);
    setCurrentAccount(account);

    recreate();
}

From source file:org.mozilla.gecko.fxa.authenticator.AndroidFxAccount.java

public static AndroidFxAccount addAndroidAccount(Context context, String email, String profile,
        String idpServerURI, String tokenServerURI, String profileServerURI, State state,
        final Map<String, Boolean> authoritiesToSyncAutomaticallyMap, final int accountVersion,
        final boolean fromPickle, ExtendedJSONObject bundle)
        throws UnsupportedEncodingException, GeneralSecurityException, URISyntaxException {
    if (email == null) {
        throw new IllegalArgumentException("email must not be null");
    }// w  w w. j a  va 2 s .c  om
    if (profile == null) {
        throw new IllegalArgumentException("profile must not be null");
    }
    if (idpServerURI == null) {
        throw new IllegalArgumentException("idpServerURI must not be null");
    }
    if (tokenServerURI == null) {
        throw new IllegalArgumentException("tokenServerURI must not be null");
    }
    if (profileServerURI == null) {
        throw new IllegalArgumentException("profileServerURI must not be null");
    }
    if (state == null) {
        throw new IllegalArgumentException("state must not be null");
    }

    // TODO: Add migration code.
    if (accountVersion != CURRENT_ACCOUNT_VERSION) {
        throw new IllegalStateException("Could not create account of version " + accountVersion
                + ". Current version is " + CURRENT_ACCOUNT_VERSION + ".");
    }

    // Android has internal restrictions that require all values in this
    // bundle to be strings. *sigh*
    Bundle userdata = new Bundle();
    userdata.putString(ACCOUNT_KEY_ACCOUNT_VERSION, "" + CURRENT_ACCOUNT_VERSION);
    userdata.putString(ACCOUNT_KEY_IDP_SERVER, idpServerURI);
    userdata.putString(ACCOUNT_KEY_TOKEN_SERVER, tokenServerURI);
    userdata.putString(ACCOUNT_KEY_PROFILE_SERVER, profileServerURI);
    userdata.putString(ACCOUNT_KEY_PROFILE, profile);

    if (bundle == null) {
        bundle = new ExtendedJSONObject();
        // TODO: How to upgrade?
        bundle.put(BUNDLE_KEY_BUNDLE_VERSION, CURRENT_BUNDLE_VERSION);
    }
    bundle.put(BUNDLE_KEY_STATE_LABEL, state.getStateLabel().name());
    bundle.put(BUNDLE_KEY_STATE, state.toJSONObject().toJSONString());

    userdata.putString(ACCOUNT_KEY_DESCRIPTOR, bundle.toJSONString());

    Account account = new Account(email, FxAccountConstants.ACCOUNT_TYPE);
    AccountManager accountManager = AccountManager.get(context);
    // We don't set an Android password, because we don't want to persist the
    // password (or anything else as powerful as the password). Instead, we
    // internally manage a sessionToken with a remotely owned lifecycle.
    boolean added = accountManager.addAccountExplicitly(account, null, userdata);
    if (!added) {
        return null;
    }

    // Try to work around an intermittent issue described at
    // http://stackoverflow.com/a/11698139.  What happens is that tests that
    // delete and re-create the same account frequently will find the account
    // missing all or some of the userdata bundle, possibly due to an Android
    // AccountManager caching bug.
    for (String key : userdata.keySet()) {
        accountManager.setUserData(account, key, userdata.getString(key));
    }

    AndroidFxAccount fxAccount = new AndroidFxAccount(context, account);

    if (!fromPickle) {
        fxAccount.clearSyncPrefs();
    }

    fxAccount.setAuthoritiesToSyncAutomaticallyMap(authoritiesToSyncAutomaticallyMap);

    return fxAccount;
}

From source file:com.cerema.cloud2.operations.UpdateOCVersionOperation.java

@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    AccountManager accountMngr = AccountManager.get(mContext);
    String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
    statUrl += AccountUtils.STATUS_PATH;
    RemoteOperationResult result = null;
    GetMethod get = null;// w w  w. j  a  va2s  .com
    try {
        get = new GetMethod(statUrl);
        int status = client.executeMethod(get);
        if (status != HttpStatus.SC_OK) {
            client.exhaustResponse(get.getResponseBodyAsStream());
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());

        } else {
            String response = get.getResponseBodyAsString();
            if (response != null) {
                JSONObject json = new JSONObject(response);
                if (json != null && json.getString("version") != null) {

                    String version = json.getString("version");
                    mOwnCloudVersion = new OwnCloudVersion(version);
                    if (mOwnCloudVersion.isVersionValid()) {
                        accountMngr.setUserData(mAccount, Constants.KEY_OC_VERSION,
                                mOwnCloudVersion.getVersion());
                        Log_OC.d(TAG, "Got new OC version " + mOwnCloudVersion.toString());

                        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);
                    }
                }
            }
            if (result == null) {
                result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
            }
        }
        Log_OC.i(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": "
                + result.getLogMessage());

    } catch (JSONException e) {
        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": "
                + result.getLogMessage(), e);

    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": "
                + result.getLogMessage(), e);

    } finally {
        if (get != null)
            get.releaseConnection();
    }
    return result;
}

From source file:com.he5ed.lib.cloudprovider.auth.OAuth2Fragment.java

/**
 * Create a new user account or update the current user account
 *
 * @param user user information returned from server
 *///from w  w w  . j  a v a 2s  . com
private void addAccount(User user) {
    boolean accountExist = false;
    AccountManager am = AccountManager.get(getActivity());
    // check if account already exist in AccountManager
    Account[] accounts = am.getAccountsByType(CloudProvider.ACCOUNT_TYPE);
    for (Account account : accounts) {
        if (account.name.equals(user.id)) {
            accountExist = true;
            break;
        }
    }

    Account account = new Account(user.id, CloudProvider.ACCOUNT_TYPE);
    Bundle userData = new Bundle(); // must be string value
    String accessToken = mTokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
    String refreshToken = mTokenInfo.get(Authenticator.KEY_REFRESH_TOKEN);
    String expiryDuration = mTokenInfo.get(Authenticator.KEY_EXPIRY);
    if (accountExist) {
        // update current account access token
        am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken);
        if (refreshToken != null)
            am.setUserData(account, Authenticator.KEY_REFRESH_TOKEN, refreshToken);
        if (expiryDuration != null)
            am.setUserData(account, Authenticator.KEY_EXPIRY, expiryDuration);
    } else {
        // add new account into AccountManager
        if (refreshToken != null)
            userData.putString(Authenticator.KEY_REFRESH_TOKEN, refreshToken);
        if (expiryDuration != null)
            userData.putString(Authenticator.KEY_EXPIRY, expiryDuration);
        userData.putString(Authenticator.KEY_CLOUD_API, AuthHelper.getCloudApi(mCloudApi));
        userData.putString(Authenticator.KEY_USERNAME, user.name);
        userData.putString(Authenticator.KEY_EMAIL, user.email);
        userData.putString(Authenticator.KEY_AVATAR_URL, user.avatarUrl);

        am.addAccountExplicitly(account, null, userData);
        am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken);
    }

    // send result back to AccountManager
    Bundle result = new Bundle();
    result.putString(AccountManager.KEY_ACCOUNT_NAME, user.id);
    result.putString(AccountManager.KEY_ACCOUNT_TYPE, CloudProvider.ACCOUNT_TYPE);
    ((AccountAuthenticatorActivity) getActivity()).setAccountAuthenticatorResult(result);

    getActivity().finish();
}

From source file:com.sefford.beauthentic.activities.LoginActivity.java

void createGoogleAccount(final GoogleSignInAccount acct) {
    final Account account = new Account(acct.getDisplayName(), AuthenticAuthenticator.ACCOUNT_TYPE);
    final AccountManager am = AccountManager.get(this);
    final Bundle data = new Bundle();
    data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.GOOGLE.ordinal());
    data.putString(AccountManager.KEY_ACCOUNT_NAME, acct.getDisplayName());
    data.putString(AccountManager.KEY_AUTHTOKEN, acct.getIdToken());
    am.confirmCredentials(account, data, null, new AccountManagerCallback<Bundle>() {
        @Override/*from  w w w .  jav  a 2 s.  c  o  m*/
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                    Sessions.addAccount(am, account, "", Bundle.EMPTY);
                    am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE,
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE,
                            Integer.toString(AuthenticAuthenticator.Type.GOOGLE.ordinal()));
                    notifyLoginToGCM(AuthenticAuthenticator.Type.GOOGLE.ordinal(), account.name, "",
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    googleApi.saveCredential(new Credential.Builder(acct.getEmail())
                            .setAccountType(IdentityProviders.GOOGLE).setName(acct.getDisplayName())
                            .setProfilePictureUri(acct.getPhotoUrl()).build(),
                            new SmartlockCredentialCallback());
                }
            } catch (OperationCanceledException e) {
                Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show();
            } catch (IOException e) {
                Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG)
                        .show();
            } catch (AuthenticatorException e) {
                Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
            }
        }
    }, null);
}