Example usage for twitter4j TwitterStreamFactory getInstance

List of usage examples for twitter4j TwitterStreamFactory getInstance

Introduction

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

Prototype

public TwitterStream getInstance() 

Source Link

Document

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

Usage

From source file:twitterGateway_v2_06.java

License:Creative Commons License

public void SetupTwitter() {
    //twitterIn = new TwitterConnectStream();
    //accessToken = new AccessToken(TwitterAccessToken, TwitterAccessTokenSecret);
    //TwitterOAuthAuthorization.setOAuthAccessToken(accessToken);
    //TwitterOAuthAuthorization = new OAuthAuthorization(conf);
    //TwitterOAuthAuthorization.setOAuthConsumer(TwitterConsumerKey, TwitterConsumerSecret);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(TwitterConsumerKey)
            .setOAuthConsumerSecret(TwitterConsumerSecret).setOAuthAccessToken(TwitterAccessToken)
            .setOAuthAccessTokenSecret(TwitterAccessTokenSecret);
    TwitterFactory tf = new TwitterFactory(cb.build());
    twitterOut = tf.getInstance();//from ww  w .j a  v  a  2s.  co m
    //  try {
    //  twitterOut.updateStatus("Hello World!");
    //  }
    //  catch (TwitterException ex) {
    //    println(ex);
    //  }
    ActivityLogAddLine("twitter connector ready");
    output = createWriter("log.txt");

    StatusListener twitterIn = new StatusListener() {
        public void onStatus(Status status) {
            double Longitude;
            double Latitude;
            GeoLocation GeoLoc = status.getGeoLocation();
            if (GeoLoc != null) {
                //println("YES got a location");
                Longitude = GeoLoc.getLongitude();
                Latitude = GeoLoc.getLatitude();
            } else {
                Longitude = 0;
                Latitude = 0;
            }
            println(TimeStamp() + "\t" + Latitude + "\t" + Longitude + "\t" + status.getUser().getScreenName()
                    + "\t" + status.getText());
            output.println(TimeStamp() + "\t" + Latitude + "\t" + Longitude + "\t"
                    + status.getUser().getScreenName() + "\t" + status.getText());
            output.flush();
            TwitterToOsc(status.getUser().getScreenName(), 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) {
            println("CAUGHT in the ACT: " + ex);
        }
    };

    ConfigurationBuilder cbIn = new ConfigurationBuilder();
    cbIn.setDebugEnabled(true).setOAuthConsumerKey(TwitterConsumerKey)
            .setOAuthConsumerSecret(TwitterConsumerSecret).setOAuthAccessToken(TwitterAccessToken)
            .setOAuthAccessTokenSecret(TwitterAccessTokenSecret);

    TwitterStreamFactory ts = new TwitterStreamFactory(cbIn.build());
    TwitterStream twitterStream = ts.getInstance();
    twitterStream.addListener(twitterIn);

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

From source file:Streamer.java

public Streamer(Configuration config, Trending trending) {
    this.trending = trending;

    TwitterStreamFactory tsf = new TwitterStreamFactory(config);
    twitterStream = tsf.getInstance();

    twitterStream.addListener(this);
    filter = new FilterQuery();
    filter.track(trending.getKeyWords());
}

From source file:ac.simons.tweetarchive.config.Twitter4jConfig.java

License:Apache License

@Bean
@ConditionalOnMissingBean//w  ww  .ja v  a 2  s. c  o m
public TwitterStream twitterStream(final TwitterStreamFactory twitterStreamFactory) {
    return twitterStreamFactory.getInstance();
}

From source file:cloudcomputebot.CloudComputeBot.java

License:Open Source License

public static void main(String[] args) {
    TwitterLib.init();/* w w  w  . j a  v  a2  s  .  c o  m*/
    t = TwitterLib.t;
    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(t.getConfiguration());
    TwitterStream twitterStream = twitterStreamFactory.getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.follow(new long[] { 4741197613L });
    twitterStream.addListener(new MentionListener());
    twitterStream.filter(filterQuery);
}

From source file:ColourUs.Stream.java

public Stream(Configuration config, Trending trending) {
    this.trending = trending;

    TwitterStreamFactory tsf = new TwitterStreamFactory(config);
    twitterStream = tsf.getInstance();

    twitterStream.addListener(this);
    filter = new FilterQuery();
    filter.track(new String[] { "I", "you", "he", "she", "them", "they", "us", "our", "her", "him", "they're",
            "I'm", "my", "your", "is", "was", "are", "were" });
}

From source file:com.chimpler.example.TwitterStatusProducer.java

License:Apache License

public synchronized void startSample(String username, String password) {
    if (twitterStream != null) {
        return;/* w  ww .  java2s  .c  o  m*/
    }
    TwitterStreamFactory factory = new TwitterStreamFactory(
            new ConfigurationBuilder().setUser(username).setPassword(password).build());
    twitterStream = factory.getInstance();
    twitterStream.addListener(new StatusAdapter() {
        public void onStatus(Status status) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "OK");
            map.put("createdAt", status.getCreatedAt().toString());
            map.put("username", status.getUser().getName());
            map.put("profileImageUrl", status.getUser().getMiniProfileImageURL());
            map.put("text", status.getText());
            cometTwitterService.publishMessage(map, Long.toString(status.getId()));
        }

        @Override
        public void onException(Exception ex) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "ERR");
            map.put("text", ex.getMessage());
            cometTwitterService.publishMessage(map, "-1");
            stopSample();
        }
    });
    logger.log(Level.INFO, "Starting listening to twitter sample");
    twitterStream.sample();
}

From source file:com.daiv.android.twitter.utils.Utils.java

License:Apache License

public static TwitterStream getStreamingTwitter(Context context, AppSettings settings) {
    settings = AppSettings.getInstance(context);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(AppSettings.TWITTER_CONSUMER_KEY)
            .setOAuthConsumerSecret(AppSettings.TWITTER_CONSUMER_SECRET)
            .setOAuthAccessToken(settings.authenticationToken)
            .setOAuthAccessTokenSecret(settings.authenticationTokenSecret);
    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());
    return tf.getInstance();
}

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

License:Apache License

@Singleton
@Provides/*  www.  j a  va 2s .  c  o  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.jcustenborder.kafka.connect.twitter.TwitterSourceTask.java

License:Apache License

@Override
public void start(Map<String, String> map) {
    this.config = new TwitterSourceConnectorConfig(map);

    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(this.config.configuration());
    this.twitterStream = twitterStreamFactory.getInstance();

    String[] keywords = this.config.filterKeywords();

    if (log.isInfoEnabled()) {
        log.info("Setting up filters. Keywords = {}", Joiner.on(", ").join(keywords));
    }/*from  ww w .j a va 2s.  co m*/

    FilterQuery filterQuery = new FilterQuery();
    filterQuery.track(keywords);

    if (log.isInfoEnabled()) {
        log.info("Starting the twitter stream.");
    }
    twitterStream.addListener(this);
    twitterStream.filter(filterQuery);
}

From source file:com.producer.TwitterProducer.java

License:Apache License

public static void main(String[] args) {

    if (args.length == 0) {
        System.out.println(/*w  ww  .  j a va  2 s  . c  o m*/
                "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);
}