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

The following examples show how to use com.twitter.sdk.android.core.Twitter. 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: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
public void testOnClick_activityNullDebuggableTrue() throws Exception {
    Twitter.initialize(new TwitterConfig.Builder(getContext())
            .executorService(mock(ExecutorService.class))
            .debug(true)
            .build());
    loginButton = new TwitterLoginButton(getContext(), null, 0, mockAuthClient) {
        // This is to allow us to test TwitterLoginButton without having to set up a real
        // activity.
        @Override
        protected Activity getActivity() {
            return null;
        }
    };
    loginButton.setCallback(mockCallback);

    try {
        loginButton.performClick();
        fail("onClick should throw an exception when called and there is no activity");
    } catch (IllegalStateException e) {
        assertEquals(TwitterLoginButton.ERROR_MSG_NO_ACTIVITY, e.getMessage());
    } finally {
        TwitterCoreTestUtils.resetTwitterCore();
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #2
Source File: TweetUiTestCase.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();
    createMocks();

    // Initialize Fabric with mock executor so that kit#doInBackground() will not be called
    // during kit initialization.
    final TwitterConfig config = new TwitterConfig.Builder(getContext())
            .logger(new DefaultLogger(Log.DEBUG))
            .executorService(mock(ThreadPoolExecutor.class))
            .build();

    Twitter.initialize(config);

    final TwitterCore twitterCore = TwitterCoreTestUtils.createTwitterCore(
            new TwitterAuthConfig("", ""), clients, apiClient);

    tweetUi = TweetUi.getInstance();
    final TweetRepository tweetRepository = new TweetRepository(mainHandler,
            mock(SessionManager.class), twitterCore);
    tweetUi.setTweetRepository(tweetRepository);
    tweetUi.setImageLoader(picasso);
}
 
Example #3
Source File: OAuthController.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Package private for testing.
 */
Callback<OAuthResponse> newRequestTempTokenCallback() {
    return new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            requestToken = result.data.authToken;
            final String authorizeUrl = oAuth1aService.getAuthorizeUrl(requestToken);
            // Step 2. Redirect user to web view to complete authorization flow.
            Twitter.getLogger().d(TwitterCore.TAG,
                    "Redirecting user to web view to complete authorization flow");
            setUpWebView(webView,
                    new OAuthWebViewClient(oAuth1aService.buildCallbackUrl(authConfig),
                            OAuthController.this), authorizeUrl, new OAuthWebChromeClient());
        }

        @Override
        public void failure(TwitterException error) {
            Twitter.getLogger().e(TwitterCore.TAG,
                    "Failed to get request token", error);
            // Create new exception that can be safely serialized since Retrofit errors may
            // throw a NotSerializableException.
            handleAuthError(AuthHandler.RESULT_CODE_ERROR,
                    new TwitterAuthException("Failed to get request token"));
        }
    };
}
 
Example #4
Source File: OAuthController.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
private void handleWebViewSuccess(Bundle bundle) {
    Twitter.getLogger().d(TwitterCore.TAG, "OAuth web view completed successfully");
    if (bundle != null) {
        final String verifier = bundle.getString(OAuthConstants.PARAM_VERIFIER);
        if (verifier != null) {
            // Step 3. Convert the request token to an access token.
            Twitter.getLogger().d(TwitterCore.TAG,
                    "Converting the request token to an access token.");
            oAuth1aService.requestAccessToken(newRequestAccessTokenCallback(),
                    requestToken, verifier);
            return;
        }
    }

    // If we get here, we failed to complete authorization.
    Twitter.getLogger().e(TwitterCore.TAG,
            "Failed to get authorization, bundle incomplete " + bundle, null);
    handleAuthError(AuthHandler.RESULT_CODE_ERROR,
            new TwitterAuthException("Failed to get authorization, bundle incomplete"));
}
 
Example #5
Source File: OAuthController.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * Package private for testing.
 */
Callback<OAuthResponse> newRequestAccessTokenCallback() {
    return new Callback<OAuthResponse>() {
        @Override
        public void success(Result<OAuthResponse> result) {
            final Intent data = new Intent();
            final OAuthResponse response = result.data;
            data.putExtra(AuthHandler.EXTRA_SCREEN_NAME, response.userName);
            data.putExtra(AuthHandler.EXTRA_USER_ID, response.userId);
            data.putExtra(AuthHandler.EXTRA_TOKEN, response.authToken.token);
            data.putExtra(AuthHandler.EXTRA_TOKEN_SECRET,
                    response.authToken.secret);
            listener.onComplete(Activity.RESULT_OK, data);
        }

        @Override
        public void failure(TwitterException error) {
            Twitter.getLogger().e(TwitterCore.TAG, "Failed to get access token", error);
            // Create new exception that can be safely serialized since Retrofit errors may
            // throw a NotSerializableException.
            handleAuthError(AuthHandler.RESULT_CODE_ERROR,
                    new TwitterAuthException("Failed to get access token"));
        }
    };
}
 
Example #6
Source File: AbstractTweetView.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
protected LinkClickListener getLinkClickListener() {
    if (linkClickListener == null) {
        linkClickListener = url -> {
            if (TextUtils.isEmpty(url)) return;

            if (tweetLinkClickListener != null) {
                tweetLinkClickListener.onLinkClick(tweet, url);
            } else {
                final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                if (!IntentUtils.safeStartActivity(getContext(), intent)) {
                    Twitter.getLogger().e(TweetUi.LOGTAG,
                            "Activity cannot be found to open URL");
                }
            }
        };
    }
    return linkClickListener;
}
 
Example #7
Source File: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
public void testConstructor_twitterStarted() throws Exception {
    try {
        Twitter.initialize(setUpLogTest());

        final TwitterLoginButton button = new TwitterLoginButton(getContext()) {
            @Override
            protected Activity getActivity() {
                return mock(Activity.class);
            }
        };

        final Logger logger = Twitter.getLogger();
        verify(logger, never()).e(eq(TwitterLoginButton.TAG), anyString());
        assertTrue(button.isEnabled());

    } finally {
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #8
Source File: ExecutorUtils.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
static void addDelayedShutdownHook(final String serviceName,
        final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) {
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        try {
            service.shutdown();
            if (!service.awaitTermination(terminationTimeout, timeUnit)) {
                Twitter.getLogger().d(Twitter.TAG, serviceName + " did not shutdown in the"
                        + " allocated time. Requesting immediate shutdown.");
                service.shutdownNow();
            }
        } catch (InterruptedException e) {
            Twitter.getLogger().d(Twitter.TAG, String.format(Locale.US,
                    "Interrupted while waiting for %s to shut down." +
                            " Requesting immediate shutdown.",
                    serviceName));
            service.shutdownNow();
        }
    }, "Twitter Shutdown Hook for " + serviceName));
}
 
Example #9
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 #10
Source File: BaseTweetView.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
/**
 * LoadTweet will trigger a request to the Twitter API and hydrate the view with the result.
 * In the event of an error it will call the listener that was provided to setOnTwitterApiError.
 */
private void loadTweet() {
    final long tweetId = getTweetId();
    // create a callback to setTweet on the view or log a failure to load the Tweet
    final Callback<Tweet> repoCb = new Callback<Tweet>() {
        @Override
        public void success(Result<Tweet> result) {
            setTweet(result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            Twitter.getLogger().d(TAG,
                    String.format(Locale.ENGLISH, TweetUtils.LOAD_TWEET_DEBUG, tweetId));
        }
    };
    dependencyProvider.getTweetUi().getTweetRepository().loadTweet(getTweetId(), repoCb);
}
 
Example #11
Source File: PlayerController.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
void prepare(PlayerActivity.PlayerItem item) {
    try {
        setUpCallToAction(item);
        setUpMediaControl(item.looping, item.showVideoControls);
        final View.OnTouchListener listener = SwipeToDismissTouchListener
                .createFromView(videoView, callback);
        videoView.setOnTouchListener(listener);
        videoView.setOnPreparedListener(mediaPlayer -> videoProgressView.setVisibility(View.GONE));
        videoView.setOnInfoListener((mediaPlayer, what, extra) -> {
            if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
                videoProgressView.setVisibility(View.GONE);
                return true;
            } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
                videoProgressView.setVisibility(View.VISIBLE);
                return true;
            }
            return false;
        });
        final Uri uri = Uri.parse(item.url);
        videoView.setVideoURI(uri, item.looping);
        videoView.requestFocus();
    } catch (Exception e) {
        Twitter.getLogger().e(TAG, "Error occurred during video playback", e);
    }
}
 
Example #12
Source File: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
public void testOnClick_activityNullDebuggableFalse() throws Exception {
    Twitter.initialize(setUpLogTest());
    loginButton = new TwitterLoginButton(getContext(), null, 0, mockAuthClient) {
        // This is to allow us to test TwitterLoginButton without having to set up a real
        // activity.
        @Override
        protected Activity getActivity() {
            return null;
        }
    };
    loginButton.setCallback(mockCallback);

    try {
        loginButton.performClick();
        assertLogMessage(TwitterLoginButton.ERROR_MSG_NO_ACTIVITY);
    } finally {
        TwitterCoreTestUtils.resetTwitterCore();
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #13
Source File: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
public void testOnClick_activityFinishingDebuggableFalse() throws Exception {
    Twitter.initialize(setUpLogTest());
    loginButton = new TwitterLoginButton(getContext(), null, 0, mockAuthClient) {
        // This is to allow us to test TwitterLoginButton without having to set up a real
        // activity.
        @Override
        protected Activity getActivity() {
            final Activity mockActivity = mock(Activity.class);
            when(mockActivity.isFinishing()).thenReturn(true);
            return mockActivity;
        }
    };
    loginButton.setCallback(mockCallback);

    try {
        loginButton.performClick();
        assertLogMessage(TwitterLoginButton.ERROR_MSG_NO_ACTIVITY);
    } finally {
        TwitterCoreTestUtils.resetTwitterCore();
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #14
Source File: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
public void testGetTwitterAuthClient() throws Exception {
    try {
        Twitter.initialize(new TwitterConfig.Builder(getContext())
                .executorService(mock(ExecutorService.class))
                .build());

        final TwitterLoginButton button = new TwitterLoginButton(getContext()) {
            @Override
            protected Activity getActivity() {
                return mock(Activity.class);
            }
        };
        final TwitterAuthClient client = button.getTwitterAuthClient();
        assertNotNull(client);

    } finally {
        TwitterCoreTestUtils.resetTwitterCore();
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #15
Source File: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 6 votes vote down vote up
public void testGetTwitterAuthClient_duplicateCalls() throws Exception {
    try {
        Twitter.initialize(new TwitterConfig.Builder(getContext())
                .executorService(mock(ExecutorService.class))
                .build());

        final TwitterLoginButton button = new TwitterLoginButton(getContext()) {
            @Override
            protected Activity getActivity() {
                return mock(Activity.class);
            }
        };
        final TwitterAuthClient client = button.getTwitterAuthClient();
        final TwitterAuthClient client2 = button.getTwitterAuthClient();
        assertSame(client, client2);

    } finally {
        TwitterCoreTestUtils.resetTwitterCore();
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #16
Source File: LoginActivity.java    From Simple-Blog-App with MIT License 6 votes vote down vote up
private void twitter() {
    TwitterConfig config = new TwitterConfig.Builder(this)
            .logger(new DefaultLogger(Log.DEBUG))
            .twitterAuthConfig(new TwitterAuthConfig(getResources().getString(R.string.com_twitter_sdk_android_CONSUMER_KEY), getResources().getString(R.string.com_twitter_sdk_android_CONSUMER_SECRET)))
            .debug(true)
            .build();
    Twitter.initialize(config);
    twitterLoginButton.setCallback(new Callback<TwitterSession>() {
        @Override
        public void success(Result<TwitterSession> result) {
            Log.d(TAG, "twitterLogin:success" + result);
            handleTwitterSession(result.data);
        }

        @Override
        public void failure(TwitterException exception) {
            Log.w(TAG, "twitterLogin:failure", exception);

        }
    });
}
 
Example #17
Source File: ReactTwitterKitPackage.java    From react-native-twitterkit with MIT License 6 votes vote down vote up
public void initFabric(Context reactContext) {
  if (consumerKey == null || consumerSecret == null) {
    return;
  }

  TwitterAuthConfig authConfig
          = new TwitterAuthConfig(consumerKey, consumerSecret);

  final TwitterConfig config = new TwitterConfig.Builder(reactContext)
          .twitterAuthConfig(authConfig)
          .debug(true)
          .build();
  Twitter.initialize(config);
  new Thread(new Runnable() {
    @Override
    public void run() {
      TweetUi.getInstance();
      Log.i("ReactTwitterKit", "TweetUi instance initialized");
    }
  }).start();
}
 
Example #18
Source File: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
public void testOnClick_callbackNullDebuggableTrue() throws Exception {
    Twitter.initialize(new TwitterConfig.Builder(getContext())
            .executorService(mock(ExecutorService.class))
            .debug(true)
            .build());
    try {
        loginButton.performClick();
        fail("onClick should throw an exception when called and there is no callback");
    } catch (IllegalStateException e) {
        assertEquals("Callback must not be null, did you call setCallback?", e.getMessage());
    } finally {
        TwitterCoreTestUtils.resetTwitterCore();
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #19
Source File: TwitterAuthClient.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
private boolean authorizeUsingSSO(Activity activity, CallbackWrapper callbackWrapper) {
    if (SSOAuthHandler.isAvailable(activity)) {
        Twitter.getLogger().d(TwitterCore.TAG, "Using SSO");
        return authState.beginAuthorize(activity,
                new SSOAuthHandler(authConfig, callbackWrapper, authConfig.getRequestCode()));
    } else {
        return false;
    }
}
 
Example #20
Source File: AuthState.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
public boolean beginAuthorize(Activity activity, AuthHandler authHandler) {
    boolean result = false;
    if (isAuthorizeInProgress()) {
        Twitter.getLogger().w(TwitterCore.TAG, "Authorize already in progress");
    } else if (authHandler.authorize(activity)) {
        result = authHandlerRef.compareAndSet(null, authHandler);
        if (!result) {
            Twitter.getLogger().w(TwitterCore.TAG, "Failed to update authHandler, authorize"
                    + " already in progress.");
        }
    }
    return result;
}
 
Example #21
Source File: FileStoreImpl.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
boolean isExternalStorageAvailable() {
    final String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        Twitter.getLogger().w(Twitter.TAG,
                "External Storage is not mounted and/or writable\n" +
                        "Have you declared android.permission.WRITE_EXTERNAL_STORAGE " +
                        "in the manifest?");
        return false;
    }

    return true;
}
 
Example #22
Source File: FileStoreImpl.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
File prepare(File file) {
    if (file != null) {
        if (file.exists() || file.mkdirs()) {
            return file;
        } else {
            Twitter.getLogger().w(Twitter.TAG, "Couldn't create file");
        }
    } else {
        Twitter.getLogger().d(Twitter.TAG, "Null File");
    }
    return null;
}
 
Example #23
Source File: TwitterAuthClient.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
/**
 * Call this method when {@link android.app.Activity#onActivityResult(int, int, Intent)}
 * is called to complete the authorization flow.
 *
 * @param requestCode the request code used for SSO
 * @param resultCode the result code returned by the SSO activity
 * @param data the result data returned by the SSO activity
 */
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Twitter.getLogger().d(TwitterCore.TAG,
            "onActivityResult called with " + requestCode + " " + resultCode);
    if (!authState.isAuthorizeInProgress()) {
        Twitter.getLogger().e(TwitterCore.TAG, "Authorize not in progress", null);
    } else {
        final AuthHandler authHandler = authState.getAuthHandler();
        if (authHandler != null &&
                authHandler.handleOnActivityResult(requestCode, resultCode, data)) {
            authState.endAuthorize();
        }
    }
}
 
Example #24
Source File: TwitterLoginButton.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
private void checkTwitterCoreAndEnable() {
    //Default (Enabled) in edit mode
    if (isInEditMode()) return;

    try {
        TwitterCore.getInstance();
    } catch (IllegalStateException ex) {
        //Disable if TwitterCore hasn't started
        Twitter.getLogger().e(TAG, ex.getMessage());
        setEnabled(false);
    }
}
 
Example #25
Source File: CommonUtils.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
/**
 *  If {@link Twitter#isDebug()}, throws an IllegalStateException,
 *  else logs a warning.
 *
 * @param logTag the log tag to use for logging
 * @param errorMsg the error message
 */
public static void logOrThrowIllegalStateException(String logTag, String errorMsg) {
    if (Twitter.isDebug()) {
        throw new IllegalStateException(errorMsg);
    } else {
        Twitter.getLogger().w(logTag, errorMsg);
    }
}
 
Example #26
Source File: TwitterLoginButtonTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
public void testOnClick_callbackNullDebuggableFalse() throws Exception {
    Twitter.initialize(setUpLogTest());
    try {
        loginButton.performClick();
        assertLogMessage("Callback must not be null, did you call setCallback?");
    } finally {
        TwitterCoreTestUtils.resetTwitterCore();
        TwitterTestUtils.resetTwitter();
    }
}
 
Example #27
Source File: OAuthActivityTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    super.setUp();

    context = getInstrumentation().getTargetContext();
    Twitter.initialize(new TwitterConfig.Builder(context)
            .executorService(mock(ExecutorService.class))
            .build());
    mockController = mock(TestOAuthController.class);
}
 
Example #28
Source File: TweetComposerTest.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
public void setUp() throws Exception {
    super.setUp();
    Twitter.initialize(new TwitterConfig.Builder(getContext())
            .executorService(mock(ThreadPoolExecutor.class))
            .build());
    tweetComposer = new TweetComposer();
    tweetComposer.instance = tweetComposer;
}
 
Example #29
Source File: App.java    From twittererer with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    JodaTimeAndroid.init(this);

    Fabric.with(this, new Crashlytics());
    Twitter.initialize(new TwitterConfig.Builder(this).twitterAuthConfig(new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET)).build());

    applicationComponent = DaggerApp_ApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .build();
}
 
Example #30
Source File: TweetRepository.java    From twitter-kit-android with Apache License 2.0 5 votes vote down vote up
void favorite(final long tweetId, final Callback<Tweet> cb) {
    getUserSession(new LoggingCallback<TwitterSession>(cb, Twitter.getLogger()) {
        @Override
        public void success(Result<TwitterSession> result) {
            twitterCore.getApiClient(result.data).getFavoriteService().create(tweetId, false)
                    .enqueue(cb);
        }
    });
}