Example usage for twitter4j TwitterFactory getInstance

List of usage examples for twitter4j TwitterFactory getInstance

Introduction

In this page you can find the example usage for twitter4j TwitterFactory getInstance.

Prototype

public Twitter getInstance() 

Source Link

Document

Returns a instance associated with the configuration bound to this factory.

Usage

From source file:com.klinker.android.twitter.activities.setup.LoginActivity.java

License:Apache License

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences", 0);
    context = this;
    settings = AppSettings.getInstance(context);

    //context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH"));

    Utils.setUpTheme(context, settings);
    setContentView(R.layout.login_activity);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(settings.TWITTER_CONSUMER_KEY);
    builder.setOAuthConsumerSecret(settings.TWITTER_CONSUMER_SECRET);
    Configuration configuration = builder.build();

    TwitterFactory factory = new TwitterFactory(configuration);
    twitter = factory.getInstance();

    btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    noThanks = (Button) findViewById(R.id.dont_follow);
    title = (TextSwitcher) findViewById(R.id.welcome);
    summary = (TextSwitcher) findViewById(R.id.info);
    progDescription = (TextSwitcher) findViewById(R.id.progress_desc);
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    main = (LinearLayout) findViewById(R.id.mainLayout);

    Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
    Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

    title.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            TextView myText = new TextView(LoginActivity.this);
            myText.setTextSize(30);/*  w w w . ja v  a2  s.  co  m*/
            return myText;
        }
    });

    // set the animation type of textSwitcher
    title.setInAnimation(in);
    title.setOutAnimation(out);

    summary.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            TextView myText = new TextView(LoginActivity.this);
            myText.setTextSize(17);
            return myText;
        }
    });

    // set the animation type of textSwitcher
    summary.setInAnimation(in);
    summary.setOutAnimation(out);

    progDescription.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            TextView myText = new TextView(LoginActivity.this);
            myText.setTextSize(17);
            return myText;
        }
    });

    // set the animation type of textSwitcher
    progDescription.setInAnimation(in);
    progDescription.setOutAnimation(out);

    title.setText(getResources().getString(R.string.first_welcome));
    summary.setText(getResources().getString(R.string.first_info));

    progressBar.setProgress(100);

    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();

    mWebView = (WebView) findViewById(R.id.loginWebView);
    try {
        mWebView.getSettings().setJavaScriptEnabled(true);
    } catch (Exception e) {

    }
    mWebView.getSettings().setAppCacheEnabled(false);
    mWebView.getSettings().setSavePassword(false);
    mWebView.getSettings().setSaveFormData(false);
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            Log.v("talon_login", "url: " + url);
            if (url != null && url.startsWith("oauth:///talonforandroid")) {
                handleTwitterCallback(url);
            } else if (url.equals("https://twitter.com/")) {
                webView.loadUrl(requestUrl);
            } else {
                webView.loadUrl(url);
            }
            return true;
        }
    });

    noThanks.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new FollowMe().execute();

            btnLoginTwitter.setText(getResources().getString(R.string.back_to_timeline));
            noThanks.setVisibility(View.GONE);

            summary.setText(getResources().getString(R.string.third_info));
        }
    });

    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login_activity twitter function
            if (btnLoginTwitter.getText().toString()
                    .contains(getResources().getString(R.string.login_to_twitter))) {
                if (Utils.hasInternetConnection(context)) {
                    btnLoginTwitter.setEnabled(false);

                    new AlertDialog.Builder(context)
                            .setMessage("Twitter may display that Talon cannot authenticate any more users. "
                                    + "\n\n"
                                    + "If so, and you have logged into Talon in the past, simply hit the 'Sign In' button in the top right and it will allow you to log in as normal. "
                                    + "\n\n"
                                    + "If you have never logged into Talon, then you will have to wait to login. Twitter seems to allow more users access every few hours.")
                            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).setNegativeButton("More Info", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(
                                            "https://plus.google.com/117432358268488452276/posts/KG4AcH3YA2U")));
                                }
                            }).show();

                    new RetreiveFeedTask().execute();
                } else {
                    Toast.makeText(context, getResources().getString(R.string.no_network) + "!",
                            Toast.LENGTH_SHORT).show();
                }
            } else if (btnLoginTwitter.getText().toString()
                    .contains(getResources().getString(R.string.initial_sync))) {
                new getTimeLine().execute();
            } else if (btnLoginTwitter.getText().toString()
                    .contains(getResources().getString(R.string.no_thanks))) {
                btnLoginTwitter.setText(getResources().getString(R.string.back_to_timeline));
                noThanks.setVisibility(View.GONE);

                summary.setText(getResources().getString(R.string.third_info));
            } else {

                if (settings.timelineRefresh != 0) { // user only wants manual
                    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

                    long now = new Date().getTime();
                    long alarm = now + settings.timelineRefresh;

                    PendingIntent pendingIntent = PendingIntent.getService(context,
                            HomeFragment.HOME_REFRESH_ID, new Intent(context, TimelineRefreshService.class), 0);

                    am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.timelineRefresh, pendingIntent);

                    now = new Date().getTime();
                    alarm = now + settings.mentionsRefresh;

                    PendingIntent pendingIntent2 = PendingIntent.getService(context,
                            MentionsFragment.MENTIONS_REFRESH_ID,
                            new Intent(context, MentionsRefreshService.class), 0);

                    am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.mentionsRefresh, pendingIntent2);

                    alarm = now + settings.dmRefresh;

                    PendingIntent pendingIntent3 = PendingIntent.getService(context, DMFragment.DM_REFRESH_ID,
                            new Intent(context, DirectMessageRefreshService.class), 0);
                    am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.dmRefresh, pendingIntent3);
                }

                // set up the autotrim
                AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                long now = new Date().getTime();
                long alarm = now + AlarmManager.INTERVAL_DAY;
                Log.v("alarm_date", "auto trim " + new Date(alarm).toString());
                PendingIntent pendingIntent = PendingIntent.getService(context, 161,
                        new Intent(context, TrimDataService.class), 0);
                am.set(AlarmManager.RTC_WAKEUP, alarm, pendingIntent);

                finish();

                Intent timeline = new Intent(context, MainActivity.class);
                timeline.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                timeline.putExtra("tutorial", true);
                sharedPrefs.edit().putBoolean("should_refresh", false).commit();
                sharedPrefs.edit().putBoolean("refresh_me", true).commit();
                sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();
                sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit();
                sharedPrefs.edit().putBoolean("need_new_dm", false).commit();
                sharedPrefs.edit().putBoolean("need_clean_databases_version_1_3_0", false).commit();
                sharedPrefs.edit().putBoolean("setup_v_two", true).commit();
                sharedPrefs.edit().putBoolean("version_2_2_7_1", false).commit();
                AppSettings.invalidate();
                startActivity(timeline);
            }

        }
    });
}

From source file:com.klinker.android.twitter.ui.setup.LoginActivity.java

License:Apache License

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    sharedPrefs = getSharedPreferences("com.klinker.android.twitter_world_preferences",
            Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
    context = this;
    settings = AppSettings.getInstance(context);

    //context.sendBroadcast(new Intent("com.klinker.android.twitter.STOP_PUSH"));

    Utils.setUpTheme(context, settings);
    setContentView(R.layout.login_activity);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(settings.TWITTER_CONSUMER_KEY);
    builder.setOAuthConsumerSecret(settings.TWITTER_CONSUMER_SECRET);
    Configuration configuration = builder.build();

    TwitterFactory factory = new TwitterFactory(configuration);
    twitter = factory.getInstance();

    btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    noThanks = (Button) findViewById(R.id.dont_follow);
    title = (TextSwitcher) findViewById(R.id.welcome);
    summary = (TextSwitcher) findViewById(R.id.info);
    progDescription = (TextSwitcher) findViewById(R.id.progress_desc);
    progressBar = (ProgressBar) findViewById(R.id.progress_bar);
    main = (LinearLayout) findViewById(R.id.mainLayout);

    Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
    Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

    title.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            TextView myText = new TextView(LoginActivity.this);
            myText.setTextSize(30);/* ww w  .  ja v a  2s.c  om*/
            return myText;
        }
    });

    // set the animation type of textSwitcher
    title.setInAnimation(in);
    title.setOutAnimation(out);

    summary.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            TextView myText = new TextView(LoginActivity.this);
            myText.setTextSize(17);
            return myText;
        }
    });

    // set the animation type of textSwitcher
    summary.setInAnimation(in);
    summary.setOutAnimation(out);

    progDescription.setFactory(new ViewSwitcher.ViewFactory() {

        public View makeView() {
            TextView myText = new TextView(LoginActivity.this);
            myText.setTextSize(17);
            return myText;
        }
    });

    // set the animation type of textSwitcher
    progDescription.setInAnimation(in);
    progDescription.setOutAnimation(out);

    title.setText(getResources().getString(R.string.first_welcome));
    summary.setText(getResources().getString(R.string.first_info));

    progressBar.setProgress(100);

    CookieSyncManager.createInstance(this);
    CookieManager cookieManager = CookieManager.getInstance();
    cookieManager.removeAllCookie();

    mWebView = (WebView) findViewById(R.id.loginWebView);
    try {
        mWebView.getSettings().setJavaScriptEnabled(true);
    } catch (Exception e) {

    }
    mWebView.getSettings().setAppCacheEnabled(false);
    mWebView.getSettings().setSavePassword(false);
    mWebView.getSettings().setSaveFormData(false);
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String url) {
            if (url != null && url.startsWith("oauth:///talonforandroid")) {
                handleTwitterCallback(url);
            } else {
                webView.loadUrl(url);
            }
            return true;
        }
    });

    noThanks.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new FollowMe().execute();

            btnLoginTwitter.setText(getResources().getString(R.string.back_to_timeline));
            noThanks.setVisibility(View.GONE);

            summary.setText(getResources().getString(R.string.third_info));
        }
    });

    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // Call login_activity twitter function
            if (btnLoginTwitter.getText().toString()
                    .contains(getResources().getString(R.string.login_to_twitter))) {
                if (Utils.hasInternetConnection(context)) {
                    btnLoginTwitter.setEnabled(false);

                    new RetreiveFeedTask().execute();
                } else {
                    Toast.makeText(context, getResources().getString(R.string.no_network) + "!",
                            Toast.LENGTH_SHORT).show();
                }
            } else if (btnLoginTwitter.getText().toString()
                    .contains(getResources().getString(R.string.initial_sync))) {
                new getTimeLine().execute();
            } else if (btnLoginTwitter.getText().toString()
                    .contains(getResources().getString(R.string.no_thanks))) {
                btnLoginTwitter.setText(getResources().getString(R.string.back_to_timeline));
                noThanks.setVisibility(View.GONE);

                summary.setText(getResources().getString(R.string.third_info));
            } else {

                if (settings.timelineRefresh != 0) { // user only wants manual
                    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

                    long now = new Date().getTime();
                    long alarm = now + settings.timelineRefresh;

                    PendingIntent pendingIntent = PendingIntent.getService(context,
                            HomeFragment.HOME_REFRESH_ID, new Intent(context, TimelineRefreshService.class), 0);

                    am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.timelineRefresh, pendingIntent);

                    now = new Date().getTime();
                    alarm = now + settings.mentionsRefresh;

                    PendingIntent pendingIntent2 = PendingIntent.getService(context,
                            MentionsFragment.MENTIONS_REFRESH_ID,
                            new Intent(context, MentionsRefreshService.class), 0);

                    am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.mentionsRefresh, pendingIntent2);

                    alarm = now + settings.dmRefresh;

                    PendingIntent pendingIntent3 = PendingIntent.getService(context, DMFragment.DM_REFRESH_ID,
                            new Intent(context, DirectMessageRefreshService.class), 0);
                    am.setRepeating(AlarmManager.RTC_WAKEUP, alarm, settings.dmRefresh, pendingIntent3);
                }

                // set up the autotrim
                AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                long now = new Date().getTime();
                long alarm = now + AlarmManager.INTERVAL_DAY;
                Log.v("alarm_date", "auto trim " + new Date(alarm).toString());
                PendingIntent pendingIntent = PendingIntent.getService(context, 161,
                        new Intent(context, TrimDataService.class), 0);
                am.set(AlarmManager.RTC_WAKEUP, alarm, pendingIntent);

                finish();

                Intent timeline = new Intent(context, MainActivity.class);
                timeline.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                timeline.putExtra("tutorial", true);
                sharedPrefs.edit().putBoolean("should_refresh", false).commit();
                sharedPrefs.edit().putBoolean("refresh_me", true).commit();
                sharedPrefs.edit().putBoolean("refresh_me_mentions", true).commit();
                sharedPrefs.edit().putBoolean("refresh_me_dm", true).commit();
                sharedPrefs.edit().putBoolean("need_new_dm", false).commit();
                sharedPrefs.edit().putBoolean("need_clean_databases_version_1_3_0", false).commit();
                sharedPrefs.edit().putBoolean("setup_v_two", true).commit();
                sharedPrefs.edit().putBoolean("version_2_2_7_1", false).commit();
                AppSettings.invalidate();
                startActivity(timeline);
            }

        }
    });
}

From source file:com.krossovochkin.kwitter.activities.MainActivity.java

License:Apache License

private void initTwitter() {
    boolean authDataExists = Settings.getBoolean(this, Settings.AUTH_DATA_EXISTS, false);

    if (authDataExists) {
        ConfigurationBuilder cb = new ConfigurationBuilder();

        cb.setDebugEnabled(BuildConfig.DEBUG).setOAuthConsumerKey(getString(R.string.twitter_consumer_key))
                .setOAuthConsumerSecret(getString(R.string.twitter_consumer_secret))
                .setOAuthAccessToken(Settings.getString(this, Settings.ACCESS_TOKEN_KEY))
                .setOAuthAccessTokenSecret(Settings.getString(this, Settings.ACCESS_TOKEN_SECRET_KEY))
                .setJSONStoreEnabled(true);

        TwitterFactory tf = new TwitterFactory(cb.build());
        mTwitter = tf.getInstance();
    } else {// www .j a  v a2 s  .  c o  m
        startActivity(new Intent(this, AuthActivity.class));
        finish();
    }
}

From source file:com.mycompany.twitterapp.TwitterApp.java

public void buildConfig() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("")
            .setOAuthAccessTokenSecret("");
    TwitterFactory tf = new TwitterFactory(cb.build());

    twitter = tf.getInstance();
}

From source file:com.mycompany.twitterproductanalysistool.TwitterAPI.java

public TwitterAPI() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("ogluOfaFe00xjVQ5WfynhkWQY")
            .setOAuthConsumerSecret("l4yL7iz6J1zEBaY4ownHu9VnIu2zSLuELVyzxykgoSEF3vzSup")
            .setOAuthAccessToken("1101064884-uMgjzYHHo82fRZdwWbvjNWs8ZKqoZj0xsKB4jnO")
            .setOAuthAccessTokenSecret("WyCAT00L4FK0lOQiXhshNXpS5bHVFoVsaoYGlJYVylWYm");
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();
}

From source file:com.oldterns.vilebot.handlers.user.UrlTweetAnnouncer.java

License:Open Source License

/**
 * Accesses the source of a HTML page and looks for a title element
 * //from   www  . java2  s. c  o m
 * @param url http tweet String
 * @return String of text which represents the tweet.  Empty if error.
 */
private String scrapeURLHTMLTitle(String url) {
    String text = "";

    URL page;
    try {
        page = new URL(url);
    } catch (MalformedURLException x) {
        // System.err.format("scrapeURLHTMLTitle new URL error: %s%n", x);
        return text;
    }

    //split the url into pieces, change the request based on what we have
    String parts[] = url.split("/");
    int userPosition = 0;
    long tweetID = 0;
    for (int i = 0; i < parts.length; i++) {

        if (parts[i].toString().equals("twitter.com"))
            userPosition = i + 1;
        if (parts[i].toString().equals("status") || parts[i].toString().equals("statuses"))
            tweetID = Long.valueOf(parts[i + 1].toString()).longValue();
    }
    if (userPosition == 0)
        return text;
    else {
        try {
            String consumerKey = ""; //may be known as 'API key'
            String consumerSecret = ""; //may be known as 'API secret'
            String accessToken = ""; //may be known as 'Access token'
            String accessTokenSecret = ""; //may be known as 'Access token secret'
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
                    .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();
            if (tweetID != 0) //tweet of the twitter.com/USERID/status/TWEETID variety
            {
                Status status = twitter.showStatus(tweetID);
                return (status.getUser().getName() + ": " + status.getText());
            } else //just the user is given, ie, twitter.com/USERID 
            {
                User user = twitter.showUser(parts[userPosition].toString());
                if (!user.getDescription().isEmpty()) //the user has a description
                    return ("Name: " + user.getName() + " | " + user.getDescription() + "\'\nLast Tweet: \'"
                            + user.getStatus().getText());
                else //the user doesn't have a description, don't print it
                    return ("Name: " + user.getName() + "\'\nLast Tweet: \'" + user.getStatus().getText());

            }
        } catch (TwitterException x) {
            return text;
        }
    }
}

From source file:com.ontotext.s4.TwitterVisualization.downloadTweets.SearchTweets.java

License:Open Source License

/**
 * Creates and configures Twitter client instance with provided credentials.
 * /*  w  ww .  j a  va 2 s  .  c o  m*/
 * @return Twitter instance
 */
private Twitter ConfigurateTwitterAccount() {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret)
            .setJSONStoreEnabled(true);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    return twitter;
}

From source file:com.revolucion.secretwit.twitter.TwitterClient.java

License:Open Source License

private void init() {
    logger.info("Starting Twitter client.");

    TwitterFactory factory = new TwitterFactory();
    twitter = factory.getInstance();

    twitter.setOAuthConsumer(consumerKey, consumerSecret);

    logger.info("OAuth consumer initialized.");

    AccessToken accessToken = loadAccessToken();
    if (accessToken != null) {
        twitter.setOAuthAccessToken(accessToken);
        logger.info("Loaded access token.");
        // signedIn = true;
        try {//from w  w w .  j  a va 2 s.c  o m
            user = twitter.verifyCredentials();
        } catch (TwitterException e) {
            logger.error(e.getMessage());
        }
    }
}

From source file:com.sinfonier.drains.TweetIt.java

License:Apache License

@Override
public void userexecute() {

    ConfigurationBuilder config = new ConfigurationBuilder();
    config.setOAuthConsumerKey(this.CONSUMER_KEY);
    config.setOAuthConsumerSecret(this.CONSUMER_SECRET);
    config.setOAuthAccessToken(this.ACCESS_TOKEN);
    config.setOAuthAccessTokenSecret(this.ACCESS_TOKEN_SECRET);
    config.setJSONStoreEnabled(true);/*from  w  w w  . j  a v  a2  s  .com*/
    config.setIncludeEntitiesEnabled(true);
    try {
        TwitterFactory tf = new TwitterFactory(config.build());
        Twitter twitter = tf.getInstance();
        Status status = twitter.updateStatus(this.customText + " " + this.getField(this.fieldToTweet));
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
    } catch (TwitterException te) {
        te.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.smart.home.service.TwitterService.java

License:Open Source License

/**
 * Constructor for twitter service/* ww  w. j  ava 2s .  c om*/
 *
 * @param apiKey      twitter API key
 * @param apiSecret   twitter API secret key
 * @param token       twitter access token
 * @param tokenSecret twitter access token secret
 */
public TwitterService(String apiKey, String apiSecret, String token, String tokenSecret) {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(apiKey).setOAuthConsumerSecret(apiSecret)
            .setOAuthAccessToken(token).setOAuthAccessTokenSecret(tokenSecret);
    TwitterFactory factory = new TwitterFactory(cb.build());
    twitter = factory.getInstance();
    twitter.directMessages();
}