Example usage for twitter4j TwitterStreamFactory TwitterStreamFactory

List of usage examples for twitter4j TwitterStreamFactory TwitterStreamFactory

Introduction

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

Prototype

public TwitterStreamFactory() 

Source Link

Document

Creates a TwitterStreamFactory with the root configuration.

Usage

From source file:com.dwdesign.tweetings.activity.HomeActivity.java

License:Open Source License

@Override
public void onStart() {
    super.onStart();
    setSupportProgressBarIndeterminateVisibility(mProgressBarIndeterminateVisible);
    final IntentFilter filter = new IntentFilter(BROADCAST_REFRESHSTATE_CHANGED);
    filter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
    filter.addAction(BROADCAST_NETWORK_STATE_CHANGED);
    filter.addAction(BROADCAST_TABS_NEW_TWEETS);
    filter.addAction(BROADCAST_TABS_READ_TWEETS);
    filter.addAction(BROADCAST_ACCOUNT_LIST_DATABASE_UPDATED);
    registerReceiver(mStateReceiver, filter);
    final boolean show_home_tab = mPreferences.getBoolean(PREFERENCE_KEY_SHOW_HOME_TAB, true);
    final boolean show_mentions_tab = mPreferences.getBoolean(PREFERENCE_KEY_SHOW_MENTIONS_TAB, true);
    final boolean show_messages_tab = mPreferences.getBoolean(PREFERENCE_KEY_SHOW_MESSAGES_TAB, true);
    final boolean show_accounts_tab = mPreferences.getBoolean(PREFERENCE_KEY_SHOW_ACCOUNTS_TAB, true);
    final boolean show_search_tab = mPreferences.getBoolean(PREFERENCE_KEY_SHOW_SEARCH_TAB, true);
    final boolean show_lists_tab = mPreferences.getBoolean(PREFERENCE_KEY_SHOW_LISTS_TAB, true);

    final List<TabSpec> tabs = getTabs(this);
    if (isTabsChanged(tabs) || show_home_tab != mShowHomeTab || show_mentions_tab != mShowMentionsTab
            || show_messages_tab != mShowMessagesTab || show_accounts_tab != mShowAccountsTab
            || show_search_tab != mShowSearchTab || show_lists_tab != mShowListsTab) {
        restart();/*w  w  w.ja  va2 s .  c o  m*/
    }
    if (mPreferences.getBoolean(PREFERENCE_KEY_STREAMING_ENABLED, false) == true) {

        if (mService != null) {
            try {
                Twitter twitter = com.dwdesign.tweetings.util.Utils
                        .getDefaultTwitterInstance(getApplicationContext(), true);
                twitterStream = new TwitterStreamFactory().getInstance(twitter.getAuthorization());
                twitterStream.addListener(listener);
            } catch (final Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.freshdigitable.udonroad.module.TwitterApiModule.java

License:Apache License

@Singleton
@Provides//  w ww  . j  a  v a 2 s.  co m
public TwitterStream provideTwitterStream() {
    final TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory();
    final TwitterStream twitterStream = twitterStreamFactory.getInstance();
    final String key = context.getString(R.string.consumer_key);
    final String secret = context.getString(R.string.consumer_secret);
    twitterStream.setOAuthConsumer(key, secret);
    return twitterStream;
}

From source file:com.github.jiloc.USTweetsAnalyzer.Streamer.java

public Streamer() throws IOException {
    this.twitterStream = new TwitterStreamFactory().getInstance();
    this.geoLocalizator = new Geolocalizator(this.GEOLOCALIZATOR_PATH);
    this.storage = new Store();
    Directory dir = storage.getDir();//from  ww w .  ja va2s.  c o  m
}

From source file:com.tuncaysenturk.jira.plugins.jtp.twitter.JiraTwitterStreamImpl.java

public void startListener() {
    if (!licenseValidator.isValid()) {
        logger.error(JTPConstants.LOG_PRE + "License problem, see configuration page");
        ExceptionMessagesUtil.addLicenseExceptionMessage();
    } else if (null != listener) {
        // it should not come here
        // first it has to be stopped  
        logger.warn(JTPConstants.LOG_PRE
                + "This is another attempt to stream twitter account that has already been streaming by another thread."
                + "It has to be stopped before.");
    } else {//from   w ww.  ja v  a 2  s . c  o  m
        twitterStream = new TwitterStreamFactory().getInstance();

        try {
            listener = new JiraTwitterUserStreamListener();
            listener.setJiraTwitterStream(twitterStream);
            listener.setJiraTwitterIssueService(issueService);
            listener.setLicenseValidator(licenseValidator);
            listener.setTweetIssueRelService(tweetIssueRelService);
            if (null == twitterStream.getConfiguration().getOAuthConsumerKey()
                    || null == twitterStream.getConfiguration().getOAuthConsumerSecret())
                twitterStream.setOAuthConsumer(propSet.getString("consumerKey"),
                        propSet.getString("consumerSecret"));
            try {
                AccessToken accessToken = new AccessToken(propSet.getString("accessToken"),
                        propSet.getString("accessTokenSecret"));
                twitterStream.setOAuthAccessToken(accessToken);
            } catch (IllegalStateException e) {
                logger.error(JTPConstants.LOG_PRE + "Exception while obtaining access tokens", e);
                ExceptionMessagesUtil.addExceptionMessage("Exception while obtaining access tokens : ", e);
            }

            twitterStream.addListener(listener);
            twitterStream.user();
            listener.setScreenName(twitterStream.getScreenName());
            logger.info(JTPConstants.LOG_PRE + "Successfully streaming twitter account");
        } catch (Exception e) {
            logger.error(JTPConstants.LOG_PRE + "Error while streaming", e);
            ExceptionMessagesUtil.addExceptionMessage("Error while streaming : ", e);
        }
    }
}

From source file:com.twitstreet.twitter.AdsListenerMgrImpl.java

License:Open Source License

@Override
public void start() {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    Announcer announcer = announcerMgr.randomAnnouncerData();
    twitterStream.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
    twitterStream/*from   w ww .jav a 2s  .  c om*/
            .setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));
    twitterStream.addListener(new StatusListener() {

        @Override
        public void onException(Exception arg0) {

        }

        @Override
        public void onTrackLimitationNotice(int arg0) {

        }

        @Override
        public void onStatus(Status status) {
            HashtagEntity[] hashtagEntities = status.getHashtagEntities();
            String screenName = status.getUser().getScreenName();
            User user = status.getUser();
            if (user != null && (System.currentTimeMillis() - lastMessage > TEN_MIN)) {
                lastMessage = System.currentTimeMillis();

                int action = (int) (ACTION_TYPES * Math.random());
                switch (action) {
                case REGULAR_TWEET:
                    LocalizationUtil lutil = LocalizationUtil.getInstance();
                    int sentenceSize = Integer
                            .parseInt(lutil.get("announcer.sentence.size", LocalizationUtil.DEFAULT_LANGUAGE));
                    int random = (int) (Math.random() * sentenceSize);
                    String rndMessage = lutil.get("announcer.sentence." + random,
                            LocalizationUtil.DEFAULT_LANGUAGE);
                    announcerMgr.announceFromRandomAnnouncer(rndMessage);
                    break;
                case RETWEEET:
                    announcerMgr.retweet(status.getId());
                    break;
                case FAVOURITE:
                    announcerMgr.favourite(status.getId());
                    break;
                default:
                    String message = constructAdsMessage(screenName, hashtagEntities,
                            status.getUser().getLang());
                    announcerMgr.reply(message, status.getId());
                    break;
                }

            }
        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
        }
    });

    FilterQuery filterQuery = new FilterQuery();
    filterQuery.count(0);
    filterQuery.track(FILTER_TERMS);
    twitterStream.filter(filterQuery);
}

From source file:com.twitstreet.twitter.FollowBackMgrImpl.java

License:Open Source License

@Override
public void start() {
    Announcer announcer = announcerMgr.randomAnnouncerData();
    twitterProxy = twitterProxyFactory.create(announcer.getAccessToken(), announcer.getAccessTokenSecret());

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
    twitterStream//from   w w  w  .  j a  v a  2  s  . co  m
            .setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));
    twitterStream.addListener(new StatusListener() {

        @Override
        public void onException(Exception arg0) {

        }

        @Override
        public void onTrackLimitationNotice(int arg0) {

        }

        @Override
        public void onStatus(Status status) {
            if (System.currentTimeMillis() - lastFollow > FOLLOW_INTERVAL) {
                twitter4j.User user = status.getUser();
                announcerMgr.follow(user.getId());
                lastFollow = System.currentTimeMillis();
            }
            //            if(System.currentTimeMillis() - lastFollowDiabloBird > FOLLOW_INTERVAL/6){
            //               twitter4j.User user = status.getUser();
            //               announcerMgr.followForDiabloBird(user.getId());
            //               lastFollowDiabloBird = System.currentTimeMillis();
            //            }

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
        }
    });

    FilterQuery filterQuery = new FilterQuery();
    filterQuery.count(0);
    filterQuery.track(FILTER_TERMS);
    twitterStream.filter(filterQuery);
}

From source file:com.twitstreet.twitter.Welcome2ListenerMgrImpl.java

License:Open Source License

@Override
public void start() {
    Announcer announcer = announcerMgr.randomAnnouncerData();
    twitterProxy = twitterProxyFactory.create(announcer.getAccessToken(), announcer.getAccessTokenSecret());

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.setOAuthConsumer(announcer.getConsumerKey(), announcer.getConsumerSecret());
    twitterStream//from  ww  w . j a  v a  2  s  .c  o  m
            .setOAuthAccessToken(new AccessToken(announcer.getAccessToken(), announcer.getAccessTokenSecret()));
    twitterStream.addListener(new StatusListener() {

        @Override
        public void onException(Exception arg0) {

        }

        @Override
        public void onTrackLimitationNotice(int arg0) {

        }

        @Override
        public void onStatus(Status status) {
            UserMentionEntity[] userMentionEntities = status.getUserMentionEntities();
            for (UserMentionEntity userMentionEntity : userMentionEntities) {
                idSet.add(userMentionEntity.getId());
                if (idSet.size() >= TwitterProxyImpl.IDS_SIZE) {
                    List<User> userList = twitterProxy.getTwUsers(new ArrayList<Long>(idSet));
                    if (userList != null) {
                        for (User user : userList) {
                            if (user.getFollowersCount() > MIN_FOLLOWER_COUNT_FOR_TREND) {
                                Stock stock = new Stock(user);
                                stockMgr.saveStock(stock);
                                stockMgr.saveTrend(stock.getId());
                            }
                        }
                    }
                    idSet.clear();
                }
            }
        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
        }
    });

    FilterQuery filterQuery = new FilterQuery();
    filterQuery.count(0);
    filterQuery.track(FILTER_TERMS);
    twitterStream.filter(filterQuery);
}

From source file:com.twitter.graphjet.demo.TwitterStreamReader.java

License:Open Source License

public static void main(String[] argv) throws Exception {
    final TwitterStreamReaderArgs args = new TwitterStreamReaderArgs();

    CmdLineParser parser = new CmdLineParser(args, ParserProperties.defaults().withUsageWidth(90));

    try {//from  w  w  w.ja  v  a 2 s .  c  o  m
        parser.parseArgument(argv);
    } catch (CmdLineException e) {
        System.err.println(e.getMessage());
        parser.printUsage(System.err);
        return;
    }

    final Date demoStart = new Date();
    final MultiSegmentPowerLawBipartiteGraph userTweetBigraph = new MultiSegmentPowerLawBipartiteGraph(
            args.maxSegments, args.maxEdgesPerSegment, args.leftSize, args.leftDegree,
            args.leftPowerLawExponent, args.rightSize, args.rightDegree, args.rightPowerLawExponent,
            new IdentityEdgeTypeMask(), new NullStatsReceiver());

    final MultiSegmentPowerLawBipartiteGraph tweetHashtagBigraph = new MultiSegmentPowerLawBipartiteGraph(
            args.maxSegments, args.maxEdgesPerSegment, args.leftSize, args.leftDegree,
            args.leftPowerLawExponent, args.rightSize, args.rightDegree, args.rightPowerLawExponent,
            new IdentityEdgeTypeMask(), new NullStatsReceiver());

    // Note that we're keeping track of the nodes on the left and right sides externally, apart from the bigraphs,
    // because the bigraph currently does not provide an API for enumerating over nodes. Currently, this is liable to
    // running out of memory, but this is fine for the demo.
    Long2ObjectOpenHashMap<String> users = new Long2ObjectOpenHashMap<>();
    LongOpenHashSet tweets = new LongOpenHashSet();
    Long2ObjectOpenHashMap<String> hashtags = new Long2ObjectOpenHashMap<>();
    // It is accurate of think of these two data structures as holding all users and tweets observed on the stream since
    // the demo program was started.

    StatusListener listener = new StatusListener() {
        long statusCnt = 0;

        public void onStatus(Status status) {

            String screenname = status.getUser().getScreenName();
            long userId = status.getUser().getId();
            long tweetId = status.getId();
            long resolvedTweetId = status.isRetweet() ? status.getRetweetedStatus().getId() : status.getId();
            HashtagEntity[] hashtagEntities = status.getHashtagEntities();

            userTweetBigraph.addEdge(userId, resolvedTweetId, (byte) 0);

            if (!users.containsKey(userId)) {
                users.put(userId, screenname);
            }

            if (!tweets.contains(tweetId)) {
                tweets.add(tweetId);
            }
            if (!tweets.contains(resolvedTweetId)) {
                tweets.add(resolvedTweetId);
            }

            for (HashtagEntity entity : hashtagEntities) {
                long hashtagHash = (long) entity.getText().toLowerCase().hashCode();
                tweetHashtagBigraph.addEdge(tweetId, hashtagHash, (byte) 0);
                if (!hashtags.containsKey(hashtagHash)) {
                    hashtags.put(hashtagHash, entity.getText().toLowerCase());
                }
            }

            statusCnt++;

            // Note that status updates are currently performed synchronously (i.e., blocking). Best practices dictate that
            // they should happen on another thread so as to not interfere with ingest, but this is okay for the pruposes
            // of the demo and the volume of the sample stream.

            // Minor status update: just print counters.
            if (statusCnt % args.minorUpdateInterval == 0) {
                long duration = (new Date().getTime() - demoStart.getTime()) / 1000;

                System.out.println(String.format(
                        "%tc: %,d statuses, %,d unique tweets, %,d unique hashtags (observed); "
                                + "%.2f edges/s; totalMemory(): %,d bytes, freeMemory(): %,d bytes",
                        new Date(), statusCnt, tweets.size(), hashtags.size(), (float) statusCnt / duration,
                        Runtime.getRuntime().totalMemory(), Runtime.getRuntime().freeMemory()));
            }

            // Major status update: iterate over right and left nodes.
            if (statusCnt % args.majorUpdateInterval == 0) {
                int leftCnt = 0;
                LongIterator leftIter = tweets.iterator();
                while (leftIter.hasNext()) {
                    if (userTweetBigraph.getLeftNodeDegree(leftIter.nextLong()) != 0)
                        leftCnt++;
                }

                int rightCnt = 0;
                LongIterator rightIter = hashtags.keySet().iterator();
                while (rightIter.hasNext()) {
                    if (userTweetBigraph.getRightNodeDegree(rightIter.nextLong()) != 0)
                        rightCnt++;
                }
                System.out.println(String.format("%tc: Current user-tweet graph state: %,d left nodes (users), "
                        + "%,d right nodes (tweets)", new Date(), leftCnt, rightCnt));
            }
        }

        public void onScrubGeo(long userId, long upToStatusId) {
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onStallWarning(StallWarning warning) {
        }

        public void onException(Exception e) {
            e.printStackTrace();
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);
    twitterStream.sample();

    ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
    context.setContextPath("/");

    Server jettyServer = new Server(args.port);
    jettyServer.setHandler(context);

    context.addServlet(new ServletHolder(new TopUsersServlet(userTweetBigraph, users)),
            "/userTweetGraph/topUsers");
    context.addServlet(
            new ServletHolder(
                    new TopTweetsServlet(userTweetBigraph, tweets, TopTweetsServlet.GraphType.USER_TWEET)),
            "/userTweetGraph/topTweets");
    context.addServlet(new ServletHolder(
            new TopTweetsServlet(tweetHashtagBigraph, tweets, TopTweetsServlet.GraphType.TWEET_HASHTAG)),
            "/tweetHashtagGraph/topTweets");
    context.addServlet(new ServletHolder(new TopHashtagsServlet(tweetHashtagBigraph, hashtags)),
            "/tweetHashtagGraph/topHashtags");
    context.addServlet(new ServletHolder(new GetEdgesServlet(userTweetBigraph, GetEdgesServlet.Side.LEFT)),
            "/userTweetGraphEdges/users");
    context.addServlet(new ServletHolder(new GetEdgesServlet(userTweetBigraph, GetEdgesServlet.Side.RIGHT)),
            "/userTweetGraphEdges/tweets");
    context.addServlet(new ServletHolder(new GetEdgesServlet(tweetHashtagBigraph, GetEdgesServlet.Side.LEFT)),
            "/tweetHashtagGraphEdges/tweets");
    context.addServlet(new ServletHolder(new GetEdgesServlet(tweetHashtagBigraph, GetEdgesServlet.Side.RIGHT)),
            "/tweetHashtagGraphEdges/hashtags");
    context.addServlet(new ServletHolder(new GetSimilarHashtagsServlet(tweetHashtagBigraph, hashtags)),
            "/similarHashtags");

    System.out.println(String.format("%tc: Starting service on port %d", new Date(), args.port));
    try {
        jettyServer.start();
        jettyServer.join();
    } finally {
        jettyServer.destroy();
    }
}

From source file:com.yahoo.labs.samoa.sentinel.model.TwitterStreamAPIReader.java

License:Apache License

public TwitterStreamAPIReader() {
    twitterStream = new TwitterStreamFactory().getInstance();
    soap = new PipeProcessor();
    listOfTweets = new ArrayList<Tweet>();
}

From source file:crawling.PrintFilterStreamByFile.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStreamByFile ID_File ");
        System.exit(-1);//from   w ww  .  ja v a 2  s .  c o m
    }

    idFile = args[0];
    tweetFile = idFile.split("\\.")[0] + "-tweets.txt";

    try {
        FileWriter outFile = new FileWriter(tweetFile, true);
        out = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            storeTweet(status.getUser().getId() + "::" + status.getText());
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        public void onScrubGeo(long userId, long upToStatusId) {
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        public void onException(Exception ex) {
            ex.printStackTrace();
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(listener);

    // String users = "700896487,701053075,636744543";
    // String[] split = users.split(",");

    buildFollowList();

    long[] followArray = new long[follow.size()];
    for (int i = 0; i < follow.size(); i++) {
        followArray[i] = follow.get(i);
    }
    String[] trackArray = track.toArray(new String[track.size()]);

    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    twitterStream.filter(new FilterQuery(0, followArray, trackArray));
}