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:socialImport.twitter.TweetToDatabaseImportListener.java

License:Open Source License

@Override
public void onStatus(Status status) {
    Date dateOfCreation = status.getCreatedAt();
    String authorName = status.getUser().getName();
    Gender gender = Gender.unknown;/*from   w  ww .  j  ava2 s. c  om*/
    int yearOfBirth = -1;
    Author author = new Author(authorName, gender, yearOfBirth);
    GeoTag geoTag = null;
    Place place = status.getPlace();
    GeoLocation[][] geoLocation = null;
    if (place != null) {
        geoLocation = place.getBoundingBoxCoordinates();
    }
    if (geoLocation != null) {
        float latitude = 0;
        float longitude = 0;
        int noOfCoordinates = geoLocation[0].length;
        for (int i = 0; i < noOfCoordinates; i++) {
            latitude += geoLocation[0][i].getLatitude();
            longitude += geoLocation[0][i].getLongitude();
        }
        latitude = latitude / noOfCoordinates;
        longitude = longitude / noOfCoordinates;
        geoTag = new GeoTag(latitude, longitude);
    }
    String postText = status.getText();
    long retweetCount = status.getRetweetCount();
    TweetPost tweet = new TweetPost(streamDescriptor, dateOfCreation, author, geoTag, postText, retweetCount);
    System.out.println(author);
    System.out.println(geoTag);
    System.out.println(status.getText());
    dataModule.savePost(tweet);

}

From source file:source.TwitterSource.java

License:Apache License

/**
 * Start processing events. This uses the Twitter Streaming API to sample
 * Twitter, and process tweets./*from www .  j  ava  2 s  .  c o m*/
 */
@Override
public void start() {
    // The channel is the piece of Flume that sits between the Source and
    // Sink, and is used to process events
    final ChannelProcessor channel = getChannelProcessor();

    final Map<String, String> headers = new HashMap<String, String>();

    // The StatusListener is a twitter4j API, which can be added to a 
    // Twitter stream, and will execute methods every time a message comes 
    // in through the stream
    StatusListener listener = new StatusListener() {

        // The onStatus method is executed every time a new tweet comes in
        public void onStatus(Status status) {
            // The EventBuilder is used to build an event using the headers 
            // and the raw JSON of a tweet
            logger.debug(status.getUser().getScreenName() + ": " + status.getText());

            headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime()));
            Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status).getBytes(), headers);

            channel.processEvent(event);
        }

        // This listener will ignore everything except for new tweets
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

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

        public void onException(Exception ex) {
        }

        public void onStallWarning(StallWarning warning) {
        }

    };

    logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}",
            new String[] { consumerKey, accessToken });
    // Set up the stream's listener (defined above), and set any necessary 
    // security information
    twitterStream.addListener(listener);

    // Set up a filter to pull out industry-relevant tweets
    logger.debug("Starting up Twitter filtering...");
    FilterQuery query = new FilterQuery().count(0);

    if (locations == null) {
        logger.debug("No locations specified");
    } else {
        String debugString = "Locations specified: ";
        debugString += "SW={" + locations[0][0] + ", " + locations[0][1] + "}, ";
        debugString += "NE={" + locations[1][0] + ", " + locations[1][1] + "}";
        logger.debug(debugString);
        query.locations(locations);
    }

    if (keywords == null) {
        logger.debug("No keywords specified");
    } else {
        String debugString = keywords.length + " keywords specified: ";
        for (int i = 0; i < keywords.length; i++) {
            debugString += keywords[i];
            if (i != keywords.length - 1) {
                debugString += ", ";
            }
        }
        logger.debug(debugString);
        query.track(keywords);
    }

    twitterStream.filter(query);

    super.start();

}

From source file:stempunksbot.MentionListener.java

License:Open Source License

@Override
public void onStatus(Status status) {
    System.out.println(status.getUser().getScreenName() + ": " + status.getText());
    /*try {// w w w .j a  va2 s.  co  m
    //STEMpunksBot.tweet("@" + status.getUser().getScreenName() + " hey - rofl");
    } catch (TwitterException ex) {
    Logger.getLogger(MentionListener.class.getName()).log(Level.SEVERE, null, ex);
    }*/
}

From source file:stemrps.MentionListener.java

License:Open Source License

@Override
public void onStatus(Status status) {
    System.out.println(status.getUser().getScreenName() + ": " + status.getText());
    String[] inp = status.getText().split(" ");
    String player = "";
    if (inp[1].equalsIgnoreCase("stats")) {
        try {/*from www. jav  a2  s . c om*/
            long user = status.getUser().getId();
            String whoStats = "";
            if (inp.length >= 3) {
                if (inp[2] != null && !inp[2].equalsIgnoreCase("me")) {
                    User acc = STEMrps.t.showUser(inp[2]);
                    user = acc.getId();
                    whoStats = acc.getScreenName() + " ";
                }
            }
            String tweet = "@" + status.getUser().getScreenName() + " " + whoStats
                    + GameLogic.getStatsString(user);
            STEMrps.t.updateStatus(tweet);

        } catch (Exception ex) {
            Logger.getLogger(MentionListener.class.getName()).log(Level.SEVERE, null, ex);
            return;
        }
    } else {
        try {
            if (status.getUser().getId() == 4741197613L) { //If it is our's?
                return;
            }
            STEMrps.makeSureUsrSetup(status.getUser().getId());
            for (String s : inp) {
                if (STEMrps.getFromString(s) != null) {
                    player = s;
                    break;
                }
            }
            stemrps.GameResult match = STEMrps.playGame(status.getUser().getId(), player);
            String tweet = "@" + status.getUser().getScreenName() + " ";
            if (match == null) {
                tweet += "Something went wrong! Please use r, rock, p, paper, s, or scissors to play!";
            } else if (match.outcome == stemrps.Status.W) {
                tweet += "You (" + match.player.name() + ") won against me (" + match.comp.name() + ")";
            } else if (match.outcome == stemrps.Status.T) {
                tweet += "You (" + match.player.name() + ") tied against me (" + match.comp.name() + ")";
            } else if (match.outcome == stemrps.Status.L) {
                tweet += "You (" + match.player.name() + ") lost against me (" + match.comp.name() + ")";
            }
            tweet += " (Game #" + STEMrps.gamesPlayed() + ")";
            StatusUpdate rt = new StatusUpdate(tweet);
            STEMrps.t.updateStatus(rt);
        } catch (Exception ex) {
            Logger.getLogger(MentionListener.class.getName()).log(Level.SEVERE, null, ex);
            String tweet = "@" + status.getUser().getScreenName() + " Oops, did't catch that. "
                    + LocalDateTime.now();
            StatusUpdate rt = new StatusUpdate(tweet);
            try {
                STEMrps.t.updateStatus(rt);
            } catch (TwitterException ex1) {
                Logger.getLogger(MentionListener.class.getName()).log(Level.SEVERE, null, ex1);
            }
        }
    }
}

From source file:storm.starter.spout.Q2FetchTweetSpout.java

License:Apache License

@Override
public void nextTuple() {
    //Utils.sleep(interval);
    Status ret = queue.poll();
    if (ret == null) {
        Utils.sleep(10);/*from  w w  w  . j av  a  2  s . c  o  m*/
    } else {
        System.out.println("DEBUG\tFetchTweetSpout\t" + ret.getText());
        if (ret.getLang().equals("en")) {
            Date date = new Date();
            long currTime = date.getTime();
            ArrayList<String> hss = new ArrayList<String>();
            for (HashtagEntity htentity : ret.getHashtagEntities()) {
                hss.add(htentity.getText());
            }
            tweetInfoList.add(new TweetInfo(ret.getUser().getFriendsCount(), hss, ret.getText()));

            if ((currTime - timestamp) > interval) {
                timestamp = currTime;
                sequenceNumber++;
                _collector.emit(new Values(sequenceNumber, tweetInfoList));
                tweetInfoList.clear();
            }
        }
    }
}

From source file:storm.starter.spout.Q2SeqTwitterSpout.java

License:Apache License

@Override
public void nextTuple() {
    Status ret = queue.poll();
    if (ret == null) {
        Utils.sleep(50);//from w  w  w .j ava  2s  .  c o  m
    } else {

        Date date = new Date();
        long currTime = date.getTime();
        ArrayList<String> hss = new ArrayList<String>();
        for (HashtagEntity htentity : ret.getHashtagEntities()) {
            hss.add(htentity.getText());
        }
        tweetInfoList.add(new TweetInfo(ret.getUser().getFriendsCount(), hss, ret.getText()));

        if ((currTime - timestamp) > interval) {
            if (tweetInfoList.size() > 0) {
                timestamp = currTime;
                sequenceNumber++;
                _collector.emit(new Values(sequenceNumber, tweetInfoList));
                tweetInfoList.clear();
            } else {
                System.out.println("DEBUG\tQ2SeqTweetSpout\tEmptyTupleFound\t" + ret.getText());
            }
        }
    }
}

From source file:stream.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application.//from   www.ja va  2s . c  om
 *
 * @param args
 */
public static void main(String[] args) throws TwitterException {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            System.out.println("@" + 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) {
            ex.printStackTrace();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.sample();
}

From source file:StringMatching.GetTweet.java

/**
 * @param args the command line arguments
 *//*from w  w w . j  a v a2  s .com*/
public static void main(String[] args) throws JSONException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH")
            .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK")
            .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA")
            .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC")
            .setHttpProxyHost("cache.itb.ac.id").setHttpProxyPort(8080).setHttpProxyUser("jonathan.benedict")
            .setHttpProxyPassword("rollingonthefloor");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    JSONObject obj = new JSONObject();
    int counterTweet = 0;
    FileWriter file = new FileWriter("C:\\Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt");
    file.flush();
    try {
        Query query = new Query("barca".toLowerCase());
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                counterTweet++;
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                obj.put("user", tweet.getUser().getScreenName());
                obj.put("tweets", tweet.getText());

                //Tulis file ke dalam txt

                try {
                    file.write(obj.toString());
                    System.out.println("Successfully Copied JSON Object to File...");
                    System.out.println("\nJSON Object: " + obj);

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        } while (counterTweet < 1000);

        file.close();
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    System.exit(0);
}

From source file:sumblr.TwitterStreamData.java

public void getSampleData() {
    this.listener = new StatusListener() {
        @Override/*from  w  ww  .  j a  v  a2s.com*/
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {

        }

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

        }

        @Override
        public void onStallWarning(StallWarning warning) {

        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }
    };
    this.twitterStream.addListener(listener);
    this.twitterStream.sample();
}

From source file:t.twitter.TTwitterModule.java

License:Open Source License

@Kroll.method
public void connect(HashMap args) {
    KrollDict arg = new KrollDict(args);

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(arg.optString("apikey", ""))
            .setOAuthConsumerSecret(arg.optString("apisecret", ""))
            .setOAuthAccessToken(arg.optString("accesstoken", ""))
            .setOAuthAccessTokenSecret(arg.optString("accesssecret", ""));
    AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build());
    twitter = tf.getInstance();// w  ww.  j av a  2 s . c o m

    twitter.addListener(new TwitterAdapter() {
        @Override
        public void updatedStatus(Status status) {
            Log.d("Twitter", "text: " + status.getText());
        }

        @Override
        public void searched(QueryResult result) {
            HashMap<String, KrollDict[]> event = new HashMap<String, KrollDict[]>();
            List<Status> tweets = result.getTweets();
            KrollDict[] dList = new KrollDict[tweets.size()];

            // sort tweets
            Collections.sort(tweets, new Comparator<Status>() {
                public int compare(Status o1, Status o2) {

                    if (desc) {
                        if (o2.getId() < o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    } else {
                        if (o2.getId() > o1.getId()) {
                            return 1;
                        } else {
                            return -1;
                        }
                    }
                }
            });

            // return tweets to titanium
            int i = 0;
            for (Status tweet : tweets) {
                if (lastID == -1 || lastID < tweet.getId()) {
                    KrollDict d = new KrollDict();
                    d.put("username", tweet.getUser().getScreenName());
                    d.put("userimage", tweet.getUser().getProfileImageURL());
                    d.put("text", tweet.getText());
                    d.put("date", tweet.getCreatedAt());
                    d.put("id", Long.toString(tweet.getId()));
                    dList[i] = d;
                    lastID = tweet.getId();
                    i++;
                }
            }

            KrollDict[] dList2 = new KrollDict[i];

            // shorten array
            System.arraycopy(dList, 0, dList2, 0, i);

            event.put("tweets", dList2);
            success.call(getKrollObject(), event);

            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void verifiedCredentials(User user) {

            HashMap<String, KrollDict> event = new HashMap<String, KrollDict>();
            KrollDict d = new KrollDict();

            d.put("user_name", user.getName());
            d.put("screen_name", user.getScreenName());
            d.put("image_path", user.getProfileImageURL());
            event.put("user_info", d);
            success.call(getKrollObject(), event);
            synchronized (LOCK) {
                LOCK.notify();
            }
        }

        @Override
        public void onException(TwitterException e, TwitterMethod method) {
            synchronized (LOCK) {
                LOCK.notify();
            }
            Log.e("twitter", "error: " + e.getErrorMessage());
        }
    });
    Log.d("Twitter", "connected");
}