Example usage for twitter4j TwitterStream addListener

List of usage examples for twitter4j TwitterStream addListener

Introduction

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

Prototype

TwitterStream addListener(StreamListener listener);

Source Link

Usage

From source file:twitter.stream.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application./*  w  w  w.  ja  v  a2 s  . c om*/
 *
 * @param args
 *            arguments doesn't take effect with this example
 * @throws TwitterException
 *             when Twitter service or network is unavailable
 */
public static void main(String[] args) throws TwitterException {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            if (status.getGeoLocation() != null)
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + "Lat:"
                        + status.getGeoLocation().getLatitude() + "Long"
                        + status.getGeoLocation().getLongitude());
        }

        @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();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.sample();
}

From source file:twitter4j.examples.lambda.TwitterStreamLambda.java

License:Apache License

public static void oldTraditionalDullBoringImplementation(String... dummy) {
    // Twitter4J 4.0.3 or earlier
    TwitterStream stream = TwitterStreamFactory.getSingleton();
    stream.addListener(new StatusAdapter() {
        @Override/*from  w ww .java 2 s .  c  om*/
        public void onStatus(Status status) {
            String.format("@%s %s", status.getUser().getScreenName(), status.getText());
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    });
    stream.filter(new FilterQuery(new String[] { "twitter4j", "#twitter4j" }));
}

From source file:twitterapp.TwitterApp.java

public static void streamTweets() throws TwitterException {
    /*getting the trends */
    ConfigurationBuilder cb2 = new ConfigurationBuilder();

    cb2.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge");

    TwitterFactory tf = new TwitterFactory(cb2.build());
    Twitter twitter = tf.getInstance();/*from w  w w  .j  a v a 2s  .  c om*/
    Trends trends = twitter.getPlaceTrends(23424977);

    String top_trend = "";
    int top = 0;
    for (Trend trend : trends.getTrends()) {
        if (top < 1) {
            top_trend = trend.getName();
            top++;
        }
    }

    System.out.println("top trend : " + top_trend);

    //Using the Streaming API to get real time tweets based on the trending topics as keywords
    /* configurating twiter4j */

    ConfigurationBuilder cb = new ConfigurationBuilder();

    cb.setDebugEnabled(true).setOAuthConsumerKey("S01GsVwuCAwZFp5BLg5C4k8PT")
            .setOAuthConsumerSecret("6jo0jo4b05Ec5ZJcf74v5yGUQu5v8DryUwypOBjPD6jaItRNzd")
            .setOAuthAccessToken("794259549297446912-Z3AWruBmLa7QmCO6BnybCSj1tZXNqbB")
            .setOAuthAccessTokenSecret("6ezMQPQVziW9yxyTITZA8Wc2RJWjcBKvbXZU4dOjo4bge")
            .setJSONStoreEnabled(true);
    /* end of configuration */

    MongoClient mongo = new MongoClient("localhost", 27017);
    MongoDatabase database = mongo.getDatabase("myTweetdb2");
    MongoCollection<Document> collection = database.getCollection("myTweetCol5");
    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {

            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            Document doc = Document.parse(rawJSON);

            collection.insertOne(doc);

        }

        @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();
        }
    };

    // twitterStream.sample();
    twitterStream.addListener(listener);
    FilterQuery fq = new FilterQuery();

    String keywords[] = { top_trend };
    fq.track(keywords);
    twitterStream.filter(fq);
}

From source file:TwitterCrawler.PrintSampleStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {

    System.getProperties().put("http.proxyHost", "127.0.0.1");
    System.getProperties().put("http.proxyPort", "8580");

    //final PrintSampleStream pr = new PrintSampleStream();

    try {//w  ww.j  a  v  a  2s .co  m
        pr.LinkMongodb();
    } catch (Exception e) {
        e.printStackTrace();
    }

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("7ZVgfKiOvBDcDFpytRWSA")
            .setOAuthConsumerSecret("JmeJVeym78arzmGthrDUshQyhkq6nWA9tWLUKxc")
            .setOAuthAccessToken("321341780-Zy7LptVYBZBVvAeQ5GFJ4aKFw8sdqhWBnvA3pDuO")
            .setOAuthAccessTokenSecret("foi8FnQCeN0J5cdwad05Q6d7dbytFayQn1ZOvmhF6Qc");
    cb.setJSONStoreEnabled(true);

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

    StatusListener listener = new StatusListener() {

        @Override
        public void onException(Exception ex) {
            // TODO Auto-generated method stub
            ex.printStackTrace();
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            // TODO Auto-generated method stub
            System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());

        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            // TODO Auto-generated method stub
            System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());  
            //System.out.println(status);  
            String str = DataObjectFactory.getRawJSON(status);
            try {
                //JSONObject nnstr = new JSONObject(newstr);  
                DBObject dbObject = (DBObject) JSON.parse(str);
                pr.collection.insert(dbObject);
                System.out.println(dbObject);
                pr.count++;
                /* if(pr.count>300000) {  
                pr.mongo.close();  
                System.exit(0);  
                 }  */
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            // TODO Auto-generated method stub
            System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);

        }

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

        }

    };
    twitterStream.addListener(listener);

    //String[] Track = {"why Obama look like he about to drop the best album of 2013?"}; 
    String[] trackArray = { "Mac", "App", "Store" };
    //trackArray[1] = ;  

    // Create a FilterQuery object and then set the items to track
    FilterQuery filter = new FilterQuery();

    // Create an array of items to track
    //String[] itemsToTrack = {""}; 
    // Set the items to track using FilterQuerys' track method.
    //filter.track(Track); 
    filter.track(trackArray);

    // Assuming you have already created Twitter/TwitterStream object, 
    // use the filter method to start streaming using the FilterQuery object just created.
    twitterStream.filter(filter);

    /* String[] username = {"katyperry"};
     twitterStream.addListener(userlistener);  
     twitterStream.user();*/
    //pr.mongo.close();
}

From source file:twittermongodbapp.CollectTweets.java

static public void getTopTrends(twitter4j.Twitter twitter, TwitterStream twitterStream,
        StatusListener listener) {//from  w  ww  .j  av a 2 s.  c  o  m
    FilterQuery filterQuery = new FilterQuery();

    Timer t = new Timer();
    t.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            Trends trends;
            try {
                trends = twitter.getPlaceTrends(23424833);//trends = twitter.getPlaceTrends(1);(23424833)
                String[] keywords = new String[trends.getTrends().length];
                System.out.println("Top Trends in Greece");
                for (int i = 0; i < trends.getTrends().length; i++) {
                    keywords[i] = trends.getTrends()[i].getName();
                    System.out.println(keywords[i]);
                }
                filterQuery.track(keywords);
                filterQuery.language(new String[] { "el" });
                twitterStream.addListener(listener);
                twitterStream.filter(filterQuery);
            } catch (TwitterException ex) {
                Logger.getLogger(TwitterMongoDBApp.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }, 1000, 360000);

}

From source file:twitterstreamsample.NewJFrame.java

private void ClickActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ClickActionPerformed
    // TODO add your handling code here:

    String consKey = "Your key";
    String consSecret = "Your Secret";
    String accToken = "Your token";
    String accSecret = "Your secret";

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            textArea.append(status.getUser().getName() + ":" + status.getText());
        }//  www .ja  va 2s  . c  o  m

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

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

        @Override
        public void onScrubGeo(long l, long l1) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

    };

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

    twitterStream.setOAuthConsumer(consKey, consSecret);

    twitterStream.setOAuthAccessToken(new AccessToken(accToken, accSecret));

    twitterStream.addListener(listener);

    twitterStream.sample();

}

From source file:twittertweetscollection.TwitterTweetsCollection.java

public List<Status> execute() throws TwitterException {

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

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("I7WYWBE6eSNKdV4FYSyiuP0uk")
            .setOAuthConsumerSecret("oft7Y6WcUCvxovPU5modCZ3BOlHH2z9Px73UkFMILN4ltBhOni")
            .setOAuthAccessToken("3524247253-o7zXFn3r8PwPb4IUTYqHRQzVabTzfoFn9Ck7FzW")
            .setOAuthAccessTokenSecret("V7zkLiJmF0vsdX8rUdkXo3q1ha452vKqVtB5OoCuQWAgR");

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

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            statuses.add(status);//from  w w  w  .  ja  v  a 2s .c  o m
            System.out.println(statuses.size() + ":" + status.getText());
            if (statuses.size() > 100) {
                synchronized (lock) {
                    lock.notify();
                }
                System.out.println("unlocked");
            }
        }

        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) {
            System.out.println(sw.getMessage());

        }
    };

    //FilterQuery fq = new FilterQuery();
    //String keywords[] = { "SuperBowlSunday"};

    //fq.track(keywords);

    twitterStream.addListener(listener);
    twitterStream.sample();
    //twitterStream.filter(fq);

    try {
        synchronized (lock) {
            lock.wait();
        }
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("returning statuses");
    twitterStream.shutdown();
    return statuses;
}

From source file:user_streaming.UserStream.java

License:Apache License

public static void main(String[] args) throws Exception {
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET)
            .setUserStreamBaseURL("https://userstream.twitter.com/2/").build();

    TwitterStream UserStream = new TwitterStreamFactory(configuration).getInstance();
    UserStream.addListener(new MyStreamAdapter());
    long[] follow = { 1038644269 };//ex)????????anondroid3?id:1598997848
    FilterQuery filter = new FilterQuery(follow);//?userID?????
    UserStream.filter(filter);/*w  w  w  .j a  v a 2 s.  c  o m*/
}

From source file:wordgame.WordGame.java

public static void initGame(String file) throws FileNotFoundException {
    Scanner s = new Scanner(new File(file)); //open the file
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true) //populate the twitter details with the proper API informatin
            .setOAuthConsumerKey(s.nextLine()).setOAuthConsumerSecret(s.nextLine())
            .setOAuthAccessToken(s.nextLine()).setOAuthAccessTokenSecret(s.nextLine());
    TwitterFactory tf = new TwitterFactory(cb.build());
    t = tf.getInstance();//from  w w w . ja v a 2  s  .  co m
    TwitterStreamFactory twitterStreamFactory = new TwitterStreamFactory(t.getConfiguration());
    TwitterStream twitterStream = twitterStreamFactory.getInstance();
    FilterQuery filterQuery = new FilterQuery();
    filterQuery.follow(new long[] { 731852008030916608L }); //Track our tweets
    twitterStream.addListener(new MentionListener()); //Set the listener to our MentionListener class
    twitterStream.filter(filterQuery); //begin listening
}

From source file:ws.project.languagebasedlexiconanalisys.TwitterStreamAnalizer.java

void parseStream() throws IOException {
    //Inizializza file JSON
    FileWriter file = new FileWriter("data.json");
    JSONObject obj = new JSONObject();
    final JSONArray data = new JSONArray();
    obj.put("data", data);
    file.write(obj.toJSONString());/*w  w w  . j  av  a  2s  .  com*/
    file.flush();
    file.close();

    SimpleDateFormat currentDate = new SimpleDateFormat();
    currentDate.applyPattern("dd-MM-yyyy");
    final String currentDateStr = currentDate.format(new Date());

    ConfigurationBuilder cfg = new ConfigurationBuilder();
    cfg.setOAuthAccessToken("3065669171-9Hp3VZbz7f0BCsvWWFfgywgqimSIp1AlT98745S");
    cfg.setOAuthAccessTokenSecret("AUmg0AdhHzMXisnP1WV7Wnsw5amWFQPyIojI5aBG5qV4A");
    cfg.setOAuthConsumerKey("arieQRhL2WwgRFfXFLAJp5Hkw");
    cfg.setOAuthConsumerSecret("NvmWqgN1UKKPUWoh9d9Z2PuQobOah8IR5faqX2WjDGBL053sWE");

    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            SimpleDateFormat tweetDate = new SimpleDateFormat();
            tweetDate.applyPattern("dd-MM-yyyy");
            String tweetDateStr = tweetDate.format(status.getCreatedAt());

            try {
                indexer.openWriter(currentDateStr);
            } catch (IOException ex) {
                Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
            }

            //CHIUDO se cambio giorno ma non ho raggiunto l'1%
            if (!tweetDateStr.equals(currentDateStr)) {
                try {
                    indexer.closeWriter();
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }
                writeOnJson(currentDateStr);
                System.out.println("Giorno successivo, completato senza aver raggiunto 1%");
                System.exit(0);
            }
            tot_count++;

            if (status.getLang().equals("it")) {
                it_count++;
                try {
                    indexer.addTweet(id, status.getText());
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            try {
                indexer.closeWriter();
            } catch (IOException ex) {
                Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        @Override
        public void onTrackLimitationNotice(int i) {
        }

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

        @Override
        public void onStallWarning(StallWarning sw) {
        }

        @Override
        public void onException(Exception excptn) {
            TwitterException exc = (TwitterException) excptn;
            if (exc.exceededRateLimitation()) {
                try {
                    indexer.closeWriter();
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }
                writeOnJson(currentDateStr);
                System.out.println("1% raccolto, dati raccolti. Amen");
            }
        }

    };

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

    indexer.addIndex(currentDateStr);
    indexer.openWriter(currentDateStr);
    twitterStream.sample();

}