Example usage for twitter4j Status getUser

List of usage examples for twitter4j Status getUser

Introduction

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

Prototype

User getUser();

Source Link

Document

Return the user associated with the status.
This can be null if the instance is from User.getStatus().

Usage

From source file:crawling.PrintFilterStreamByFile.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStreamByFile ID_File ");
        System.exit(-1);/*www. j a  va2s . c o m*/
    }

    idFile = args[0];
    tweetFile = idFile.split("\\.")[0] + "-tweets.txt";

    try {
        FileWriter outFile = new FileWriter(tweetFile, true);
        out = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            storeTweet(status.getUser().getId() + "::" + 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) {
            ex.printStackTrace();
        }

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

        }
    };

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

    // String users = "700896487,701053075,636744543";
    // String[] split = users.split(",");

    buildFollowList();

    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:crawling.PrintFilterStreamGeo.java

License:Apache License

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

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            /* my shutdown code here */
            // Record the user status
            idOut.println("Final status -------------------:");
            for (Long id : discoveredUsers.keySet()) {
                idOut.println(id + "," + discoveredUsers.get(id));
            }//from  www .  j  a v a2 s.c  om
            idOut.close();
        }
    });

    if (args.length < 5) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStreamGeo long1 lati1 long2 lati2 CITY");
        System.exit(-1);
    }
    if (args.length == 6) {
        // Preload the collected user IDs
        preloadID(args[5]);
    }

    File file = new File(fileName);
    InputStream is = null;

    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        } else {
            System.out.println(fileName + " doesn't exist!");
            System.exit(-1);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    }

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

        private void CheckUser(Status status) {
            // TODO Auto-generated method stub
            Long id = status.getUser().getId();
            /*String username = status.getUser().getScreenName();
            String realname = status.getUser().getName();
            String text = status.getText();
            Date date = status.getCreatedAt();*/
            if (discoveredUsers.containsKey(id)) {
                //System.out.println("Already found this user: " + id);
                long num = discoveredUsers.get(id);
                discoveredUsers.put(id, num + 1);
            } else {
                discoveredUsers.put(id, (long) 1);
                storeUserID(status);
            }
        }

        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 arg0) {
            // TODO Auto-generated method stub

        }
    };

    try {
        FileWriter outFile = new FileWriter("discoveredUser" + args[4] + ".txt", true);
        idOut = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    TwitterStream twitterStream = getOAuthTwitterStream();
    twitterStream.addListener(listener);
    /*ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();
            
    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()]);*/

    // Geographic location
    double[][] location = new double[2][2];
    //location[0] = new double[4];
    //location[1] = new double[4];
    location[0][0] = Double.parseDouble(args[0]);
    location[0][1] = Double.parseDouble(args[1]);
    location[1][0] = Double.parseDouble(args[2]);
    location[1][1] = Double.parseDouble(args[3]);
    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    //twitterStream.filter(new FilterQuery(0, followArray, trackArray, location));
    FilterQuery query = new FilterQuery();
    query.locations(location);
    twitterStream.filter(query);
}

From source file:crawling.PrintFilterStreamGeo.java

License:Apache License

private static void storeUserID(Status status) {
    // TODO Auto-generated method stub
    Long id = status.getUser().getId();
    String username = status.getUser().getScreenName();
    String realname = status.getUser().getName();
    String text = status.getText();
    Date date = status.getCreatedAt();

    String line = id + "::" + username + "::" + realname + "::" + text + "::" + date + "::" + (new Date());
    //System.out.println(line);
    idOut.println(line);//w  w  w  . j a v  a2  s.  c o m
    idOut.flush();
    System.out.print("\r" + ++count);

}

From source file:crawling.PrintSampleStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    //TwitterStream twitterStream = new TwitterStreamFactory().getInstance();

    TwitterStream twitterStream = getOAuthTwitterStream();

    try {/*w  w w  . j a v a 2 s .co m*/
        FileWriter outFile = new FileWriter("sampledUsers" + ".txt", true);
        idOut = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            ++tweetsCount;
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            Long id = status.getUser().getId();
            /*String username = status.getUser().getScreenName();
            String realname = status.getUser().getName();
            String text = status.getText();
            Date date = status.getCreatedAt();*/
            if (discoveredUsers.containsKey(id)) {
                //System.out.println("Already found this user: " + id);
                long num = discoveredUsers.get(id);
                discoveredUsers.put(id, num + 1);
            } else {
                discoveredUsers.put(id, (long) 1);
                storeUserID(status);
            }

        }

        @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:crawling.PrintSampleStream.java

License:Apache License

private static void storeUserID(Status status) {
    // TODO Auto-generated method stub
    Long id = status.getUser().getId();
    String username = status.getUser().getScreenName();
    String realname = status.getUser().getName();
    String text = status.getText();
    Date date = status.getCreatedAt();

    //String line = id + "::" + username + "::" + realname + "::" + text + "::" + date + "::" + (new Date());
    String line = id + "," + username;
    //System.out.println(line);
    idOut.println(line);/*from w  w w  . ja v  a 2 s  . co  m*/
    idOut.flush();
    System.out.print("\r" + ++count + ", " + tweetsCount);
}

From source file:crawling.SearchTweetsHashtag.java

License:Apache License

private static void storeATweet(Status status) {
    int len = status.getUserMentionEntities().length;
    /*//from  w w w. ja  v  a  2s.c  o m
     * We only need the interactions
     */
    if (len <= 0)
        return;

    String record = "";
    record += status.getId();
    record += "::" + status.getInReplyToStatusId();
    record += "::" + status.getInReplyToUserId();
    record += "::" + status.getRetweetCount();
    if (status.getRetweetedStatus() != null)
        record += "::" + status.getRetweetedStatus().getId();
    else
        record += "::" + "-1";
    //record += "::" + status.isRetweet();
    //int len = status.getUserMentionEntities().length;
    if (len > 0) {
        record += "::";
        for (int l = 0; l < len; l++) {
            UserMentionEntity ent = status.getUserMentionEntities()[l];
            record += "," + ent.getId();
        }
    } else {
        record += "::" + "-1";
    }
    len = status.getURLEntities().length;
    if (len > 0) {
        record += "::";
        for (int l = 0; l < len; l++) {
            URLEntity ent = status.getURLEntities()[l];
            record += "," + ent.getURL() + "|"
            //+ ent.getDisplayURL() + "|"
                    + ent.getExpandedURL();
        }
    } else
        record += "::" + "-1";
    record += "::" + cleanText(status.getText());
    // We just ignore the text content in this crawling
    //record += "::-1";
    record += "::" +
    // status.getCreatedAt();
            (status.getCreatedAt().getTime() - start.getTime()) / 1000;

    record += "::" + getSource(status.getSource());

    // Geo Location
    if (status.getGeoLocation() != null)
        record += "::" + status.getGeoLocation();
    else
        record += "::" + "-1";

    record += "::" + status.getUser().getId() + "::" + status.getUser().getScreenName() + "::"
            + status.getUser().getName() + "::" + status.getCreatedAt();

    //System.out.println(record);
    out.println(record);
    out.flush();
    count++;
}

From source file:crawltweets2mongo.MonoThread.java

void getNewTweets(String keyword) {
    try {// w  w w.j  av  a  2s .  com
        Query query = new Query(keyword);
        query.setCount(20000);
        QueryResult result;
        result = twitter.search(query);

        //System.out.println("Getting Tweets..by Key.");
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {

            BasicDBObject basicObj = new BasicDBObject();
            basicObj.put("user_Rname", tweet.getUser().getName());
            basicObj.put("user_name", tweet.getUser().getScreenName());
            basicObj.put("retweet_count", tweet.getRetweetCount());
            basicObj.put("tweet_followers_count", tweet.getUser().getFollowersCount());

            UserMentionEntity[] mentioned = tweet.getUserMentionEntities();
            basicObj.put("tweet_mentioned_count", mentioned.length);
            basicObj.put("tweet_ID", tweet.getId());
            basicObj.put("tweet_text", tweet.getText());
            Status temp1 = tweet.getRetweetedStatus();
            if (temp1 != null)
                basicObj.put("Re_tweet_ID", temp1.getUser().getId());
            GeoLocation loc = tweet.getGeoLocation();
            if (loc != null) {
                basicObj.put("Latitude", loc.getLatitude());
                basicObj.put("Longitude", loc.getLongitude());
            }
            basicObj.put("CreateTime", tweet.getCreatedAt());
            basicObj.put("FavoriteCount", tweet.getFavoriteCount());
            basicObj.put("user_Id", tweet.getUser().getId());

            if (tweet.getUser().getTimeZone() != null)
                basicObj.put("UsertimeZone", tweet.getUser().getTimeZone());
            if (tweet.getUser().getStatus() != null)
                basicObj.put("UserStatus", tweet.getUser().getStatus());
            //basicObj.put("tweetLocation", tweet.getPlace().getGeometryCoordinates());
            String U_Loc = tweet.getUser().getLocation();
            if (U_Loc != null)
                basicObj.put("userLocation", U_Loc);
            basicObj.put("number_of_rt", tweet.getRetweetCount());

            if (mentioned.length > 0) {
                basicObj.append("mentions", pickMentions(mentioned));
            }
            try {

                collection.insert(basicObj);
            } catch (Exception e) {
                //System.out.println("MongoDB Connection Error : " + e.getMessage());
                //                            loadMenu();
            }
        }
        collection.ensureIndex(new BasicDBObject("tweet_ID", 1), new BasicDBObject("unique", true));
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(MonoThread.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:crawltweets2mongo.MonoThread.java

void getNewTweets(GeoLocation myLoc, double radius) {
    try {/*from   www.  j a  va  2s .  com*/
        Query query = new Query();
        Query.Unit unit = Query.KILOMETERS; // or Query.MILES;
        query.setGeoCode(myLoc, radius, unit);
        if (radius > 200)
            query.setCount(20000);
        else
            query.setCount(20000);

        QueryResult result;
        result = this.twitter.search(query);

        //System.out.println("Getting Tweets. by Geo..");
        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {

            BasicDBObject basicObj = new BasicDBObject();
            basicObj.put("user_Rname", tweet.getUser().getName());
            basicObj.put("user_name", tweet.getUser().getScreenName());
            basicObj.put("retweet_count", tweet.getRetweetCount());
            basicObj.put("tweet_followers_count", tweet.getUser().getFollowersCount());

            UserMentionEntity[] mentioned = tweet.getUserMentionEntities();
            basicObj.put("tweet_mentioned_count", mentioned.length);
            basicObj.put("tweet_ID", tweet.getId());
            basicObj.put("tweet_text", tweet.getText());
            Status temp1 = tweet.getRetweetedStatus();
            if (temp1 != null)
                basicObj.put("Re_tweet_ID", temp1.getUser().getId());
            GeoLocation loc = tweet.getGeoLocation();
            if (loc != null) {
                basicObj.put("Latitude", loc.getLatitude());
                basicObj.put("Longitude", loc.getLongitude());
            }
            basicObj.put("CreateTime", tweet.getCreatedAt());
            basicObj.put("FavoriteCount", tweet.getFavoriteCount());
            basicObj.put("user_Id", tweet.getUser().getId());

            if (tweet.getUser().getTimeZone() != null)
                basicObj.put("UsertimeZone", tweet.getUser().getTimeZone());
            if (tweet.getUser().getStatus() != null)
                basicObj.put("UserStatus", tweet.getUser().getStatus());
            //basicObj.put("tweetLocation", tweet.getPlace().getGeometryCoordinates());
            String U_Loc = tweet.getUser().getLocation();
            if (U_Loc != null)
                basicObj.put("userLocation", U_Loc);
            basicObj.put("number_of_rt", tweet.getRetweetCount());
            //basicObj.put("isRetweet", tweet.getPlace().getGeometryCoordinates());                
            //basicObj.put("POS", tweet.getWithheldInCountries());

            if (mentioned.length > 0) {
                basicObj.append("mentions", pickMentions(mentioned));
            }
            try {
                //items.insert(basicObj);
                collection.insert(basicObj);
            } catch (Exception e) {
                //     System.out.println("MongoDB Connection Error : " + e.getMessage());
                //                            loadMenu();
            }
        }
        collection.ensureIndex(new BasicDBObject("tweet_ID", 1), new BasicDBObject("unique", true));
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(MonoThread.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:Data.Tweet.java

public Tweet(Status tweet) {
    this.author = tweet.getUser().getName();
    this.message = tweet.getText();
}

From source file:DataCollection.ActiveTrendsStatusListener.java

@Override
public void onStatus(Status arg0) {
    if (arg0.isRetweet())
        return;/*  ww  w . j a v  a  2 s.c o  m*/

    ArrayList<Trend> trends = associatedStreamer.getActiveTrends();
    Trend associatedTrend = null;

    for (int i = 0; i < trends.size(); i++) {
        if (arg0.toString().contains(trends.get(i).toString())) {
            associatedTrend = trends.get(i);
            break;
        }
    }

    if (associatedTrend == null)
        return;

    Tweet t = new Tweet(arg0.getText(), null, associatedTrend.toString(), arg0.getUser().getName(), new Date());
    cache.addDatum(t);
}