Example usage for twitter4j TwitterStream sample

List of usage examples for twitter4j TwitterStream sample

Introduction

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

Prototype

TwitterStream sample();

Source Link

Document

Starts listening on random sample of all public statuses.

Usage

From source file:stream.Sample.java

License:Apache License

/**
 * @param args/* w  w w . ja va2  s .  c om*/
 */
public static void main(String[] args) {

    // Check how many arguments were passed in
    if ((args == null) || (args.length == 0)) {
        System.err.println("Please provide output directory path");
        System.exit(-1);
    }

    try {
        OutputDirPath = StringEscapeUtils.escapeJava(args[0]);
    } catch (Exception e) {
        System.err.println("Argument" + args[0] + " must be an String.");
        System.exit(-1);
    }

    dataStoreManager();

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {
            // System.out.println(status.getUser().getName() + " : " +
            // status.getText());
            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            // System.out.println(rawJSON);
            writer.println(rawJSON);
            counter++;
            System.out.println(counter);
            if (counter >= 1000) {
                dataStoreManager();
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

        public void onException(Exception ex) {
        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {
            // TODO Auto-generated method stub

        }

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

        }
    };

    // mozellecandi
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("****").setOAuthConsumerSecret("****")
            .setOAuthAccessToken("****").setOAuthAccessTokenSecret("****").setJSONStoreEnabled(true);

    TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
    twitterStream.addListener(listener);
    // sample() method internally creates a thread which manipulates
    // TwitterStream and calls these adequate listener methods continuously.
    twitterStream.sample();

}

From source file:tweet.streams.TwitterCrawler.java

License:Apache License

public static void main(String[] args) {
    initFile();// w w  w.  ja  v a  2  s .c  o  m

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

    //      FilterQuery query = new FilterQuery().language("EN").track(seeds);
    //      twitterStream.filter(query);
    twitterStream.sample();
}

From source file:twitter.stream.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application./*from   w  w  w  .  j a  v a  2 s .  c  o m*/
 *
 * @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: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());
        }/*  w w  w .ja v a 2s.  com*/

        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. j  ava  2 s .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: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());/*  ww w.j  a  v a 2 s .  co  m*/
    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();

}