com.twitter.sdk.android.core.Callback Java Examples

The following examples show how to use com.twitter.sdk.android.core.Callback. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TwitterAuthClient.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Requests authorization.
 *
 * @param activity The {@link android.app.Activity} context to use for the authorization flow.
 * @param callback The callback interface to invoke when authorization completes.
 * @throws java.lang.IllegalArgumentException if activity or callback is null.
 */
public void authorize(Activity activity, Callback<TwitterSession> callback) {
    if (activity == null) {
        throw new IllegalArgumentException("Activity must not be null.");
    }
    if (callback == null) {
        throw new IllegalArgumentException("Callback must not be null.");
    }

    if (activity.isFinishing()) {
        Twitter.getLogger()
                .e(TwitterCore.TAG, "Cannot authorize, activity is finishing.", null);
    } else {
        handleAuthorize(activity, callback);
    }
}
 
Example #2
Source File: TwitterServiceImpl.java    From twittererer with Apache License 2.0 6 votes vote down vote up
public Observable<Boolean> sendTweet(String tweetText) {
    return Observable.create(subscriber -> {
        Callback<Tweet> callback = new Callback<Tweet>() {
            @Override
            public void success(Result<Tweet> result) {
                Log.i(TAG, "Tweet tweeted");
                subscriber.onNext(true);
            }

            @Override
            public void failure(TwitterException e) {
                Log.e(TAG, e.getMessage(), e);
                subscriber.onError(e);
            }
        };

        getStatusesService().update(tweetText, null, null, null, null, null, null, null, null).enqueue(callback);
    });
}
 
Example #3
Source File: TwitterNetwork.java    From EasyLogin with MIT License 6 votes vote down vote up
private void requestEmail(final TwitterSession session, final AccessToken tempToken) {
    TwitterAuthClient authClient = new TwitterAuthClient();
    authClient.requestEmail(session, new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            final String email = result.data;
            if (TextUtils.isEmpty(email)) {
                logout();
                callLoginFailure("Before fetching an email, ensure that 'Request email addresses from users' is checked for your Twitter app.");
                return;
            }
            accessToken = new AccessToken.Builder(tempToken).email(email).build();
            callLoginSuccess();
        }

        @Override
        public void failure(TwitterException exception) {
            Log.e("TwitterNetwork", "Before fetching an email, ensure that 'Request email addresses from users' is checked for your Twitter app.");
            callLoginFailure(exception.getMessage());
        }
    });
}
 
Example #4
Source File: OAuth1aServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallbackWrapperSuccess_iOException() throws IOException {
    final Callback<OAuthResponse> callback = new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            fail();
        }

        @Override
        public void failure(TwitterException exception) {
            assertNotNull(exception);
        }
    };
    final Callback<ResponseBody> callbackWrapper = service.getCallbackWrapper(callback);
    final ResponseBody responseBody = ResponseBody.create(MediaType.parse("application/json"), "");
    callbackWrapper.success(new Result<>(responseBody, Response.success(responseBody)));
}
 
Example #5
Source File: TweetView.java    From react-native-twitterkit with MIT License 6 votes vote down vote up
private void loadTweet() {
  LogUtils.d(TAG, "loadTweet, tweetId = " + tweetId);

  TweetUtils.loadTweet(tweetId, new Callback<Tweet>() {
    @Override
    public void success(Result<Tweet> result) {
      LogUtils.d(TAG, "loadTweet, success");
      Tweet selectedTweet = result.data;
      setTweet(selectedTweet);
      handleSuccess();
    }

    @Override
    public void failure(TwitterException exception) {
      LogUtils.d(TAG, "loadTweet, failure");
      // TODO send message
      handleError();
    }
  });
}
 
Example #6
Source File: TimelineObservable.java    From photosearcher with Apache License 2.0 6 votes vote down vote up
public void next(Long maxPosition) {
    if (!mTimelineStateHolder.startTimelineRequest()) {
        return;
    }
    mTimeline.next(maxPosition, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            mTimelineStateHolder.setNextCursor(result.data.timelineCursor);
            mTweets.addAll(0, result.data.items);

            mNextSubject.onNext(new DataSetInsertResult(0, result.data.items.size()));

            mTimelineStateHolder.finishTimelineRequest();
        }

        @Override
        public void failure(TwitterException e) {
            mNextSubject.onError(e);

            mTimelineStateHolder.finishTimelineRequest();
        }
    });
}
 
Example #7
Source File: TimelineObservable.java    From photosearcher with Apache License 2.0 6 votes vote down vote up
private void fetchPrevious(Long minPosition) {
    mTimeline.previous(minPosition, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            mTimelineStateHolder.setPreviousCursor(result.data.timelineCursor);
            if (mRefreshing) {
                mTweets.clear();
            }
            int position = mTweets.size();
            mTweets.addAll(result.data.items);

            mPreviousSubject.onNext(new DataSetInsertResult(position, result.data.items.size()));

            mTimelineStateHolder.finishTimelineRequest();
            mRefreshing = false;
        }

        @Override
        public void failure(TwitterException e) {
            mPreviousSubject.onError(e);

            mTimelineStateHolder.finishTimelineRequest();
            mRefreshing = false;
        }
    });
}
 
Example #8
Source File: AuthStateTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testBeginAuthorize_authHandlerCompareAndSetFails() {
    final AuthState authState = new AuthState();
    final boolean result = authState.beginAuthorize(mockActivity,
            new AuthHandler(mock(TwitterAuthConfig.class), mock(Callback.class),
                    TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE) {
                @Override
                public boolean authorize(Activity activity) {
                    // We use this opportunity to set authState's authHandlerRef so that we
                    // can verify behavior when compare and set fails. This is done because
                    // AtomicReference has methods that cannot be mocked.
                    authState.authHandlerRef.set(mock(AuthHandler.class));
                    return true;
                }
            });
    assertFalse(result);
}
 
Example #9
Source File: TweetTimelineListAdapterTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
public void testConstructor_withActionCallback() {
    final TimelineDelegate<Tweet> mockTimelineDelegate = mock(TestTimelineDelegate.class);
    final Callback<Tweet> mockCallback = mock(Callback.class);
    final TweetUi tweetUi = mock(TweetUi.class);
    listAdapter = new TweetTimelineListAdapter(getContext(), mockTimelineDelegate, ANY_STYLE,
            mockCallback, tweetUi);
    // assert that
    // - developer callback wrapped in a ReplaceTweetCallback
    if (listAdapter.actionCallback instanceof TweetTimelineListAdapter.ReplaceTweetCallback) {
        final TweetTimelineListAdapter.ReplaceTweetCallback replaceCallback
                = (TweetTimelineListAdapter.ReplaceTweetCallback) listAdapter.actionCallback;
        assertEquals(mockTimelineDelegate, replaceCallback.delegate);
        assertEquals(mockCallback, replaceCallback.cb);
    } else {
        fail("Expected actionCallback to be wrapped in ReplaceTweetCallback");
    }
}
 
Example #10
Source File: OAuth1aServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallbackWrapperSuccess_noToken() throws IOException {
    final String response = "oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo&"
            + "screen_name=test&user_id=1";
    final Callback<OAuthResponse> callback = new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            fail();
        }

        @Override
        public void failure(TwitterException exception) {
            assertNotNull(exception);
        }
    };
    setupCallbackWrapperTest(response, callback);
}
 
Example #11
Source File: OAuth1aServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testCallbackWrapperSuccess() throws IOException {
    final String response = "oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4&"
            + "oauth_token_secret=PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo&"
            + "screen_name=test&user_id=1";
    final Callback<OAuthResponse> callback = new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            final OAuthResponse authResponse = result.data;
            assertEquals("7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4",
                    authResponse.authToken.token);
            assertEquals("PbKfYqSryyeKDWz4ebtY3o5ogNLG11WJuZBc9fQrQo",
                    authResponse.authToken.secret);
            assertEquals("test", authResponse.userName);
            assertEquals(1L, authResponse.userId);
        }

        @Override
        public void failure(TwitterException exception) {
            fail();
        }
    };
    setupCallbackWrapperTest(response, callback);
}
 
Example #12
Source File: TwitterAuthClientTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestEmail_withSuccess() {
    final User user = new UserBuilder().setEmail(TEST_EMAIL).build();
    final Call<User> call = Calls.response(user);
    setupMockAccountService(call);

    authClient.requestEmail(mock(TwitterSession.class), new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            assertEquals(TEST_EMAIL, result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            fail("Expected Callback#success to be called");
        }
    });
}
 
Example #13
Source File: FixedTweetTimelineTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testNext_succeedsWithFixedTweets() {
    final FixedTweetTimeline timeline = new FixedTweetTimeline(fixedTweets);
    timeline.next(ANY_ID, new Callback<TimelineResult<Tweet>>() {
        @Override
        public void success(Result<TimelineResult<Tweet>> result) {
            assertEquals(fixedTweets, result.data.items);
            assertEquals((Long) TestFixtures.TEST_PHOTO_TWEET.getId(),
                    result.data.timelineCursor.minPosition);
            assertEquals((Long) TestFixtures.TEST_TWEET.getId(),
                    result.data.timelineCursor.maxPosition);
            assertNull(result.response);
        }
        @Override
        public void failure(TwitterException exception) {
            fail("Expected FixedTweetTimeline next to always succeed.");
        }
    });
}
 
Example #14
Source File: TweetActivity.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * loadTweets wraps TweetUtils.loadTweets to use a callback that ensures each view is given
 * a known id to simplify UI automation testing.
 */
private void loadTweets(final List<Long> tweetIds, final ViewGroup container,
                        final List<Integer> viewIds) {
    TweetUtils.loadTweets(tweetIds, new Callback<List<Tweet>>() {
        @Override
        public void success(Result<List<Tweet>> result) {
            final Context context = getActivity();
            if (context == null) return;
            for (int i = 0; i < result.data.size(); i++) {
                final BaseTweetView tv = new CompactTweetView(context, result.data.get(i),
                        R.style.tw__TweetDarkWithActionsStyle);
                tv.setOnActionCallback(actionCallback);
                tv.setId(viewIds.get(i));
                container.addView(tv);
            }
        }

        @Override
        public void failure(TwitterException exception) {
            Log.e(TAG, "loadTweets failure " + tweetIds, exception);
        }
    });
}
 
Example #15
Source File: TweetUploadService.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
void uploadTweet(final TwitterSession session, final String text, final Uri imageUri) {
    if (imageUri != null) {
        uploadMedia(session, imageUri, new Callback<Media>() {
            @Override
            public void success(Result<Media> result) {
                uploadTweetWithMedia(session, text, result.data.mediaIdString);
            }

            @Override
            public void failure(TwitterException exception) {
                fail(exception);
            }

        });
    } else {
        uploadTweetWithMedia(session, text, null);
    }
}
 
Example #16
Source File: OAuth2ServiceTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestGuestAuthToken_appAuthFailure() {

    service.api = new MockOAuth2Api() {
        @Override
        public Call<OAuth2Token> getAppAuthToken(@Header(OAuthConstants.HEADER_AUTHORIZATION) String auth,
                @Field(OAuthConstants.PARAM_GRANT_TYPE) String grantType) {
            return Calls.failure(new IOException());
        }
    };

    service.requestGuestAuthToken(new Callback<GuestAuthToken>() {
        @Override
        public void success(Result<GuestAuthToken> result) {
            fail();
        }

        @Override
        public void failure(TwitterException error) {
            assertNotNull(error);
        }
    });
}
 
Example #17
Source File: LoginActivity.java    From cannonball-android with Apache License 2.0 6 votes vote down vote up
private void setUpTwitterButton() {
    twitterButton = (TwitterLoginButton) findViewById(R.id.twitter_button);
    twitterButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            SessionRecorder.recordSessionActive("Login: twitter account active", result.data);
            Answers.getInstance().logLogin(new LoginEvent().putMethod("Twitter").putSuccess(true));
            startThemeChooser();
        }

        @Override
        public void failure(TwitterException exception) {
            Answers.getInstance().logLogin(new LoginEvent().putMethod("Twitter").putSuccess(false));
            Toast.makeText(getApplicationContext(),
                    getResources().getString(R.string.toast_twitter_signin_fail),
                    Toast.LENGTH_SHORT).show();
            Crashlytics.logException(exception);
        }
    });
}
 
Example #18
Source File: TwitterAuthClientTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Test
public void testRequestEmail_withFailure() {
    final IOException networkException = new IOException("Network failure");
    final Call<User> call = Calls.failure(networkException);
    setupMockAccountService(call);

    authClient.requestEmail(mock(TwitterSession.class), new Callback<String>() {
        @Override
        public void success(Result<String> result) {
            fail("Expected Callback#failure to be called");
        }

        @Override
        public void failure(TwitterException exception) {
            assertEquals(exception.getCause(), networkException);
        }
    });
}
 
Example #19
Source File: TwitterServiceImpl.java    From twittererer with Apache License 2.0 6 votes vote down vote up
public Observable<List<TimelineItem>> getTimelineItems() {
    return Observable.create(subscriber -> {
        Callback<List<Tweet>> callback = new Callback<List<Tweet>>() {
            @Override
            public void success(Result<List<Tweet>> result) {
                Log.i(TAG, "Got the tweets, buddy!");
                subscriber.onNext(TimelineConverter.fromTweets(result.data, DateTime.now()));
            }

            @Override
            public void failure(TwitterException e) {
                Log.e(TAG, e.getMessage(), e);
                subscriber.onError(e);
            }
        };

        getStatusesService().homeTimeline(null, null, null, null, null, null, null).enqueue(callback);
    });
}
 
Example #20
Source File: TimelineDelegateTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Override
public void next(Long sinceId, Callback<TimelineResult<TestItem>> cb) {
    final List<TestItem> testItems = new ArrayList<>();
    TestItem.populateList(testItems, numItems);
    final TimelineResult<TestItem> timelineResult
            = new TimelineResult<>(new TimelineCursor(minPosition, maxPosition), testItems);
    cb.success(new Result<>(timelineResult, null));
}
 
Example #21
Source File: TimelineDelegateTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadPrevious() {
    delegate = new TimelineDelegate<>(mockTimeline);
    final Callback<TimelineResult<TestItem>> testCb = delegate.new PreviousCallback(
            delegate.timelineStateHolder);
    delegate.loadPrevious(TEST_MAX_POSITION, testCb);
    verify(mockTimeline).previous(TEST_MAX_POSITION, testCb);
}
 
Example #22
Source File: SearchTimelineTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrevious_createsCorrectRequest() {
    final SearchTimeline timeline = spy(new SearchTimeline(twitterCore, TEST_QUERY,
            TEST_GEOCODE, TEST_RESULT_TYPE, TEST_LANG, TEST_ITEMS_PER_REQUEST,
            TEST_UNTIL_DATE));
    timeline.previous(TEST_MAX_ID, mock(Callback.class));
    // intentionally decrementing the maxId which is passed through to the request
    verify(timeline).createSearchRequest(isNull(Long.class),
            eq(TEST_MAX_ID - 1));
}
 
Example #23
Source File: OAuthControllerTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewAccessTokenCallback_failure() {
    final Callback<OAuthResponse> callback = controller.newRequestAccessTokenCallback();
    final TwitterException mockException = mock(TwitterException.class);
    callback.failure(mockException);
    verifyOnCompleteWithError("Failed to get access token");
}
 
Example #24
Source File: SearchTimelineTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testNext_createsCorrectRequest() {
    final SearchTimeline timeline = spy(new SearchTimeline(twitterCore, TEST_QUERY,
            TEST_GEOCODE, TEST_RESULT_TYPE, TEST_LANG, TEST_ITEMS_PER_REQUEST,
            TEST_UNTIL_DATE));
    timeline.next(TEST_SINCE_ID, mock(Callback.class));
    verify(timeline).createSearchRequest(eq(TEST_SINCE_ID),
            isNull(Long.class));
}
 
Example #25
Source File: CollectionTimelineTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testPrevious_createsCorrectRequest() {
    final CollectionTimeline timeline = spy(new CollectionTimeline(twitterCore,
            TEST_COLLECTION_ID, TEST_ITEMS_PER_REQUEST));
    timeline.next(TEST_MAX_POSITION, mock(Callback.class));
    verify(timeline).createCollectionRequest(eq(TEST_MAX_POSITION), isNull(Long.class));
}
 
Example #26
Source File: TweetTimelineListAdapter.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
TweetTimelineListAdapter(Context context, TimelineDelegate<Tweet> delegate, int styleResId,
                         Callback<Tweet> cb, TweetUi tweetUi) {
    super(context, delegate);
    this.styleResId = styleResId;
    this.actionCallback = new ReplaceTweetCallback(delegate, cb);
    this.tweetUi = tweetUi;
}
 
Example #27
Source File: TimelineDelegateTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadNext_respectsRequestInFlight() {
    delegate = new TimelineDelegate<>(mockTimeline);
    delegate.timelineStateHolder.startTimelineRequest();
    final Callback<TimelineResult<TestItem>> mockCallback = mock(Callback.class);
    delegate.loadNext(ANY_POSITION, mockCallback);
    final ArgumentCaptor<TwitterException> exceptionCaptor
            = ArgumentCaptor.forClass(TwitterException.class);
    verifyZeroInteractions(mockTimeline);
    verify(mockCallback).failure(exceptionCaptor.capture());
    assertEquals(exceptionCaptor.getValue().getMessage(), REQUIRED_REQUEST_IN_FLIGHT_ERROR);
}
 
Example #28
Source File: TweetUtils.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
/**
 * Loads a single Tweet by id.
 * @param tweetId Tweet id
 * @param cb callback
 */
public static void loadTweet(final long tweetId, final Callback<Tweet> cb) {
    TweetUi.getInstance().getTweetRepository().loadTweet(tweetId,
            new LoggingCallback<Tweet>(cb, Twitter.getLogger()) {
                @Override
                public void success(Result<Tweet> result) {
                    if (cb != null) {
                        cb.success(result);
                    }
                }
            });
}
 
Example #29
Source File: LoggingCallbackTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Test
public void testFailure_callsCb() {
    final Callback<Tweet> developerCallback = mock(Callback.class);
    final LoggingCallback<Tweet> cb
            = new TestLoggingCallback<>(developerCallback, mock(Logger.class));
    cb.failure(mock(TwitterException.class));
    verify(developerCallback).failure(any(TwitterException.class));
}
 
Example #30
Source File: UserTimeline.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
/**
 * Loads Tweets with id less than (older than) maxId.
 * @param maxId maximum id of the Tweets to load (exclusive).
 * @param cb callback.
 */
@Override
public void previous(Long maxId, Callback<TimelineResult<Tweet>> cb) {
    // user timeline api provides results which are inclusive, decrement the maxId to get
    // exclusive results
    createUserTimelineRequest(null, decrementMaxId(maxId)).enqueue(new TweetsCallback(cb));
}