Example usage for twitter4j StatusListener StatusListener

List of usage examples for twitter4j StatusListener StatusListener

Introduction

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

Prototype

StatusListener

Source Link

Usage

From source file:tweetmining.MiningFunctions.java

/**
 * This method creates an instance of Miningfunctions based on your TwitterApss credentials.
 * You should as well check filepaths to put yours.
 * //from  w  w w. j  a  va  2  s.co  m
 * @throws FileNotFoundException 
 */

public MiningFunctions() throws FileNotFoundException, IOException {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);

    tf = new TwitterFactory(configurationBuilder.build());

    twitter = tf.getInstance();

    File f = new File(fichero1);
    File f2 = new File(fichero2);
    File f3 = new File(fichero3);
    if (!f.exists())
        f.createNewFile();
    if (!f2.exists())
        f2.createNewFile();
    if (!f3.exists())
        f3.createNewFile();
    pw = new PrintWriter(new FileOutputStream(f, true));
    pw2 = new PrintWriter(new FileOutputStream(f2, true));
    pw3 = new PrintWriter(new FileOutputStream(f3, true));

    listener = new StatusListener() {
        public void onStatus(Status status) {
            if (status.getGeoLocation() != null) {
                cont++;
                System.out.println("Loc not null----" + cont);
                GeoLocation loc = status.getGeoLocation();
                pw.println(String.valueOf(loc.getLatitude()) + ";" + String.valueOf(loc.getLongitude()) + ";"
                        + status.getUser().getName());
                System.out.println(
                        loc.getLatitude() + " " + loc.getLongitude() + " " + status.getUser().getName());
            }
            pw2.println(status.getUser().getName() + "--->" + status.getText());
            try {
                CloseWriteAndOpen();
            } catch (FileNotFoundException ex) {
                java.util.logging.Logger.getLogger(MiningFunctions.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        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.
        }
    };
    configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);
    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
}

From source file:Twitter.FilterStream.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");

    /* 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);//from  ww w .  ja v  a 2  s . co  m
     }*/

    final FilterStream fs = new FilterStream();

    try {
        fs.LinkMongodb();
    } catch (Exception e) {
        e.printStackTrace();
    }

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

        @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).setOAuthConsumerKey("7ZVgfKiOvBDcDFpytRWSA")
            .setOAuthConsumerSecret("JmeJVeym78arzmGthrDUshQyhkq6nWA9tWLUKxc")
            .setOAuthAccessToken("321341780-Zy7LptVYBZBVvAeQ5GFJ4aKFw8sdqhWBnvA3pDuO")
            .setOAuthAccessTokenSecret("foi8FnQCeN0J5cdwad05Q6d7dbytFayQn1ZOvmhF6Qc");
    cb.setJSONStoreEnabled(true);

    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());

    TwitterStream twitterStream = tf.getInstance();
    twitterStream.addListener(listener);
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();

    //String[] keywords = {"RT @justinbieber"};
    String[] keywords = { "27260086" }; // user_id(justinbieber)
    for (String arg : keywords) {
        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));
    twitterStream.filter(new FilterQuery(followArray));
}

From source file:twitter.stream.PrintFilterStream.java

License:Apache License

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

    if (args.length < 1) {
        System.out.println(//from  w ww .  j a v a  2  s.c  o  m
                "Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]");
        System.exit(-1);
    }

    final ConnectionManager c = new ConnectionManager();
    try {
        c.createConnection();
        c.createDB();
        c.closeConnection();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        System.out.println(e);
    }
    System.out.println("conexion creada");

    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {

            //            pw.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            //            if (status.getGeoLocation() != null)
            //               pw.println("Lat:" + status.getGeoLocation().getLatitude() + "Long"
            //                     + status.getGeoLocation().getLongitude());

            //            User u = status.getUser();
            //            try {
            //               System.out.println("User: id: " + u.getId() + " name: " + u.getName());
            //               c.insertTwitterUser(u);
            //            } catch (SQLException e1) {
            //               // TODO Auto-generated catch block
            //               System.out.println(e1);
            //            }
            //            
            //            if (status.isRetweet()) {
            //               
            //               System.out.println("RT Found!, getting the original tweet");
            //               Status retweetedStat = status.getRetweetedStatus();
            //               u = retweetedStat.getUser();
            //               System.out.println("RT User: id: " + u.getId() + " name: " + u.getName());
            //
            //               try {
            //            
            //                     c.insertTwitterUser(u);
            //                     
            //                     c.insertTweet(retweetedStat);
            //                     
            //                  
            //                  
            //                  
            //               } catch (SQLException e) {
            //                  // TODO Auto-generated catch block
            //                  System.out.println(e);
            //               }
            //               
            //            }
            //            if(status.getQuotedStatus() != null){
            //               
            //               System.out.println("Quoted Found!, getting the original tweet");
            //               Status quotedStatus = status.getQuotedStatus();
            //               u = quotedStatus.getUser();
            //               System.out.println("Quoted User: id: " + u.getId() + " name: " + u.getName());
            //
            //               try {
            //                  c.insertTwitterUser(u);
            //                  c.insertTweet(quotedStatus);
            //               } catch (SQLException e) {
            //                  // TODO Auto-generated catch block
            //                  System.out.println(e);
            //               }
            //            }
            //            
            //      
            //            
            //            try {
            //               c.insertTweet(status);
            //            } catch (SQLException e) {
            //               // TODO Auto-generated catch block
            //               System.out.println(e);
            //            }

            try {
                c.recursiveInsert(status, 0);
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        @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 twitterStream = new TwitterStreamFactory().getInstance();

    FilterQuery fq = new FilterQuery();

    String keywords[] = { "election2016", "NeverTrump", "Hillary2016", "Trump", "HillarysEmail",
            "2016election" };

    fq.track(keywords);

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

From source file:twitter.stream.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application.//from   w  w  w  .jav  a 2s  .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.stream.PrintFilterStream.java

License:Apache License

/**
 * Main entry of this application.//from ww w .  j  a va 2 s  . c  om
 *
 * @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);
    }

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance().addListener(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();
        }
    });

    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:twitter4j.examples.stream.PrintFirehoseStream.java

License:Apache License

/**
 * Main entry of this application.//  w  w w . j a  v a2s . 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().addListener(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();
        }
    }).firehose(0);
}

From source file:twitter4j.examples.stream.PrintLinksStream.java

License:Apache License

/**
 * Main entry of this application./*  w ww . jav a  2s.  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().addListener(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();
        }
    }).links(0);
}

From source file:twitter4j.examples.stream.PrintRetweetStream.java

License:Apache License

/**
 * Main entry of this application./*  ww  w . ja  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().addListener(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();
        }
    }).retweet();
}

From source file:twitter4j.examples.stream.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application./*from   w  w  w  . j av  a  2s  .  com*/
 *
 * @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().addListener(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();
        }
    }).sample();
}

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  2  s  .c o  m
    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);
}