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:co.uk.socialticker.ticker.TickerActivity.java

License:Open Source License

/**
 * Function to login twitter/*w w  w. jav a  2 s.c o  m*/
 * */
private void loginToTwitter() {
    // Check if already logged in
    if (!isTwitterLoggedInAlready()) {
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
        builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        Configuration configuration = builder.build();

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

        try {
            requestToken = twitter.getOAuthRequestToken(TWITTER_CALLBACK_URL);
            this.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(requestToken.getAuthenticationURL())));
        } catch (TwitterException e) {
            e.printStackTrace();
        }
    } else {
        // user already logged into twitter
        Toast.makeText(getApplicationContext(), "Already Logged into twitter", Toast.LENGTH_LONG).show();
    }
}

From source file:collector.TwitterCollector.java

public TwitterCollector(List<String> credentials) {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    String OAuthConsumerKey = credentials.get(0);
    String OAuthConsumerSecret = credentials.get(1);
    String OAuthAccessToken = credentials.get(2);
    String OAuthAccessTokenSecret = credentials.get(3);

    cb.setDebugEnabled(true).setOAuthConsumerKey(OAuthConsumerKey).setOAuthConsumerSecret(OAuthConsumerSecret)
            .setOAuthAccessToken(OAuthAccessToken).setOAuthAccessTokenSecret(OAuthAccessTokenSecret);
    //                .setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter = tf.getInstance();

}

From source file:ColourUs.Main.java

public Main() {
    OAuth auth = new OAuth();
    Configuration config = auth.getConfig();

    TwitterFactory tf = new TwitterFactory(config);
    Twitter twitter = tf.getInstance();

    t = new Trending(twitter, 10);
    s = new Stream(config, t);
    p = new Parser(t);
    c = new Calculation();
    Timing timer = new Timing(this);
    s.run();// w  w  w  .  j  ava2 s  .c  om
    timer.start(120);
}

From source file:com.ahuralab.mozaic.auth.TwitterAuthenticator.java

License:Open Source License

public Twitter createTwitter(Context context) {
    SharedPreferences settings = context.getSharedPreferences(TWITTER_CREDENTIAL, 0);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(settings.getString("user_key", null))
            .setOAuthAccessTokenSecret(settings.getString("user_secret", null));
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    return twitter;
}

From source file:com.ak.android.akplaza.common.sns.twitter.TwitterController.java

License:Open Source License

public static void write(String content, Activity at) {
    //      Log.d(TAG, "content : " + content);
    String path = Environment.getExternalStorageDirectory().getAbsolutePath();
    String fileName = "example.jpg";
    InputStream is = null;//from w w w .j  ava  2s.c om

    try {
        if (new File(path + File.separator + fileName).exists())
            is = new FileInputStream(path + File.separator + fileName);
        else
            is = null;

        ConfigurationBuilder cb = new ConfigurationBuilder();
        String oAuthAccessToken = acToken.getToken();
        String oAuthAccessTokenSecret = tacs;
        String oAuthConsumerKey = C.TWITTER_CONSUMER_KEY;
        String oAuthConsumerSecret = C.TWITTER_CONSUMER_SECRET;
        cb.setOAuthAccessToken(oAuthAccessToken);
        cb.setOAuthAccessTokenSecret(oAuthAccessTokenSecret);
        cb.setOAuthConsumerKey(oAuthConsumerKey);
        cb.setOAuthConsumerSecret(oAuthConsumerSecret);
        Configuration config = cb.build();
        OAuthAuthorization auth = new OAuthAuthorization(config);

        TwitterFactory tFactory = new TwitterFactory(config);
        Twitter twitter = tFactory.getInstance();
        //         ImageUploadFactory iFactory = new ImageUploadFactory(getConfiguration(C.TWITPIC_API_KEY));
        //         ImageUpload upload = iFactory.getInstance(MediaProvider.TWITPIC, auth);

        if (is != null) {
            //        String strResult = upload.upload("example.jpg", is, mEtContent.getText().toString());
            //        twitter.updateStatus(mEtContent.getText().toString() + " " + strResult);
        } else
            twitter.updateStatus(content);
        new AlertDialog.Builder(at).setMessage(" ? ? ?.")
                .setPositiveButton("?", null).show();
    } catch (Exception e) {
        e.printStackTrace();
        new AlertDialog.Builder(at).setMessage("? ?  ")
                .setPositiveButton("?", null).show();
    } finally {
        try {
            is.close();
        } catch (Exception e) {
        }
    }

}

From source file:com.amazonbird.db.data.Announcer.java

License:Open Source License

public Twitter getTwitterProxy() throws TwitterException {
    if (twitter == null) {

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

        twitter.setOAuthConsumer(getConsumerKey(), getConsumerSecret());
        twitter.setOAuthAccessToken(new AccessToken(getAccessToken(), getAccessTokenSecret()));
    }/* w  w w .  j a v  a  2 s  .  co m*/
    return twitter;
}

From source file:com.android.calendar.AllInOneActivity.java

License:Apache License

@Override
protected void onCreate(Bundle icicle) {
    if (Utils.getSharedPreference(this, OtherPreferences.KEY_OTHER_1, false)) {
        setTheme(R.style.CalendarTheme_WithActionBarWallpaper);
    }/*from  w  w  w. j  a  va  2 s  .co  m*/
    super.onCreate(icicle);
    dynamicTheme.onCreate(this);

    if (icicle != null && icicle.containsKey(BUNDLE_KEY_CHECK_ACCOUNTS)) {
        mCheckForAccounts = icicle.getBoolean(BUNDLE_KEY_CHECK_ACCOUNTS);
    }
    // Launch add google account if this is first time and there are no
    // accounts yet
    if (mCheckForAccounts && !Utils.getSharedPreference(this, GeneralPreferences.KEY_SKIP_SETUP, false)) {

        mHandler = new QueryHandler(this.getContentResolver());
        mHandler.startQuery(0, null, Calendars.CONTENT_URI, new String[] { Calendars._ID }, null,
                null /* selection args */, null /* sort order */);
    }

    // This needs to be created before setContentView
    mController = CalendarController.getInstance(this);

    // Check and ask for most needed permissions
    checkAppPermissions();

    // Get time from intent or icicle
    long timeMillis = -1;
    int viewType = -1;
    final Intent intent = getIntent();
    if (icicle != null) {
        timeMillis = icicle.getLong(BUNDLE_KEY_RESTORE_TIME);
        viewType = icicle.getInt(BUNDLE_KEY_RESTORE_VIEW, -1);
    } else {
        String action = intent.getAction();
        if (Intent.ACTION_VIEW.equals(action)) {
            // Open EventInfo later
            timeMillis = parseViewAction(intent);
        }

        if (timeMillis == -1) {
            timeMillis = Utils.timeFromIntentInMillis(intent);
        }
    }

    if (viewType == -1 || viewType > ViewType.MAX_VALUE) {
        viewType = Utils.getViewTypeFromIntentAndSharedPref(this);
    }
    mTimeZone = Utils.getTimeZone(this, mHomeTimeUpdater);
    Time t = new Time(mTimeZone);
    t.set(timeMillis);

    if (DEBUG) {
        if (icicle != null && intent != null) {
            Log.d(TAG, "both, icicle:" + icicle.toString() + "  intent:" + intent.toString());
        } else {
            Log.d(TAG, "not both, icicle:" + icicle + " intent:" + intent);
        }
    }

    Resources res = getResources();
    mHideString = res.getString(R.string.hide_controls);
    mShowString = res.getString(R.string.show_controls);
    mOrientation = res.getConfiguration().orientation;
    if (mOrientation == Configuration.ORIENTATION_LANDSCAPE) {
        mControlsAnimateWidth = (int) res.getDimension(R.dimen.calendar_controls_width);
        if (mControlsParams == null) {
            mControlsParams = new LayoutParams(mControlsAnimateWidth, 0);
        }
        mControlsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    } else {
        // Make sure width is in between allowed min and max width values
        mControlsAnimateWidth = Math.max(res.getDisplayMetrics().widthPixels * 45 / 100,
                (int) res.getDimension(R.dimen.min_portrait_calendar_controls_width));
        mControlsAnimateWidth = Math.min(mControlsAnimateWidth,
                (int) res.getDimension(R.dimen.max_portrait_calendar_controls_width));
    }

    mControlsAnimateHeight = (int) res.getDimension(R.dimen.calendar_controls_height);

    mHideControls = !Utils.getSharedPreference(this, GeneralPreferences.KEY_SHOW_CONTROLS, true);
    mIsMultipane = Utils.getConfigBool(this, R.bool.multiple_pane_config);
    mIsTabletConfig = Utils.getConfigBool(this, R.bool.tablet_config);
    mShowAgendaWithMonth = Utils.getConfigBool(this, R.bool.show_agenda_with_month);
    mShowCalendarControls = Utils.getConfigBool(this, R.bool.show_calendar_controls);
    mShowEventDetailsWithAgenda = Utils.getConfigBool(this, R.bool.show_event_details_with_agenda);
    mShowEventInfoFullScreenAgenda = Utils.getConfigBool(this, R.bool.agenda_show_event_info_full_screen);
    mShowEventInfoFullScreen = Utils.getConfigBool(this, R.bool.show_event_info_full_screen);
    mCalendarControlsAnimationTime = res.getInteger(R.integer.calendar_controls_animation_time);
    Utils.setAllowWeekForDetailView(mIsMultipane);

    // setContentView must be called before configureActionBar
    setContentView(R.layout.all_in_one_material);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mNavigationView = (NavigationView) findViewById(R.id.navigation_view);

    mFab = (FloatingActionButton) findViewById(R.id.floating_action_button);

    if (mIsTabletConfig) {
        mDateRange = (TextView) findViewById(R.id.date_bar);
        mWeekTextView = (TextView) findViewById(R.id.week_num);
    } else {
        mDateRange = (TextView) getLayoutInflater().inflate(R.layout.date_range_title, null);
    }

    setupToolbar(viewType);
    setupNavDrawer();
    setupFloatingActionButton();

    mHomeTime = (TextView) findViewById(R.id.home_time);
    mMiniMonth = findViewById(R.id.mini_month);
    if (mIsTabletConfig && mOrientation == Configuration.ORIENTATION_PORTRAIT) {
        mMiniMonth.setLayoutParams(
                new RelativeLayout.LayoutParams(mControlsAnimateWidth, mControlsAnimateHeight));
    }
    mCalendarsList = findViewById(R.id.calendar_list);
    mMiniMonthContainer = findViewById(R.id.mini_month_container);
    mSecondaryPane = findViewById(R.id.secondary_pane);

    // Must register as the first activity because this activity can modify
    // the list of event handlers in it's handle method. This affects who
    // the rest of the handlers the controller dispatches to are.
    mController.registerFirstEventHandler(HANDLER_KEY, this);

    initFragments(timeMillis, viewType, icicle);

    // Listen for changes that would require this to be refreshed
    SharedPreferences prefs = GeneralPreferences.getSharedPreferences(this);
    prefs.registerOnSharedPreferenceChangeListener(this);

    mContentResolver = getContentResolver();

    //set layout background
    AnimationDrawable animation = new AnimationDrawable();
    animation.addFrame(getResources().getDrawable(R.mipmap.namo1), 5000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo2), 10000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo3), 15000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo4), 20000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo7), 25000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo8), 30000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo9), 35000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo10), 40000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo11), 45000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo12), 50000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo13), 55000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo14), 60000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo15), 65000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo16), 70000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo17), 75000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo18), 80000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo19), 85000);
    animation.addFrame(getResources().getDrawable(R.mipmap.namo20), 90000);

    animation.setOneShot(false);
    mDrawerLayout.setBackground(animation);
    animation.start();

    //sharedpreference for get n save tweet

    tvSlogan = (TextView) findViewById(R.id.modi_Slogan);
    list = new ArrayList<>();
    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
    final SharedPreferences.Editor editor = sharedpreferences.edit();
    final Set<String> set = new HashSet<String>();
    new Thread(new Runnable() {
        @Override
        public void run() {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey("IXJTMZRCoCPs0pnZfODmpvCem")
                    .setOAuthConsumerSecret("ReF3xJiSdFcePKeFv2or5JFDxERnkgKBjEl1u9tc6zgsmmgvl7")
                    .setOAuthAccessToken("580688604-FsMXIhAgOVLuMvpieiwTFLHAerMvUXmdvvq6Zsal")
                    .setOAuthAccessTokenSecret("93IEkCWSikYPQw6RsjifUu70COSOJumHQyXTFUyhKh1XJ");
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();
            try {
                List<Status> statuses;
                String user;
                user = "@narendramodi";
                statuses = twitter.getUserTimeline(user);
                Log.i("Status Count", statuses.size() + " Feeds");
                for (int i = 0; i < statuses.size(); i++) {
                    Status status = statuses.get(i);

                    set.add(status.getText());

                    editor.putStringSet("key", set);
                    editor.commit();
                    Log.i("Tweet Count " + (i + 1), status.getText() + "\n\n");
                }
            } catch (TwitterException te) {
                te.printStackTrace();
            }
        }
    }).start();

    Set<String> mySet = new HashSet<String>();
    mySet = sharedpreferences.getStringSet("key", set);

    Timer timer = new Timer();

    if (mySet != null) {
        for (final String tweet : mySet) {

            list.add(tweet);
            /* Toast.makeText(getApplicationContext(),
                tweet,
                Toast.LENGTH_LONG).show();*/
        }
    }

    //set modi's slogan

    //  list = new ArrayList<>();

    /*  sharedpreferences= getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
      SharedPreferences.Editor editor = sharedpreferences.edit();
            
      for(int i=0;i<slogan.length;i++)
    editor.putString(slogan + "_" + i, slogan[i]);
      editor.commit();
            
      Map<String, ?> str = sharedpreferences.getAll();
            
            
      for (final Map.Entry<String, ?> entry : str.entrySet()) {
            
    list.add(entry.getValue().toString());
            
      }*/

    getTweet();
    getSlogan();

}

From source file:com.arihant15.ActionServlet.java

@RequestMapping("/login.arihant15")
public void doLogin(HttpServletRequest req, HttpServletResponse res) {
    try {/*from  ww  w .j  ava 2  s  . c o  m*/
        ConfigurationBuilder configuration = new ConfigurationBuilder();
        configuration.setOAuthConsumerKey(ConsumerKey);
        configuration.setOAuthConsumerSecret(ConsumerSecret);
        TwitterFactory twitterfactory = new TwitterFactory(configuration.build());
        Twitter twitter = twitterfactory.getInstance();
        req.getSession().setAttribute("t", twitter);
        RequestToken requestToken = twitter.getOAuthRequestToken();
        req.getSession().setAttribute("rToken", requestToken);
        res.sendRedirect(requestToken.getAuthenticationURL());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.bordengrammar.bordengrammarapp.TwitterActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_twitter);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        setTranslucentStatus(true);//from  ww  w.j  av a  2 s . c  om
    }
    SystemBarTintManager tintManager = new SystemBarTintManager(this);
    tintManager.setStatusBarTintEnabled(true);
    tintManager.setStatusBarTintResource(R.color.bordenpurple);
    FeedbackSettings feedbackSettings = new FeedbackSettings();
    feedbackSettings.setCancelButtonText("Cancel");
    feedbackSettings.setSendButtonText("Send");
    feedbackSettings.setText("Send feedback to improve the app");
    feedbackSettings.setTitle("Feedback");
    feedbackSettings.setToast("We value your feedback");
    feedBack = new FeedbackDialog(this, "AF-186C1F794D93-1A", feedbackSettings);
    ActionBar actionBar = getActionBar();
    assert actionBar != null;
    actionBar.setDisplayHomeAsUpEnabled(true);
    PACKAGE_NAME = getApplicationContext().getPackageName();

    //Now lets get down into the twitter

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Toqp03fcUErG5P8e9nhfsw")
            .setOAuthConsumerSecret("SEqktstO9h7SqSm7zmcuWlH3bOtElJm1Ds2TFSwFBc")
            .setOAuthAccessToken("2245935685-U5LMfl4oEcOv6Khw58JZqRdcH2PlABEeUP2JeXj")
            .setOAuthAccessTokenSecret("uFcGRpCx8aGXdv3AiAkfVImnoLrlNNCUnZ2UtE76Zbnpa");

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    List<Status> statuses = null;
    String user;
    user = "bordengrammar";
    try {
        statuses = twitter.getUserTimeline(user);
    } catch (TwitterException e) {
        e.printStackTrace();
    }
    assert statuses != null;
    twitter4j.Status status1 = statuses.get(0);
    Format formatter = new SimpleDateFormat("MMM d, K:mm");
    savePrefs("twitter", status1.getText());
    savePrefs("twittertime", formatter.format(status1.getCreatedAt()));
    twitter4j.Status status2 = statuses.get(1);
    twitter4j.Status status3 = statuses.get(2);
    twitter4j.Status status4 = statuses.get(3);
    twitter4j.Status status5 = statuses.get(4);
    twitter4j.Status status6 = statuses.get(5);
    twitter4j.Status status7 = statuses.get(6);
    twitter4j.Status status8 = statuses.get(7);
    twitter4j.Status status9 = statuses.get(8);
    twitter4j.Status status10 = statuses.get(9);
    TextView time1 = (TextView) findViewById(R.id.time1);
    TextView time2 = (TextView) findViewById(R.id.time2);
    TextView time3 = (TextView) findViewById(R.id.time3);
    TextView time4 = (TextView) findViewById(R.id.time4);
    TextView time5 = (TextView) findViewById(R.id.time5);
    TextView time6 = (TextView) findViewById(R.id.time6);
    TextView time7 = (TextView) findViewById(R.id.time7);
    TextView time8 = (TextView) findViewById(R.id.time8);
    TextView time9 = (TextView) findViewById(R.id.time9);
    TextView time10 = (TextView) findViewById(R.id.time10);
    time1.setText(formatter.format(status1.getCreatedAt()));
    time2.setText(formatter.format(status2.getCreatedAt()));
    time3.setText(formatter.format(status3.getCreatedAt()));
    time4.setText(formatter.format(status4.getCreatedAt()));
    time5.setText(formatter.format(status5.getCreatedAt()));
    time6.setText(formatter.format(status6.getCreatedAt()));
    time7.setText(formatter.format(status7.getCreatedAt()));
    time8.setText(formatter.format(status8.getCreatedAt()));
    time9.setText(formatter.format(status9.getCreatedAt()));
    time10.setText(formatter.format(status10.getCreatedAt()));
    TextView text1 = (TextView) findViewById(R.id.text1);
    TextView text2 = (TextView) findViewById(R.id.text2);
    TextView text3 = (TextView) findViewById(R.id.text3);
    TextView text4 = (TextView) findViewById(R.id.text4);
    TextView text5 = (TextView) findViewById(R.id.text5);
    TextView text6 = (TextView) findViewById(R.id.text6);
    TextView text7 = (TextView) findViewById(R.id.text7);
    TextView text8 = (TextView) findViewById(R.id.text8);
    TextView text9 = (TextView) findViewById(R.id.text9);
    TextView text10 = (TextView) findViewById(R.id.text10);
    text1.setText(readPrefs("twitter"));
    text2.setText(status2.getText());
    text3.setText(status3.getText());
    text4.setText(status4.getText());
    text5.setText(status5.getText());
    text6.setText(status6.getText());
    text7.setText(status7.getText());
    text8.setText(status8.getText());
    text9.setText(status9.getText());
    text10.setText(status10.getText());
    /* i think i could have used a for loop... oh well i typed it all already. */
}

From source file:com.buddycloud.friendfinder.provider.Twitter.java

License:Apache License

@Override
public ContactProfile getProfile(String accessToken, String accessTokenSecret) throws Exception {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(getProperties().getProperty("twitter.consumerKey"))
            .setOAuthConsumerSecret(getProperties().getProperty("twitter.consumerSecret"))
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter4j.Twitter twitter = tf.getInstance();

    Long myId = twitter.getId();/*w w  w  .j  av  a2  s  .co m*/
    ContactProfile contactProfile = new ContactProfile(HashUtils.encodeSHA256(PROVIDER_NAME, myId.toString()));
    long nextCursor = -1;
    while (true) {
        IDs friendsIDs = twitter.getFollowersIDs(nextCursor);
        for (Long friendId : friendsIDs.getIDs()) {
            contactProfile.addFriendHash(HashUtils.encodeSHA256(PROVIDER_NAME, friendId.toString()));
        }
        if (!friendsIDs.hasNext()) {
            break;
        }
        nextCursor = friendsIDs.getNextCursor();
    }
    return contactProfile;
}