Search in sources :

Example 6 with AuthenticatorException

use of android.accounts.AuthenticatorException in project FastDev4Android by jiangqqlmj.

the class AndroidAuthenticatorTest method failedGetAuthToken.

@Test(expected = AuthFailureError.class)
public void failedGetAuthToken() throws Exception {
    when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
    when(mFuture.getResult()).thenThrow(new AuthenticatorException("sadness!"));
    mAuthenticator.getAuthToken();
}
Also used : AuthenticatorException(android.accounts.AuthenticatorException) Test(org.junit.Test)

Example 7 with AuthenticatorException

use of android.accounts.AuthenticatorException in project AndroidSDK-RecipeBook by gabu.

the class Recipe098 method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // GoogleTransportを作る
    mTransport = GoogleTransport.create();
    GoogleHeaders headers = (GoogleHeaders) mTransport.defaultHeaders;
    // "[company-id]-[app-name]-[app-version]"という形式で
    // アプリケーション名をセット
    headers.setApplicationName("gabu-recipe-98");
    // バージョンをセット
    headers.gdataVersion = "3";
    // AtomParserを作る
    AtomParser parser = new AtomParser();
    // GoogleDocumentsListのネームスペースをセット
    parser.namespaceDictionary = Namespace.DICTIONARY;
    // GoogleTransportにAtomParserをセット
    mTransport.addParser(parser);
    // HttpTransportにApacheHttpTransportのインスタンスをセット
    // これをやっておかないとExceptionが発生します。
    HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
    // AccountManagerを取得
    AccountManager manager = AccountManager.get(this);
    // Googleアカウントの一覧を取得
    Account[] accounts = manager.getAccountsByType("com.google");
    // サンプルなので暫定的に1つ目を取得
    Account acount = accounts[0];
    // 認証のためのauth tokenを取得
    AccountManagerFuture<Bundle> f = manager.getAuthToken(acount, DOCS_AUTH_TOKEN_TYPE, null, this, null, null);
    try {
        Bundle b = f.getResult();
        mAuthToken = b.getString(AccountManager.KEY_AUTHTOKEN);
    //            Log.d(TAG, "authToken=" + mAuthToken);
    } catch (OperationCanceledException e) {
        e.printStackTrace();
    } catch (AuthenticatorException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // GoogleTransportにauth tokenをセット
    // これで認証ヘッダを自動的に付けてくれます。
    ((GoogleHeaders) mTransport.defaultHeaders).setGoogleLogin(mAuthToken);
    // Googleドキュメントの一覧を取得するURLを作成
    String url = GOOGLE_DOCS_API_URL + "default/private/full/-/document";
    // GoogleTransportからGETリクエストを生成
    HttpRequest request = mTransport.buildGetRequest();
    // URLをセット
    request.setUrl(url);
    try {
        // HTTPリクエストを実行してレスポンスをパース
        DocumentListFeed feed = request.execute().parseAs(DocumentListFeed.class);
        // DocsAdapterを生成
        DocsAdapter adapter = new DocsAdapter(getApplicationContext(), 0, feed.entries);
        // ListViewにDocsAdapterをセット
        ListView listView = (ListView) findViewById(R.id.list_view);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(mOnItemClickListener);
    } catch (IOException e) {
        handleException(e);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Account(android.accounts.Account) GoogleHeaders(com.google.api.client.googleapis.GoogleHeaders) Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) IOException(java.io.IOException) AtomParser(com.google.api.client.xml.atom.AtomParser) ListView(android.widget.ListView) AccountManager(android.accounts.AccountManager)

Example 8 with AuthenticatorException

use of android.accounts.AuthenticatorException in project AndroidSDK-RecipeBook by gabu.

the class Recipe101 method onCreate.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mTransport = GoogleTransport.create();
    GoogleHeaders headers = (GoogleHeaders) mTransport.defaultHeaders;
    // "[company-id]-[app-name]-[app-version]"という形式で
    // アプリケーション名をセット
    headers.setApplicationName("gabu-recipe-101");
    // バージョンをセット
    headers.gdataVersion = "2";
    // AtomParserを作る
    AtomParser parser = new AtomParser();
    // GoogleCalendarのネームスペースをセット
    parser.namespaceDictionary = Namespace.DICTIONARY;
    // GoogleTransportにAtomParserをセット
    mTransport.addParser(parser);
    // HttpTransportにApacheHttpTransportのインスタンスをセット
    // これをやっておかないとExceptionが発生します。
    HttpTransport.setLowLevelHttpTransport(ApacheHttpTransport.INSTANCE);
    // AccountManagerを取得
    AccountManager manager = AccountManager.get(this);
    // Googleアカウントの一覧を取得
    Account[] accounts = manager.getAccountsByType("com.google");
    // サンプルなので暫定的に1つ目を取得
    Account acount = accounts[0];
    // 認証のためのauth tokenを取得
    AccountManagerFuture<Bundle> f = manager.getAuthToken(acount, CAL_AUTH_TOKEN_TYPE, null, this, null, null);
    try {
        Bundle b = f.getResult();
        mAuthToken = b.getString(AccountManager.KEY_AUTHTOKEN);
    //            Log.d(TAG, "authToken=" + mAuthToken);
    } catch (OperationCanceledException e) {
        e.printStackTrace();
    } catch (AuthenticatorException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // GoogleTransportにauth tokenをセット
    // これで認証ヘッダを自動的に付けてくれます。
    ((GoogleHeaders) mTransport.defaultHeaders).setGoogleLogin(mAuthToken);
    // GoogleTransportからGETリクエストを生成
    HttpRequest request = mTransport.buildGetRequest();
    // Googleカレンダーの一覧を取得するURLを作成
    // 共有しているカレンダーも含む
    //        String url = GOOGLE_CAL_API_URL + "default/allcalendars/full";
    // 自分がオーナーのカレンダーのみ
    String url = GOOGLE_CAL_API_URL + "default/owncalendars/full";
    // URLをセット
    request.setUrl(url);
    try {
        // HTTPリクエストを実行してレスポンスをパース
        CalendarFeed feed = request.execute().parseAs(CalendarFeed.class);
        for (CalendarEntry entry : feed.entries) {
            Log.d(TAG, entry.title + ", " + entry.id);
        }
        // サンプルのためカレンダーの1つ目を取得
        CalendarEntry entry = feed.entries.get(0);
        // このuserIDがカレンダーを一意に特定するIDになります。
        String userID = entry.getUserID();
        // 何も指定せずに予定の一覧を取得
        url = GOOGLE_CAL_API_URL + userID + "/private/full";
        debug(request, url);
    // 2010年6月の予定の一覧を取得
    //            url = createMonthlyUrl(userID, 2010, 6);
    //            debug(request, url);
    // 2010年6月30日の予定の一覧
    //            url = createDailyUrl(userID, 2010, 6, 30);
    //            debug(request, url);
    } catch (IOException e) {
        handleException(e);
    }
}
Also used : HttpRequest(com.google.api.client.http.HttpRequest) Account(android.accounts.Account) GoogleHeaders(com.google.api.client.googleapis.GoogleHeaders) Bundle(android.os.Bundle) OperationCanceledException(android.accounts.OperationCanceledException) AuthenticatorException(android.accounts.AuthenticatorException) IOException(java.io.IOException) AtomParser(com.google.api.client.xml.atom.AtomParser) AccountManager(android.accounts.AccountManager)

Example 9 with AuthenticatorException

use of android.accounts.AuthenticatorException in project Reader by TheKeeperOfPie.

the class Receiver method checkInbox.

public void checkInbox(final Context context, @Nullable final ArrayList<String> names) {
    final ArrayList<String> readNames;
    if (names == null) {
        readNames = new ArrayList<>();
    } else {
        readNames = names;
    }
    new Thread(new Runnable() {

        @Override
        public void run() {
            final Listing messages = new Listing();
            Account[] accounts = accountManager.getAccountsByType(Reddit.ACCOUNT_TYPE);
            for (Account account : accounts) {
                final AccountManagerFuture<Bundle> futureAuth = accountManager.getAuthToken(account, Reddit.AUTH_TOKEN_FULL_ACCESS, null, true, null, null);
                try {
                    Bundle bundle = futureAuth.getResult();
                    final String tokenAuth = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Request request = new Request.Builder().url(Reddit.OAUTH_URL + "/message/unread").header(Reddit.USER_AGENT, Reddit.CUSTOM_USER_AGENT).header(Reddit.AUTHORIZATION, Reddit.BEARER + tokenAuth).header(Reddit.CONTENT_TYPE, Reddit.CONTENT_TYPE_APP_JSON).get().build();
                    String response = okHttpClient.newCall(request).execute().body().string();
                    Listing listing = Listing.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class));
                    messages.addChildren(listing.getChildren());
                    Log.d(TAG, account.name + " checkInbox response: " + response);
                } catch (OperationCanceledException | AuthenticatorException | IOException e) {
                    e.printStackTrace();
                }
            }
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
            Thing thing = null;
            for (int index = 0; index < messages.getChildren().size(); index++) {
                thing = messages.getChildren().get(index);
                if (readNames.contains(thing.getName())) {
                    reddit.markRead(thing.getName()).subscribe(new ObserverEmpty<>());
                    thing = null;
                } else {
                    readNames.add(thing.getName());
                    break;
                }
            }
            if (thing == null) {
                notificationManager.cancel(NOTIFICATION_INBOX);
                return;
            }
            int titleSuffixResource = messages.getChildren().size() == 1 ? R.string.new_message : R.string.new_messages;
            CharSequence content = "";
            CharSequence author = "";
            CharSequence dest = "";
            if (thing instanceof Message) {
                content = ((Message) thing).getBodyHtml();
                author = ((Message) thing).getAuthor();
                dest = ((Message) thing).getDest();
            } else if (thing instanceof Comment) {
                content = ((Comment) thing).getBodyHtml();
                author = ((Comment) thing).getAuthor();
                dest = ((Comment) thing).getDest();
            }
            Intent intentActivity = new Intent(context, ActivityMain.class);
            intentActivity.putExtra(ActivityMain.ACCOUNT, dest);
            intentActivity.putExtra(ActivityMain.NAV_ID, R.id.item_inbox);
            intentActivity.putExtra(ActivityMain.NAV_PAGE, ControllerInbox.UNREAD);
            PendingIntent pendingIntentActivity = PendingIntent.getActivity(context, 0, intentActivity, PendingIntent.FLAG_CANCEL_CURRENT);
            Intent intentRecheckInbox = new Intent(INTENT_INBOX);
            intentRecheckInbox.putExtra(READ_NAMES, readNames);
            PendingIntent pendingIntentRecheckInbox = PendingIntent.getBroadcast(context, 0, intentRecheckInbox, PendingIntent.FLAG_CANCEL_CURRENT);
            Themer themer = new Themer(context);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.app_icon_white_outline).setContentTitle(messages.getChildren().size() + " " + context.getResources().getString(titleSuffixResource)).setContentText(context.getString(R.string.expand_to_read_first_message)).setStyle(new NotificationCompat.BigTextStyle().setSummaryText(context.getString(R.string.from) + " /u/" + author).bigText(content)).setContentIntent(pendingIntentActivity).addAction(new NotificationCompat.Action(R.drawable.ic_check_white_24dp, context.getString(R.string.mark_read), pendingIntentRecheckInbox)).setDeleteIntent(pendingIntentRecheckInbox).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_EMAIL).setColor(themer.getColorPrimary()).setLights(themer.getColorPrimary(), LED_MS_ON, LED_MS_OFF);
            notificationManager.notify(NOTIFICATION_INBOX, builder.build());
        }
    }).start();
}
Also used : Account(android.accounts.Account) Message(com.winsonchiu.reader.data.reddit.Message) OperationCanceledException(android.accounts.OperationCanceledException) NotificationManagerCompat(android.support.v4.app.NotificationManagerCompat) JsonNode(com.fasterxml.jackson.databind.JsonNode) NotificationCompat(android.support.v4.app.NotificationCompat) Thing(com.winsonchiu.reader.data.reddit.Thing) Comment(com.winsonchiu.reader.data.reddit.Comment) Bundle(android.os.Bundle) Request(okhttp3.Request) AuthenticatorException(android.accounts.AuthenticatorException) Themer(com.winsonchiu.reader.theme.Themer) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) IOException(java.io.IOException) Listing(com.winsonchiu.reader.data.reddit.Listing) PendingIntent(android.app.PendingIntent)

Example 10 with AuthenticatorException

use of android.accounts.AuthenticatorException in project TaEmCasa by Dionen.

the class AndroidAuthenticatorTest method failedGetAuthToken.

@Test(expected = AuthFailureError.class)
public void failedGetAuthToken() throws Exception {
    when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
    when(mFuture.getResult()).thenThrow(new AuthenticatorException("sadness!"));
    mAuthenticator.getAuthToken();
}
Also used : AuthenticatorException(android.accounts.AuthenticatorException) Test(org.junit.Test)

Aggregations

AuthenticatorException (android.accounts.AuthenticatorException)13 OperationCanceledException (android.accounts.OperationCanceledException)10 IOException (java.io.IOException)10 Bundle (android.os.Bundle)8 Account (android.accounts.Account)6 AccountManager (android.accounts.AccountManager)4 Intent (android.content.Intent)3 Test (org.junit.Test)3 UserHandle (android.os.UserHandle)2 GoogleHeaders (com.google.api.client.googleapis.GoogleHeaders)2 HttpRequest (com.google.api.client.http.HttpRequest)2 AtomParser (com.google.api.client.xml.atom.AtomParser)2 PendingIntent (android.app.PendingIntent)1 ContentProviderClient (android.content.ContentProviderClient)1 Cursor (android.database.Cursor)1 RemoteException (android.os.RemoteException)1 NotificationCompat (android.support.v4.app.NotificationCompat)1 NotificationManagerCompat (android.support.v4.app.NotificationManagerCompat)1 ListView (android.widget.ListView)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1