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(String configTreePath) 

Source Link

Document

Creates a TwitterStreamFactory with a specified config tree.

Usage

From source file:com.mycompany.mech2015task.App.java

public static void main(String[] args) throws Exception {
    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(CONSUMER_KEY);
    builder.setOAuthConsumerSecret(CONSUMER_SECRET);
    builder.setOAuthAccessToken(ACCESS_TOKEN);
    builder.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);

    // ??Twitter4J??API???betastream.twitter.com???????
    builder.setUserStreamBaseURL("https://userstream.twitter.com/2/");

    // Configuration?
    Configuration configuration = builder.build();

    /*        Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
        .setOAuthConsumerSecret(CONSUMER_SECRET)
        .setOAuthAccessToken(ACCESS_TOKEN)
        .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET)
        .build();//from w w  w .jav a  2s  . c  o m
    */
    TwitterStream twStream = new TwitterStreamFactory(configuration).getInstance();
    //TwitterStream twStream = new TwitterStreamFactory().getInstance();
    twStream.addListener(new MyStatusListener());
    twStream.user();
    //twStream.sample();
}

From source file:com.mycompany.omnomtweets.Search.java

public static void main(String[] args) throws TwitterException {
    System.setProperty("twitter4j.loggerFactory", "twitter4j.internal.logging.NullLoggerFactory");
    if (args.length >= 1) {
        candidate = Candidate.valueOf(args[0]);
        System.out.println("Getting tweets on " + candidate.name);
    } else {/*w w w. j  a  v a2s.  c  o m*/
        //System.out.println("You didn't give me a candidate, so you get TRUMP");
    }
    //System.out.println("Starting at: " + sdf.format(new Date()));
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(candidate.consumerKey)
            .setOAuthConsumerSecret(candidate.consumerSecret).setOAuthAccessToken(candidate.accessToken)
            .setOAuthAccessTokenSecret(candidate.accessTokenSecret);

    final ArrayList<Status> statuses = new ArrayList<>();

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            statuses.add(status);
            writeToStdErr(status);
            //Removed because writing to STD OUT instead.
            //System.out.println("statuses: " + statuses.size());
            if (statuses.size() >= 100) {
                /*System.out.println("Writing " + statuses.size() + " to file " + 
                            "at: " + sdf.format(new Date()));*/
                writeTweetsToFile(statuses, candidate.name + "StreamTweets.txt");
                statuses.clear();
            }
        }

        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 sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    };

    FilterQuery fq = new FilterQuery();
    String keywords[] = candidate.aliases;

    fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.filter(fq);
}

From source file:com.narvis.frontend.twitter.AccessTwitter.java

License:Open Source License

private Pair<TwitterStream, Twitter> loadAccessTwitter(String token, String tokenSecret, String consumerKey,
        String consumerSecret) {//  ww  w .j a  v  a 2  s.c om
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(token);
    cb.setOAuthAccessTokenSecret(tokenSecret);
    Configuration authConf = cb.build();
    return new Pair(new TwitterStreamFactory(authConf).getInstance(),
            new TwitterFactory(authConf).getInstance());
}

From source file:com.producer.TwitterProducer.java

License:Apache License

public static void main(String[] args) {

    if (args.length == 0) {
        System.out.println(// w  w w.j  a va  2 s.c  om
                "SimpleCounter {broker-list} {topic} {type old/new} {type sync/async} {delay (ms)} {count}");
        return;
    }

    /* get arguments */
    String brokerList = args[0];
    String topic = args[1];
    String age = args[2];
    String sync = args[3];
    /*
     * In order to create the spout, you need to get twitter credentials
     * If you need to use Twitter firehose/Tweet stream for your idea,
     * create a set of credentials by following the instructions at
     *
     * https://dev.twitter.com/discussions/631
     *
     */
    String custkey = "WXDgVgeJMwHEn0Z9VHDx5j93h";
    String custsecret = "DgP9CsaPtG87urpNU14fZySXOjNX4j4v2PqmeTndcjjYBgLldy";
    String accesstoken = "3243813491-ixCQ3HWWeMsthKQvj5MiBvNw3dSNAuAd3IfoDUw";
    String accesssecret = "aHOXUB4nbhZv2vbAeV15ZyTAD0lPPCptCr32N0PX7OaMe";

    producer = new DemoProducerOld(topic);

    /* start a producer */
    producer.configure(brokerList, sync);
    producer.start();

    //long startTime = System.currentTimeMillis();
    System.out.println("Starting...");
    producer.produce("Starting...");

    ConfigurationBuilder config = new ConfigurationBuilder().setOAuthConsumerKey(custkey)
            .setOAuthConsumerSecret(custsecret).setOAuthAccessToken(accesstoken)
            .setOAuthAccessTokenSecret(accesssecret);

    // create the twitter stream factory with the config
    TwitterStream twitterStream;
    TwitterStreamFactory fact = new TwitterStreamFactory(config.build());

    // get an instance of twitter stream
    twitterStream = fact.getInstance();
    // message to kafka
    Map<String, String> headers = new HashMap<String, String>();

    //filter non-english tweets
    FilterQuery tweetFilterQuery = new FilterQuery();
    tweetFilterQuery.language(new String[] { "en" });
    // tweetFilterQuery.locations(new double[][] { { -180, -90 }, { 180, 90 } });

    // provide the handler for twitter stream
    twitterStream.addListener(new TweetListener());

    twitterStream.filter(tweetFilterQuery);

    // start the sampling of tweets
    twitterStream.sample();

    // TODO ADD timestamp
    //long endTime = System.currentTimeMillis();
    //System.out.println("... and we are done. This took " + (endTime - startTime) + " ms.");
    //producer.produce("... and we are done. This took " + (endTime - startTime) + " ms.");

    /* close shop and leave */
    //producer.close();
    //System.exit(0);
}

From source file:com.pulzitinc.flume.source.TwitterSource.java

License:Apache License

/**
 * The initialization method for the Source. The context contains all the
 * Flume configuration info, and can be used to retrieve any configuration
 * values necessary to set up the Source.
 *//*from   w w w .  ja  v a  2 s.co m*/
@Override
public void configure(Context context) {

    logger.info(context.toString());

    consumerKey = context.getString(TwitterSourceConstants.CONSUMER_KEY_KEY);
    consumerSecret = context.getString(TwitterSourceConstants.CONSUMER_SECRET_KEY);
    accessToken = context.getString(TwitterSourceConstants.ACCESS_TOKEN_KEY);
    accessTokenSecret = context.getString(TwitterSourceConstants.ACCESS_TOKEN_SECRET_KEY);

    String accountIdsString = context.getString(TwitterSourceConstants.ACCOUNT_IDS_KEY, "");
    if (accountIdsString.trim().length() == 0) {
        throw new IllegalStateException("No accounts to follow provided");
    } else {
        String[] accountIds = accountIdsString.split(",");
        accountsToFollow = new long[accountIds.length];
        for (int i = 0; i < accountIds.length; i++) {
            accountsToFollow[i] = Long.valueOf(accountIds[i]);
        }
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey(consumerKey);
    cb.setOAuthConsumerSecret(consumerSecret);
    cb.setOAuthAccessToken(accessToken);
    cb.setOAuthAccessTokenSecret(accessTokenSecret);
    cb.setJSONStoreEnabled(true);
    cb.setIncludeEntitiesEnabled(true);

    twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
}

From source file:com.redhat.middleware.jdg.TwitterDemoClient.java

License:Open Source License

public void startAsync() {

    ConfigurationBuilder cb = new ConfigurationBuilder();

    if (accessTokenSecret == null || accessToken == null) {
        try {/*from  ww w  .ja  v  a  2 s  .c om*/
            this.authorize();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "error occured while authorizing", e);
        }
    }

    cb.setDebugEnabled(false).setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret)
            .setOAuthAccessToken(accessToken).setOAuthAccessTokenSecret(accessTokenSecret);

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    twitterStream.addListener(new DemoTwitterListener(twitterStream));
    twitterStream.sample();
}

From source file:com.richardstansbury.tweetfollow.TwitterHelper.java

License:Open Source License

/**
 * Constructor/*from w  w  w.ja  va 2s.  com*/
 * @param tweets - an array list to store _tweets received by this class
 * @param parentActivity - _parent activity that this helper is running on
 * @param adapter - array _adapter that is being updated by this class.
 */
public TwitterHelper(List<String> tweets, Activity parentActivity, ArrayAdapter<String> adapter) {
    //Set up the Twitter Stream FActor and listener.
    this._twitter = new TwitterStreamFactory(readConfiguration(parentActivity)).getInstance();
    this._twitter.addListener(this);

    //Copy parameters to class variables
    this._tweets = tweets;
    this._parent = parentActivity;
    this._adapter = adapter;
}

From source file:com.saugereau.spout.TwitterSpout.java

License:Apache License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<Status>(1000);
    _collector = collector;/*  ww w .j  a  v a2  s.  c  om*/

    StatusListener listener = new StatusListener() {

        @Override
        public void onStatus(Status status) {

            queue.offer(status);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            LOG.info("Got track limitation notice:" + i);
        }

        @Override
        public void onScrubGeo(long l, long l1) {
        }

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

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

        }

    };

    _twitterStream = new TwitterStreamFactory(new ConfigurationBuilder().setJSONStoreEnabled(true).build())
            .getInstance();

    _twitterStream.addListener(listener);
    _twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    _twitterStream.setOAuthAccessToken(token);

    if (keyWords.length == 0) {

        _twitterStream.sample();
    }

    else {

        FilterQuery query = new FilterQuery().track(keyWords);
        query.language(new String[] { "en" });
        _twitterStream.filter(query);
    }

}

From source file:com.sinfonier.spouts.Twitter.java

License:Apache License

/**
 * Create a TwitterStream. Requires Twitter API keys.
 * /*  w  ww  . java  2 s. c  o  m*/
 * @return {@link twitter4j.TwitterStream}
 */
private TwitterStream createTwitterStream() {

    ConfigurationBuilder config = new ConfigurationBuilder();
    config.setOAuthConsumerKey(xml.get(CONSUMER_KEY, true));
    config.setOAuthConsumerSecret(xml.get(CONSUMER_SECRET, true));
    config.setOAuthAccessToken(xml.get(ACCESS_TOKEN, true));
    config.setOAuthAccessTokenSecret(xml.get(ACCESS_TOKEN_SECRET, true));
    config.setJSONStoreEnabled(true);
    config.setIncludeEntitiesEnabled(true);

    return new TwitterStreamFactory(config.build()).getInstance();
}

From source file:com.storm.demo.TwitterSampleSpout.java

License:Apache License

@Override
public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<String>(1000);
    _collector = collector;/*from   www  .  java2s. c  om*/

    //        StatusListener listener = new StatusListener() {
    //
    //            @Override
    //            public void onStatus(Status status) {
    //                System.out.println(DataObjectFactory.getRawJSON(status));
    //                queue.offer(status);
    //            }
    //
    //            @Override
    //            public void onDeletionNotice(StatusDeletionNotice sdn) {
    //            }
    //
    //            @Override
    //            public void onTrackLimitationNotice(int i) {
    //            }
    //
    //            @Override
    //            public void onScrubGeo(long l, long l1) {
    //            }
    //
    //            @Override
    //            public void onException(Exception ex) {
    //            }
    //
    //            @Override
    //            public void onStallWarning(StallWarning arg0) {
    //                // TODO Auto-generated method stub
    //
    //            }
    //
    //        };

    RawStreamListener rawListener = new RawStreamListener() {
        @Override
        public void onMessage(String rawJSON) {
            //System.out.println(rawJSON);
            queue.offer(rawJSON);
        }

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

    TwitterStream twitterStream = new TwitterStreamFactory(
            new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance();

    //twitterStream.addListener(listener);
    twitterStream.addListener(rawListener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    if (keyWords.length == 0) {

        twitterStream.sample();
    }

    else {

        FilterQuery query = new FilterQuery().track(keyWords);
        twitterStream.filter(query);
    }

}