Example usage for twitter4j TwitterFactory TwitterFactory

List of usage examples for twitter4j TwitterFactory TwitterFactory

Introduction

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

Prototype

public TwitterFactory(String configTreePath) 

Source Link

Document

Creates a TwitterFactory with a specified config tree

Usage

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();/*  ww w.  j  a  va 2  s  . c  o  m*/

}

From source file:Collector.TwitterConnector.java

public void makeConnection() {
    try {//w  ww . jav  a 2  s  . c  o  m

        ob = new ConfigurationBuilder();
        ob.setJSONStoreEnabled(true);
        ob.setDebugEnabled(true).setOAuthConsumerKey("EaNDPdbztcAhLEwREWrnXFrbH")
                .setOAuthConsumerSecret("TfzWIxgGXrgrlpiCAITFMVD1e7i6y6UuP2Z9rHpKIy7ZN35pGQ")
                .setOAuthAccessToken("4832753560-BLljOptOjTJs8lmbJlvgjSUM9nEQXjyEpKhQart")
                .setOAuthAccessTokenSecret("cbXs1UMe9mfcCHWdBEj9yV7NgFZ6xgF8w2uzguQs4BTMb");

        tf = new TwitterFactory(ob.build());
        tw = tf.getInstance();

        System.out.println("Connection made");
        // return tw;

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

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();// ww w  .j a  v  a  2 s  . c o m

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

From source file:com.adobe.acs.commons.twitter.impl.TwitterAdapterFactory.java

License:Apache License

@Activate
protected void activate() {
    this.factory = new TwitterFactory(buildConfiguration());
}

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();// w w w .  j  av a 2  s  .  c  o m
    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  a  v a 2 s.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.alainesp.fan.sanderson.SummaryFragment.java

License:Open Source License

protected int doWork() {
    int state = DownloadParseSaveTask.STATE_SUCCESS;

    try {//from w ww  .j a v a  2  s . co m
        List<twitter4j.Status> tweets;

        // Twitter client configuration
        ConfigurationBuilder builder = new ConfigurationBuilder();
        builder.setOAuthConsumerKey(TwitterAPISecrets.CONSUMER_KEY)
                .setOAuthConsumerSecret(TwitterAPISecrets.CONSUMER_SECRET);
        // TODO: Use guest authentication instead of application
        builder.setApplicationOnlyAuthEnabled(true).setDebugEnabled(false).setGZIPEnabled(true);

        Twitter twitter = new TwitterFactory(builder.build()).getInstance();
        twitter.getOAuth2Token();

        // Get the tweets
        long lastTweetID = DB.Tweet.getLastTweetID();
        if (lastTweetID <= 0)
            tweets = twitter.getUserTimeline("BrandSanderson");
        else
            tweets = twitter.getUserTimeline("BrandSanderson", new Paging(lastTweetID));

        if (tweets != null) {
            long brandonID = 28187205;
            Hashtable<Long, DB.Tweet> findTweet = new Hashtable<>(tweets.size() * 16, 0.25f);
            List<DB.Tweet> dbTweets = new ArrayList<>(tweets.size());
            for (twitter4j.Status tweet : tweets) {
                // Create the tweet
                if (tweet.isRetweet())
                    tweet = tweet.getRetweetedStatus();

                long tweetID = tweet.getId();
                // TODO: Include the tweets in the DB
                if (findTweet.get(tweetID) == null)// This eliminate tweets already in the replies tree
                {
                    DB.Tweet dbTweet = new DB.Tweet(tweetID, getTweetText(tweet), tweet.getCreatedAt(), false,
                            tweet.getUser().getName(), tweet.getUser().getBiggerProfileImageURLHttps());
                    InternetHelper.getRemoteFile(tweet.getUser().getBiggerProfileImageURLHttps());
                    dbTweets.add(dbTweet);
                    findTweet.put(tweetID, dbTweet);

                    // Traverse the tree of the replies tweets
                    twitter4j.Status treeTweet = tweet;
                    while (treeTweet != null && treeTweet.getInReplyToStatusId() >= 0) {
                        try {
                            long id = treeTweet.getInReplyToStatusId();
                            long userID = treeTweet.getUser().getId();
                            treeTweet = null;
                            if (findTweet.get(id) == null || brandonID == userID)
                                treeTweet = twitter.showStatus(id);
                            else// Remove duplicates. Not sure why they appear, but the difference of the text is a dot at the end.
                                dbTweets.remove(dbTweets.size() - 1);
                        } catch (Exception ignore) {
                        }

                        if (treeTweet != null) {
                            findTweet.put(treeTweet.getId(), dbTweet);
                            StringBuilder replyBuilder = new StringBuilder();

                            replyBuilder.append("<blockquote>");

                            // Profile image
                            replyBuilder.append("<img src=\"");
                            InternetHelper.getRemoteFile(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append(treeTweet.getUser().getBiggerProfileImageURLHttps());
                            replyBuilder.append("\"/>&nbsp;<b>");

                            // Username - date
                            replyBuilder.append(treeTweet.getUser().getName());
                            replyBuilder.append("</b> @");
                            replyBuilder.append(treeTweet.getUser().getScreenName());
                            replyBuilder.append(" - ");
                            replyBuilder
                                    .append(TwitterFragment.showDateFormat.format(treeTweet.getCreatedAt()));

                            // Tweet text
                            replyBuilder.append("<br/>");
                            replyBuilder.append(getTweetText(treeTweet));

                            // Remaining
                            replyBuilder.append(dbTweet.htmlReply);
                            replyBuilder.append("</blockquote>");

                            dbTweet.htmlReply = replyBuilder.toString();
                        }
                    }
                }
            }
            DB.Tweet.updateTwitter(dbTweets);
        }
    } catch (Exception e) {
        Logger.reportError(e.toString());
        state = DownloadParseSaveTask.STATE_ERROR_PARSING;
    }

    return state;
}

From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java

License:Open Source License

public TwitterCommands(String consumerKey, String consumerSecret) {
    this.consumerKey = consumerKey;
    this.consumerSecret = consumerSecret;
    defaultConfigBuilder.setDebugEnabled(true).setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret);
    defaultTwitterFactory = new TwitterFactory(defaultConfigBuilder.build());
    twitter = defaultTwitterFactory.getInstance();
}

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. jav a  2s  . 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.aremaitch.codestock2010.library.TwitterAvatarManager.java

License:Apache License

public void downloadAvatar(String twitterScreenName, long twitterUserId, String consumerKey,
        String consumerSecret, String accessToken, String accessTokenSecret) {
    //  Fire & forget

    if (!_cacheManager.isCacheReady()) {
        ACLogger.info(CSConstants.LOG_TAG, "could not download twitter picture because sdcard is not mounted");
        return;/*w  ww . j  ava  2 s  . c  om*/
    }
    Configuration config = new ConfigurationBuilder().setOAuthConsumerKey(consumerKey)
            .setOAuthConsumerSecret(consumerSecret).setOAuthAccessToken(accessToken)
            .setOAuthAccessTokenSecret(accessTokenSecret).build();
    t = new TwitterFactory(config).getInstance();

    try {
        ProfileImage image = t.getProfileImage(twitterScreenName, ProfileImage.NORMAL);
        String srcUrl = image.getURL();

        downloadAvatar(twitterScreenName, twitterUserId, srcUrl);
    } catch (TwitterException e) {
        e.printStackTrace();
    }

}