Example usage for twitter4j TwitterStream filter

List of usage examples for twitter4j TwitterStream filter

Introduction

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

Prototype

TwitterStream filter(final String... track);

Source Link

Document

Start consuming public statuses that match the filter predicate.

Usage

From source file:Read_data.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException// ww  w  .j ava  2s.c o  m
 * @throws java.io.FileNotFoundException
 */
public static void main(String[] args) throws TwitterException, FileNotFoundException, IOException {
    // TODO code application logic here

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(customer_key).setOAuthConsumerSecret(customer_secret)
            .setOAuthAccessToken(access_token).setOAuthAccessTokenSecret(access_token_secret);

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

    StatusListener statusListener = new StatusListener() {

        @Override
        public void onStatus(Status status) {

            //get the place if it is not null
            if (status.getPlace() != null) {

                try {

                    String place = status.getPlace().getName();

                    System.out.println("Place: " + place + "\t\t\t" + "Tweet: " + status.getText());

                    Thread.sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Read_data.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        @Override

        public void onDeletionNotice(StatusDeletionNotice sdn) {
            System.out.print("");
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            System.out.print("");
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            System.out.print("");
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            System.out.println(sw);
        }

        @Override
        public void onException(Exception ex) {
            System.out.println(ex);
        }
    };

    FilterQuery fq = new FilterQuery();

    //Stream tweets with these keywords. Replace for your tweets that you are looking for.
    String keywords[] = { "lol", "lls", "lmao", "llf" };

    fq.track(keywords);

    twitterStream.addListener(statusListener);
    twitterStream.filter(fq);

    try {
        synchronized (lock) {
            lock.wait();
        }
    } catch (InterruptedException e) {
        System.out.println(e);
    }
    System.out.println("returning statuses");
    // twitterStream.shutdown();
}

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 w w  w. j a v a 2  s. c o  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:PrintFilterStream.java

License:Apache License

/**
 * Main entry of this application.//  w  w w  .j  av  a2  s.com
 *
 * @param args follow(comma separated user ids) track(comma separated filter terms)
 * @throws TwitterException when Twitter service or network is unavailable
 */
public static void main(String[] args) throws TwitterException {
    if (args.length < 1) {
        System.out.println(
                "Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]");
        System.exit(-1);
    }

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

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

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

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

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }

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

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey("");
    cb.setOAuthConsumerSecret("");
    cb.setOAuthAccessToken("");
    cb.setOAuthAccessTokenSecret("");

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

    twitterStream.addListener(listener);
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();
    for (String arg : args) {
        if (isNumericalArgument(arg)) {
            for (String id : arg.split(",")) {
                follow.add(Long.parseLong(id));
            }
        } else {
            track.addAll(Arrays.asList(arg.split(",")));
        }
    }
    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));
}

From source file:TwitterListenerSnippet.java

License:BEER-WARE LICENSE

public void setupListener(Configuration c) {
    filtreListener = "love";
    TwitterStream ts = new TwitterStreamFactory(c).getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.track(new String[] { filtreListener });
    // On fait le lien entre le TwitterStream (qui r\u00e9cup\u00e8re les messages) et notre \u00e9couteur  
    ts.addListener(new TwitterListener());
    // On d\u00e9marre la recherche !
    ts.filter(filterQuery);
}

From source file:adapter.TwitterKeywordsAdapter.java

License:Apache License

public void connectAndRead() throws Exception {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    Properties twitterProperties = new Properties();
    File twitter4jPropsFile = new File("../twitter4j.properties");
    if (!twitter4jPropsFile.exists()) {
        logger.error("Cannot find twitter4j.properties file in this location :[{}]",
                twitter4jPropsFile.getAbsolutePath());
        return;//from   w  w  w  . ja v a 2 s . c  om
    }

    twitterProperties.load(new FileInputStream(twitter4jPropsFile));

    cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(twitterProperties.getProperty("oauth.consumerKey"));
    cb.setOAuthConsumerSecret(twitterProperties.getProperty("oauth.consumerSecret"));
    cb.setOAuthAccessToken(twitterProperties.getProperty("oauth.accessToken"));
    cb.setOAuthAccessTokenSecret(twitterProperties.getProperty("oauth.accessTokenSecret"));

    cb.setDebugEnabled(false);
    cb.setPrettyDebugEnabled(false);
    cb.setIncludeMyRetweetEnabled(false);

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

    StatusListener statusListener = new StatusListener() {
        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onStatus(Status status) {
            messageQueue.add(status);
        }

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

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    FilterQuery fq = new FilterQuery();

    //System.out.println(Arrays.toString(configuration.getTrack()));

    //Elige todos los tweets que posean esas palabras claves
    fq.track(new String[] { "palabra1,palabra2,palabra3" });
    //fq.track(keywords);
    twitterStream.addListener(statusListener);
    twitterStream.filter(fq);
}

From source file:adapter.TwitterLanguageAdapter.java

License:Apache License

public void connectAndRead() throws Exception {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    Properties twitterProperties = new Properties();
    File twitter4jPropsFile = new File("../twitter4j.properties");
    if (!twitter4jPropsFile.exists()) {
        logger.error("Cannot find twitter4j.properties file in this location :[{}]",
                twitter4jPropsFile.getAbsolutePath());
        return;/*  w w w. j a  v a 2s  . c  o m*/
    }

    twitterProperties.load(new FileInputStream(twitter4jPropsFile));

    cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(twitterProperties.getProperty("oauth.consumerKey"));
    cb.setOAuthConsumerSecret(twitterProperties.getProperty("oauth.consumerSecret"));
    cb.setOAuthAccessToken(twitterProperties.getProperty("oauth.accessToken"));
    cb.setOAuthAccessTokenSecret(twitterProperties.getProperty("oauth.accessTokenSecret"));

    cb.setDebugEnabled(false);
    cb.setPrettyDebugEnabled(false);
    cb.setIncludeMyRetweetEnabled(false);

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

    StatusListener statusListener = new StatusListener() {
        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onStatus(Status status) {
            messageQueue.add(status);
        }

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

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    //Filter language and track
    FilterQuery tweetFilterQuery = new FilterQuery();
    tweetFilterQuery.track(new String[] { "palabra1,palabra2,palabra3" });
    tweetFilterQuery.language(new String[] { "es" });

    //TwitterStream
    twitterStream.addListener(statusListener);
    twitterStream.filter(tweetFilterQuery);
}

From source file:adapter.TwitterLocationAdapter.java

License:Apache License

public void connectAndRead() throws Exception {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    Properties twitterProperties = new Properties();
    File twitter4jPropsFile = new File("../twitter4j.properties");
    if (!twitter4jPropsFile.exists()) {
        logger.error("Cannot find twitter4j.properties file in this location :[{}]",
                twitter4jPropsFile.getAbsolutePath());
        return;//  w w  w  .jav  a2 s.co m
    }

    twitterProperties.load(new FileInputStream(twitter4jPropsFile));

    cb = new ConfigurationBuilder();

    cb.setOAuthConsumerKey(twitterProperties.getProperty("oauth.consumerKey"));
    cb.setOAuthConsumerSecret(twitterProperties.getProperty("oauth.consumerSecret"));
    cb.setOAuthAccessToken(twitterProperties.getProperty("oauth.accessToken"));
    cb.setOAuthAccessTokenSecret(twitterProperties.getProperty("oauth.accessTokenSecret"));

    cb.setDebugEnabled(false);
    cb.setPrettyDebugEnabled(false);
    cb.setIncludeMyRetweetEnabled(false);

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

    StatusListener statusListener = new StatusListener() {
        @Override
        public void onException(Exception ex) {
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        @Override
        public void onStatus(Status status) {
            messageQueue.add(status);
        }

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

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

    };

    FilterQuery fq = new FilterQuery();
    // Posiciones geogrficas, esas dos coordenadas son el vrtice superior izquierda e inferior derecho
    // de un rectangulo, de tal manera de analizar solo una parte geografica
    double position[][] = { { 0.0, 0.0 }, { 0.0, 0.0 } };
    fq.locations(position);

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

From source file:at.aictopic1.twitter.AICStream.java

public void startStream() {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(getListener());

    twitterStream.filter(getQuery());

}

From source file:at.illecker.sentistorm.spout.TwitterStreamSpout.java

License:Apache License

@Override
public void open(Map config, TopologyContext context, SpoutOutputCollector collector) {
    m_collector = collector;//from   ww w  .j a  va2  s.co  m
    m_tweetsQueue = new LinkedBlockingQueue<Status>(1000);

    // Optional startup sleep to finish bolt preparation
    // before spout starts emitting
    if (config.get(CONF_STARTUP_SLEEP_MS) != null) {
        long startupSleepMillis = (Long) config.get(CONF_STARTUP_SLEEP_MS);
        TimeUtils.sleepMillis(startupSleepMillis);
    }

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

    // Set Listener
    twitterStream.addListener(new StatusListener() {
        @Override
        public void onStatus(Status status) {
            m_tweetsQueue.offer(status); // add tweet into queue
        }

        @Override
        public void onException(Exception arg0) {
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
        }

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

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
        }
    });

    // Set credentials
    twitterStream.setOAuthConsumer(m_consumerKey, m_consumerSecret);
    AccessToken token = new AccessToken(m_accessToken, m_accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    // Filter twitter stream
    FilterQuery tweetFilterQuery = new FilterQuery();
    if (m_keyWords != null) {
        tweetFilterQuery.track(m_keyWords);
    }

    // Filter location
    // https://dev.twitter.com/docs/streaming-apis/parameters#locations
    tweetFilterQuery.locations(new double[][] { new double[] { -180, -90, }, new double[] { 180, 90 } }); // any geotagged tweet

    // Filter language
    tweetFilterQuery.language(new String[] { m_filterLanguage });

    twitterStream.filter(tweetFilterQuery);
}

From source file:at.storm.spout.TwitterStreamSpout.java

License:Apache License

@SuppressWarnings("rawtypes")
@Override// w ww . j  av a  2s . c  o  m
public void open(Map config, TopologyContext context, SpoutOutputCollector collector) {
    m_collector = collector;
    m_tweetsQueue = new LinkedBlockingQueue<Status>(1000);

    // Optional startup sleep to finish bolt preparation
    // before spout starts emitting
    if (config.get(CONF_STARTUP_SLEEP_MS) != null) {
        long startupSleepMillis = (Long) config.get(CONF_STARTUP_SLEEP_MS);
        TimeUtils.sleepMillis(startupSleepMillis);
    }

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

    // Set Listener
    twitterStream.addListener(new StatusListener() {
        @Override
        public void onStatus(Status status) {
            m_tweetsQueue.offer(status); // add tweet into queue
        }

        @Override
        public void onException(Exception arg0) {
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
        }

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

        @Override
        public void onStallWarning(StallWarning arg0) {
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
        }
    });

    // Set credentials
    twitterStream.setOAuthConsumer(m_consumerKey, m_consumerSecret);
    AccessToken token = new AccessToken(m_accessToken, m_accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    // Filter twitter stream
    FilterQuery tweetFilterQuery = new FilterQuery();
    if (m_keyWords != null) {
        tweetFilterQuery.track(m_keyWords);
    }

    // Filter location
    // https://dev.twitter.com/docs/streaming-apis/parameters#locations
    tweetFilterQuery.locations(new double[][] { new double[] { -180, -90, }, new double[] { 180, 90 } }); // any
    // geotagged
    // tweet

    // Filter language
    tweetFilterQuery.language(new String[] { m_filterLanguage });

    twitterStream.filter(tweetFilterQuery);
}