Example usage for twitter4j Status getRetweetCount

List of usage examples for twitter4j Status getRetweetCount

Introduction

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

Prototype

int getRetweetCount();

Source Link

Document

Returns the number of times this tweet has been retweeted, or -1 when the tweet was created before this feature was enabled.

Usage

From source file:DataCollections.TweetHelper.java

public Tweet_dbo convertStatusToTweet_dbo(Status s) {
    Tweet_dbo tweet = new Tweet_dbo();
    tweet.values[Tweet_dbo.map.get("tweet_id")].setValue(String.valueOf(s.getId()));
    tweet.values[Tweet_dbo.map.get("user_id")].setValue(String.valueOf(s.getUser().getId()));
    tweet.values[Tweet_dbo.map.get("user_screenname")]
            .setValue(removeEscapeCharacters(s.getUser().getScreenName()));
    if (s.getGeoLocation() != null) {
        tweet.values[Tweet_dbo.map.get("lon")].setValue(String.valueOf(s.getGeoLocation().getLongitude()));
        tweet.values[Tweet_dbo.map.get("lat")].setValue(String.valueOf(s.getGeoLocation().getLatitude()));
    }//  w  w  w.j  a  v a2  s  .  c  o m
    //tweet.values[Tweet_dbo.map.get("f_search")].setValue("true");
    tweet.values[Tweet_dbo.map.get("text")].setValue(removeEscapeCharacters(s.getText()));
    tweet.values[Tweet_dbo.map.get("hashtags")].setValue(stringifyHashtags(s.getHashtagEntities()));
    tweet.values[Tweet_dbo.map.get("mentions")].setValue(stringiyMentions(s.getUserMentionEntities()));
    tweet.values[Tweet_dbo.map.get("favouritecount")].setValue(String.valueOf(s.getFavoriteCount()));
    tweet.values[Tweet_dbo.map.get("retweetcount")].setValue(String.valueOf(s.getRetweetCount()));
    return tweet;
}

From source file:de.vanita5.twittnuker.model.ParcelableStatus.java

License:Open Source License

public ParcelableStatus(final Status orig, final long account_id, final boolean is_gap) {
    this.is_gap = is_gap;
    this.account_id = account_id;
    id = orig.getId();//from  w  w  w  . j  a v  a  2 s. c  om
    timestamp = getTime(orig.getCreatedAt());
    is_retweet = orig.isRetweet();
    final Status retweeted = orig.getRetweetedStatus();
    final User retweet_user = retweeted != null ? orig.getUser() : null;
    retweet_id = retweeted != null ? retweeted.getId() : -1;
    //NOTE getTime(orig.getCreatedAt())
    retweet_timestamp = retweeted != null ? getTime(retweeted.getCreatedAt()) : -1;
    retweeted_by_id = retweet_user != null ? retweet_user.getId() : -1;
    retweeted_by_name = retweet_user != null ? retweet_user.getName() : null;
    retweeted_by_screen_name = retweet_user != null ? retweet_user.getScreenName() : null;
    retweeted_by_profile_image = retweet_user != null
            ? ParseUtils.parseString(retweet_user.getProfileImageUrlHttps())
            : null;
    final Status status = retweeted != null ? retweeted : orig;
    final User user = status.getUser();
    user_id = user.getId();
    user_name = user.getName();
    user_screen_name = user.getScreenName();
    user_profile_image_url = ParseUtils.parseString(user.getProfileImageUrlHttps());
    user_is_protected = user.isProtected();
    user_is_verified = user.isVerified();
    user_is_following = user.isFollowing();
    text_html = formatStatusText(status);
    media = ParcelableMedia.fromEntities(status);
    text_plain = status.getText();
    retweet_count = status.getRetweetCount();
    favorite_count = status.getFavoriteCount();
    reply_count = status.getReplyCount();
    descendent_reply_count = status.getDescendentReplyCount();
    in_reply_to_name = getInReplyToName(status);
    in_reply_to_screen_name = status.getInReplyToScreenName();
    in_reply_to_status_id = status.getInReplyToStatusId();
    in_reply_to_user_id = status.getInReplyToUserId();
    source = status.getSource();
    location = new ParcelableLocation(status.getGeoLocation());
    is_favorite = status.isFavorited();
    text_unescaped = toPlainText(text_html);
    my_retweet_id = retweeted_by_id == account_id ? id : -1;
    is_possibly_sensitive = status.isPossiblySensitive();
    mentions = ParcelableUserMention.fromUserMentionEntities(status.getUserMentionEntities());
    first_media = media != null && media.length > 0 ? media[0].url : null;
}

From source file:de.vanita5.twittnuker.util.ContentValuesCreator.java

License:Open Source License

public static ContentValues makeStatusContentValues(final Status orig, final long accountId,
        final boolean largeProfileImage) {
    if (orig == null || orig.getId() <= 0)
        return null;
    final ContentValues values = new ContentValues();
    values.put(Statuses.ACCOUNT_ID, accountId);
    values.put(Statuses.STATUS_ID, orig.getId());
    values.put(Statuses.STATUS_TIMESTAMP, orig.getCreatedAt().getTime());
    values.put(Statuses.MY_RETWEET_ID, orig.getCurrentUserRetweet());
    final boolean isRetweet = orig.isRetweet();
    final Status status;
    final Status retweetedStatus = isRetweet ? orig.getRetweetedStatus() : null;
    if (retweetedStatus != null) {
        final User retweetUser = orig.getUser();
        values.put(Statuses.RETWEET_ID, retweetedStatus.getId());
        values.put(Statuses.RETWEET_TIMESTAMP, retweetedStatus.getCreatedAt().getTime());
        values.put(Statuses.RETWEETED_BY_USER_ID, retweetUser.getId());
        values.put(Statuses.RETWEETED_BY_USER_NAME, retweetUser.getName());
        values.put(Statuses.RETWEETED_BY_USER_SCREEN_NAME, retweetUser.getScreenName());
        values.put(Statuses.RETWEETED_BY_USER_PROFILE_IMAGE,
                ParseUtils.parseString(retweetUser.getProfileImageUrlHttps()));
        status = retweetedStatus;//from   w  ww.j a v a2s. c  o m
    } else {
        status = orig;
    }
    final User user = status.getUser();
    if (user != null) {
        final long userId = user.getId();
        final String profileImageUrl = ParseUtils.parseString(user.getProfileImageUrlHttps());
        final String name = user.getName(), screenName = user.getScreenName();
        values.put(Statuses.USER_ID, userId);
        values.put(Statuses.USER_NAME, name);
        values.put(Statuses.USER_SCREEN_NAME, screenName);
        values.put(Statuses.IS_PROTECTED, user.isProtected());
        values.put(Statuses.IS_VERIFIED, user.isVerified());
        values.put(Statuses.USER_PROFILE_IMAGE_URL,
                largeProfileImage ? getBiggerTwitterProfileImage(profileImageUrl) : profileImageUrl);
        values.put(CachedUsers.IS_FOLLOWING, user.isFollowing());
    }
    final String text_html = Utils.formatStatusText(status);
    values.put(Statuses.TEXT_HTML, text_html);
    values.put(Statuses.TEXT_PLAIN, status.getText());
    values.put(Statuses.TEXT_UNESCAPED, toPlainText(text_html));
    values.put(Statuses.RETWEET_COUNT, status.getRetweetCount());
    values.put(Statuses.REPLY_COUNT, status.getReplyCount());
    values.put(Statuses.DESCENDENT_REPLY_COUNT, status.getDescendentReplyCount());
    values.put(Statuses.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId());
    values.put(Statuses.IN_REPLY_TO_USER_ID, status.getInReplyToUserId());
    values.put(Statuses.IN_REPLY_TO_USER_NAME, Utils.getInReplyToName(status));
    values.put(Statuses.IN_REPLY_TO_USER_SCREEN_NAME, status.getInReplyToScreenName());
    values.put(Statuses.SOURCE, status.getSource());
    values.put(Statuses.IS_POSSIBLY_SENSITIVE, status.isPossiblySensitive());
    final GeoLocation location = status.getGeoLocation();
    if (location != null) {
        values.put(Statuses.LOCATION, location.getLatitude() + "," + location.getLongitude());
    }
    values.put(Statuses.IS_RETWEET, isRetweet);
    values.put(Statuses.IS_FAVORITE, status.isFavorited());
    final ParcelableMedia[] media = ParcelableMedia.fromEntities(status);
    if (media != null) {
        values.put(Statuses.MEDIA, JSONSerializer.toJSONArrayString(media));
        values.put(Statuses.FIRST_MEDIA, media[0].url);
    }
    final ParcelableUserMention[] mentions = ParcelableUserMention.fromStatus(status);
    if (mentions != null) {
        values.put(Statuses.MENTIONS, JSONSerializer.toJSONArrayString(mentions));
    }
    return values;
}

From source file:druid.examples.twitter.TwitterSpritzerFirehoseFactory.java

License:Open Source License

@Override
public Firehose connect() throws IOException {
    final ConnectionLifeCycleListener connectionLifeCycleListener = new ConnectionLifeCycleListener() {
        @Override//w  w w .j  av a 2s  .  c o m
        public void onConnect() {
            log.info("Connected_to_Twitter");
        }

        @Override
        public void onDisconnect() {
            log.info("Disconnect_from_Twitter");
        }

        /**
         * called before thread gets cleaned up
         */
        @Override
        public void onCleanUp() {
            log.info("Cleanup_twitter_stream");
        }
    }; // ConnectionLifeCycleListener

    final TwitterStream twitterStream;
    final StatusListener statusListener;
    final int QUEUE_SIZE = 2000;
    /** This queue is used to move twitter events from the twitter4j thread to the druid ingest thread.   */
    final BlockingQueue<Status> queue = new ArrayBlockingQueue<Status>(QUEUE_SIZE);
    final LinkedList<String> dimensions = new LinkedList<String>();
    final long startMsec = System.currentTimeMillis();

    dimensions.add("htags");
    dimensions.add("lang");
    dimensions.add("utc_offset");

    //
    //   set up Twitter Spritzer
    //
    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addConnectionLifeCycleListener(connectionLifeCycleListener);
    statusListener = new StatusListener() { // This is what really gets called to deliver stuff from twitter4j
        @Override
        public void onStatus(Status status) {
            // time to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }
            try {
                boolean success = queue.offer(status, 15L, TimeUnit.SECONDS);
                if (!success) {
                    log.warn("queue too slow!");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            //log.info("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            // This notice will be sent each time a limited stream becomes unlimited.
            // If this number is high and or rapidly increasing, it is an indication that your predicate is too broad, and you should consider a predicate with higher selectivity.
            log.warn("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            //log.info("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

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

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }
    };

    twitterStream.addListener(statusListener);
    twitterStream.sample(); // creates a generic StatusStream
    log.info("returned from sample()");

    return new Firehose() {

        private final Runnable doNothingRunnable = new Runnable() {
            public void run() {
            }
        };

        private long rowCount = 0L;
        private boolean waitIfmax = (maxEventCount < 0L);
        private final Map<String, Object> theMap = new HashMap<String, Object>(2);
        // DIY json parsing // private final ObjectMapper omapper = new ObjectMapper();

        private boolean maxTimeReached() {
            if (maxRunMinutes <= 0) {
                return false;
            } else {
                return (System.currentTimeMillis() - startMsec) / 60000L >= maxRunMinutes;
            }
        }

        private boolean maxCountReached() {
            return maxEventCount >= 0 && rowCount >= maxEventCount;
        }

        @Override
        public boolean hasMore() {
            if (maxCountReached() || maxTimeReached()) {
                return waitIfmax;
            } else {
                return true;
            }
        }

        @Override
        public InputRow nextRow() {
            // Interrupted to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }

            // all done?
            if (maxCountReached() || maxTimeReached()) {
                if (waitIfmax) {
                    // sleep a long time instead of terminating
                    try {
                        log.info("reached limit, sleeping a long time...");
                        sleep(2000000000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException("InterruptedException", e);
                    }
                } else {
                    // allow this event through, and the next hasMore() call will be false
                }
            }
            if (++rowCount % 1000 == 0) {
                log.info("nextRow() has returned %,d InputRows", rowCount);
            }

            Status status;
            try {
                status = queue.take();
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }

            HashtagEntity[] hts = status.getHashtagEntities();
            if (hts != null && hts.length > 0) {
                List<String> hashTags = Lists.newArrayListWithExpectedSize(hts.length);
                for (HashtagEntity ht : hts) {
                    hashTags.add(ht.getText());
                }

                theMap.put("htags", Arrays.asList(hashTags.get(0)));
            }

            long retweetCount = status.getRetweetCount();
            theMap.put("retweet_count", retweetCount);
            User user = status.getUser();
            if (user != null) {
                theMap.put("follower_count", user.getFollowersCount());
                theMap.put("friends_count", user.getFriendsCount());
                theMap.put("lang", user.getLang());
                theMap.put("utc_offset", user.getUtcOffset()); // resolution in seconds, -1 if not available?
                theMap.put("statuses_count", user.getStatusesCount());
            }

            return new MapBasedInputRow(status.getCreatedAt().getTime(), dimensions, theMap);
        }

        @Override
        public Runnable commit() {
            // ephemera in, ephemera out.
            return doNothingRunnable; // reuse the same object each time
        }

        @Override
        public void close() throws IOException {
            log.info("CLOSE twitterstream");
            twitterStream.shutdown(); // invokes twitterStream.cleanUp()
        }
    };
}

From source file:flight_ranker.Flight_colllector.java

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

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);/* w ww. ja  va 2  s.c  o  m*/
    cb.setOAuthConsumerKey("Oa6WAzH0j3sgVrP0CNGvxnWA2");
    cb.setOAuthConsumerSecret("sLdoFybvJvVFz7Lxbbv9KWQDFeKcVeZAkWDC4QMHnx5lV2OmGE");
    cb.setOAuthAccessToken("2691889945-5NOBWKUgT9FiAoyOQSCFg8CLlPRlDMbWcUrJBdK");
    cb.setOAuthAccessTokenSecret("J6tA8Sxrtz2JNSFdQwAonbGxNfLNuD9I54Zfvomku3p5t");

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

    StatusListener listener = new StatusListener() {

        @Override
        public void onException(Exception arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {
            // TODO Auto-generated method stub

        }

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

        }

        @Override
        public void onStatus(Status status) {
            User user = status.getUser();

            // gets Username
            String username = status.getUser().getScreenName();
            long followers = user.getFollowersCount();

            long retweets = status.getRetweetCount();

            long favs = status.getFavoriteCount();

            System.out.println("USERNAME--> " + username);
            System.out.println("FOLLOWERS--> " + followers);
            String profileLocation = user.getLocation();

            //                System.out.println("RETWEETS--> "+retweets);

            //                System.out.println("FAVOURITES--> "+favs);

            System.out.println("LOCATION--> " + profileLocation);
            long tweetId = status.getId();
            System.out.println("TWEET ID--> " + tweetId);
            String content = status.getText();
            System.out.println("TWEET--> " + content + "\n");

            BufferedWriter b1 = null, b2, b3, b4, b5, b6, b7 = null;

            try {
                //output_file = new BufferedReader(new FileReader("G:\\Sentiwords.txt"));

                FileWriter f1 = new FileWriter("G:\\flights_data.txt", true);
                b1 = new BufferedWriter(f1);
                b1.write("#USERNAME- " + username);
                b1.newLine();

                b1.write("#Followers- " + followers);

                b1.newLine();

                b1.write("#Location- " + profileLocation);

                b1.newLine();
                b1.write("#ID- " + tweetId);

                b1.newLine();
                b1.write("#Tweet- " + content);
                b1.newLine();
                b1.newLine();

                tweet_editor modified_tweet = new tweet_editor(content);
                //tweet_tagger tagged_tweet = new tweet_tagger(modified_tweet.edited_tweet);
                //System.out.println(tagged_tweet.tagged);

                sentiment_calculator senti_value = new sentiment_calculator(modified_tweet.edited_tweet);

                if (content.contains("Indigo")) {
                    System.out.println("indigo");
                    FileWriter f2 = new FileWriter("G:\\Indigo.txt", true);
                    b2 = new BufferedWriter(f2);
                    b2.write(Double.toString(senti_value.senti_rate));
                    b2.newLine();
                }

                if (content.contains("Jet")) {
                    System.out.println("jet");
                    FileWriter f3 = new FileWriter("G:\\jet.txt", true);
                    b3 = new BufferedWriter(f3);
                    b3.write(Double.toString(senti_value.senti_rate));
                    b3.newLine();
                }

                if (content.contains("Indian")) {
                    System.out.println("indian");
                    FileWriter f4 = new FileWriter("G:\\Indian.txt", true);
                    b4 = new BufferedWriter(f4);
                    b4.write(Double.toString(senti_value.senti_rate));
                    b4.newLine();
                }

                if (content.contains("Spicejet")) {
                    System.out.println("spicejet");
                    FileWriter f5 = new FileWriter("G:\\spicejet.txt", true);
                    b5 = new BufferedWriter(f5);
                    b5.write(Double.toString(senti_value.senti_rate));
                    b5.newLine();
                }

                if (content.contains("AirAsia")) {
                    System.out.println("airasia");
                    FileWriter f6 = new FileWriter("G:\\airasia.txt", true);
                    b6 = new BufferedWriter(f6);
                    b6.write(Double.toString(senti_value.senti_rate));
                    b6.newLine();
                }

                try {
                    //output_file = new BufferedReader(new FileReader("G:\\Sentiwords.txt"));

                    FileWriter f7 = new FileWriter("G:\\flight_senti.txt", true);
                    b7 = new BufferedWriter(f7);
                    b7.write(String.valueOf(senti_value.senti_rate));
                    b7.newLine();

                }

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

                finally {
                    try {
                        b7.close();
                    } catch (IOException ex) {
                        Logger.getLogger(Flight_colllector.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

            }

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

            finally {
                try {
                    b1.close();
                } catch (IOException ex) {
                    Logger.getLogger(Flight_colllector.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {
            // TODO Auto-generated method stub

        }

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

    };

    FilterQuery fq = new FilterQuery();

    String keywords[] = {
            "Indian Airlines, Indigo Airlines, Indigo Airline , Indian Airline , Spicejet , jetAirways , Jet Airways, Jet Airlines , airasia" }; //we will pass stock related keyword here

    fq.track(keywords);

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

}

From source file:info.maslowis.twitterripper.util.Util.java

License:Open Source License

/**
 * Returns a representation the status (tweet) as string
 *
 * @return a representation the status as string in format <em>Status{id=, text='', lang='', createdAt=, geoLocation=, isFavorited=, isRetweeted=, retweetCount=, isTruncated=}</em>
 *//* ww  w.ja va 2  s  .c  o m*/
public static String toString(final Status status) {
    return "Status{id=" + status.getId() + ", text='" + status.getText() + "', lang='" + status.getLang()
            + "', createdAt=" + status.getCreatedAt() + ", geoLocation=" + status.getGeoLocation()
            + ", isFavorited=" + status.isFavorited() + ", isRetweeted=" + status.isRetweeted()
            + ", retweetCount=" + status.getRetweetCount() + ", isTruncated=" + status.isTruncated() + "}";
}

From source file:io.druid.examples.twitter.TwitterSpritzerFirehoseFactory.java

License:Apache License

@Override
public Firehose connect(InputRowParser parser) throws IOException {
    final ConnectionLifeCycleListener connectionLifeCycleListener = new ConnectionLifeCycleListener() {
        @Override/*from  w  w w.  j  ava 2s.  c  om*/
        public void onConnect() {
            log.info("Connected_to_Twitter");
        }

        @Override
        public void onDisconnect() {
            log.info("Disconnect_from_Twitter");
        }

        /**
         * called before thread gets cleaned up
         */
        @Override
        public void onCleanUp() {
            log.info("Cleanup_twitter_stream");
        }
    }; // ConnectionLifeCycleListener

    final TwitterStream twitterStream;
    final StatusListener statusListener;
    final int QUEUE_SIZE = 2000;
    /** This queue is used to move twitter events from the twitter4j thread to the druid ingest thread.   */
    final BlockingQueue<Status> queue = new ArrayBlockingQueue<Status>(QUEUE_SIZE);
    final long startMsec = System.currentTimeMillis();

    //
    //   set up Twitter Spritzer
    //
    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addConnectionLifeCycleListener(connectionLifeCycleListener);
    statusListener = new StatusListener() { // This is what really gets called to deliver stuff from twitter4j
        @Override
        public void onStatus(Status status) {
            // time to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }
            try {
                boolean success = queue.offer(status, 15L, TimeUnit.SECONDS);
                if (!success) {
                    log.warn("queue too slow!");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
            //log.info("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            // This notice will be sent each time a limited stream becomes unlimited.
            // If this number is high and or rapidly increasing, it is an indication that your predicate is too broad, and you should consider a predicate with higher selectivity.
            log.warn("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
            //log.info("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

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

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }
    };

    twitterStream.addListener(statusListener);
    twitterStream.sample(); // creates a generic StatusStream
    log.info("returned from sample()");

    return new Firehose() {

        private final Runnable doNothingRunnable = new Runnable() {
            public void run() {
            }
        };

        private long rowCount = 0L;
        private boolean waitIfmax = (getMaxEventCount() < 0L);
        private final Map<String, Object> theMap = new TreeMap<>();
        // DIY json parsing // private final ObjectMapper omapper = new ObjectMapper();

        private boolean maxTimeReached() {
            if (getMaxRunMinutes() <= 0) {
                return false;
            } else {
                return (System.currentTimeMillis() - startMsec) / 60000L >= getMaxRunMinutes();
            }
        }

        private boolean maxCountReached() {
            return getMaxEventCount() >= 0 && rowCount >= getMaxEventCount();
        }

        @Override
        public boolean hasMore() {
            if (maxCountReached() || maxTimeReached()) {
                return waitIfmax;
            } else {
                return true;
            }
        }

        @Override
        public InputRow nextRow() {
            // Interrupted to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }

            // all done?
            if (maxCountReached() || maxTimeReached()) {
                if (waitIfmax) {
                    // sleep a long time instead of terminating
                    try {
                        log.info("reached limit, sleeping a long time...");
                        sleep(2000000000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException("InterruptedException", e);
                    }
                } else {
                    // allow this event through, and the next hasMore() call will be false
                }
            }
            if (++rowCount % 1000 == 0) {
                log.info("nextRow() has returned %,d InputRows", rowCount);
            }

            Status status;
            try {
                status = queue.take();
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }

            theMap.clear();

            HashtagEntity[] hts = status.getHashtagEntities();
            String text = status.getText();
            theMap.put("text", (null == text) ? "" : text);
            theMap.put("htags", (hts.length > 0)
                    ? Lists.transform(Arrays.asList(hts), new Function<HashtagEntity, String>() {
                        @Nullable
                        @Override
                        public String apply(HashtagEntity input) {
                            return input.getText();
                        }
                    })
                    : ImmutableList.<String>of());

            long[] lcontrobutors = status.getContributors();
            List<String> contributors = new ArrayList<>();
            for (long contrib : lcontrobutors) {
                contributors.add(String.format("%d", contrib));
            }
            theMap.put("contributors", contributors);

            GeoLocation geoLocation = status.getGeoLocation();
            if (null != geoLocation) {
                double lat = status.getGeoLocation().getLatitude();
                double lon = status.getGeoLocation().getLongitude();
                theMap.put("lat", lat);
                theMap.put("lon", lon);
            } else {
                theMap.put("lat", null);
                theMap.put("lon", null);
            }

            if (status.getSource() != null) {
                Matcher m = sourcePattern.matcher(status.getSource());
                theMap.put("source", m.find() ? m.group(1) : status.getSource());
            }

            theMap.put("retweet", status.isRetweet());

            if (status.isRetweet()) {
                Status original = status.getRetweetedStatus();
                theMap.put("retweet_count", original.getRetweetCount());

                User originator = original.getUser();
                theMap.put("originator_screen_name", originator != null ? originator.getScreenName() : "");
                theMap.put("originator_follower_count",
                        originator != null ? originator.getFollowersCount() : "");
                theMap.put("originator_friends_count", originator != null ? originator.getFriendsCount() : "");
                theMap.put("originator_verified", originator != null ? originator.isVerified() : "");
            }

            User user = status.getUser();
            final boolean hasUser = (null != user);
            theMap.put("follower_count", hasUser ? user.getFollowersCount() : 0);
            theMap.put("friends_count", hasUser ? user.getFriendsCount() : 0);
            theMap.put("lang", hasUser ? user.getLang() : "");
            theMap.put("utc_offset", hasUser ? user.getUtcOffset() : -1); // resolution in seconds, -1 if not available?
            theMap.put("statuses_count", hasUser ? user.getStatusesCount() : 0);
            theMap.put("user_id", hasUser ? String.format("%d", user.getId()) : "");
            theMap.put("screen_name", hasUser ? user.getScreenName() : "");
            theMap.put("location", hasUser ? user.getLocation() : "");
            theMap.put("verified", hasUser ? user.isVerified() : "");

            theMap.put("ts", status.getCreatedAt().getTime());

            List<String> dimensions = Lists.newArrayList(theMap.keySet());

            return new MapBasedInputRow(status.getCreatedAt().getTime(), dimensions, theMap);
        }

        @Override
        public Runnable commit() {
            // ephemera in, ephemera out.
            return doNothingRunnable; // reuse the same object each time
        }

        @Override
        public void close() throws IOException {
            log.info("CLOSE twitterstream");
            twitterStream.shutdown(); // invokes twitterStream.cleanUp()
        }
    };
}

From source file:Logic.mongoC.java

public void IngresarUsuario(String name) {

    String[] buscarUs = new String[1];
    buscarUs[0] = name;/* w ww.  j av a 2  s . com*/
    try {
        ResponseList<twitter4j.User> use = twitter.lookupUsers(buscarUs);
        twitter4j.User u = use.get(0);
        System.out.println(u.getStatus());
        usuario nuevoS = new usuario();
        nuevoS.setId(Long.toString(u.getId()));
        nuevoS.setNombre(u.getName());
        nuevoS.setLocation(u.getLocation());
        nuevoS.setNumFol(u.getFollowersCount());
        nuevoS.setNumeroDeT(u.getStatusesCount());
        List<Status> twitts = twitter.getUserTimeline(u.getId(), new Paging(1, 200));
        ArrayList<twitt> timeL = new ArrayList();
        for (Status s : twitts) {
            twitt tw = new twitt();
            tw.setTexto(s.getText());
            tw.setRetwett(s.getRetweetCount());
            //tw.setFecha((java.util.Date) s.getCreatedAt());
            tw.setFav(s.getFavoriteCount());
            tw.setCreador(s.getUser().getScreenName());
            UserMentionEntity[] userMentionEntities = s.getUserMentionEntities();
            ArrayList<String> inter = new ArrayList();
            for (UserMentionEntity uh : userMentionEntities) {
                inter.add(uh.getScreenName());
            }
            tw.setPersonas(inter);
            timeL.add(tw);
        }
        nuevoS.setTimeline(timeL);
        final String fIns = gson.toJson(nuevoS);

        Document dt;
        dt = new Document("ScreenName", u.getScreenName());
        dt.append("todo", fIns);
        conect();
        coll.insertOne(dt);
        JOptionPane.showMessageDialog(null, "Usuario Ingresado");
    }

    catch (TwitterException ex) {
        System.out.println("No se pudo conectar el usuario deseado");
    }

}

From source file:mapper.TweetDataMapper.java

/**
* Transform a {@link Status} into an {@link Tweet}.
*
* @param status Object to be transformed.
* @return {@link Tweet}./*  w ww . j  a v  a 2  s  . co m*/
*/
@Override
public Tweet transform(Status status) {
    if (status == null) {
        throw new IllegalArgumentException("Cannot transform a null value");
    }
    Tweet tweet = new Tweet();
    tweet.setCreateAt(status.getCreatedAt());
    tweet.setLang(status.getLang());
    if (status.getGeoLocation() != null) {
        tweet.setLat(status.getGeoLocation().getLatitude());
        tweet.setLon(status.getGeoLocation().getLongitude());
    }
    tweet.setReTweetCount(status.getRetweetCount());
    tweet.setText(status.getText());
    return tweet;

}

From source file:nl.isaac.dotcms.twitter.pojo.CustomStatus.java

License:Creative Commons License

public CustomStatus(Status status) {
    this.createdAt = status.getCreatedAt();
    this.id = status.getId();
    this.id_str = String.valueOf(status.getId());
    this.text = status.getText();
    this.source = status.getSource();
    this.isTruncated = status.isTruncated();
    this.inReplyToStatusId = status.getInReplyToStatusId();
    this.inReplyToUserId = status.getInReplyToUserId();
    this.isFavorited = status.isFavorited();
    this.inReplyToScreenName = status.getInReplyToScreenName();
    this.geoLocation = status.getGeoLocation();
    this.place = status.getPlace();
    this.retweetCount = status.getRetweetCount();
    this.isPossiblySensitive = status.isPossiblySensitive();

    this.contributorsIDs = status.getContributors();

    this.retweetedStatus = status.getRetweetedStatus();
    this.userMentionEntities = status.getUserMentionEntities();
    this.urlEntities = status.getURLEntities();
    this.hashtagEntities = status.getHashtagEntities();
    this.mediaEntities = status.getMediaEntities();
    this.currentUserRetweetId = status.getCurrentUserRetweetId();

    this.isRetweet = status.isRetweet();
    this.isRetweetedByMe = status.isRetweetedByMe();

    this.rateLimitStatus = status.getRateLimitStatus();
    this.accessLevel = status.getAccessLevel();
    this.user = status.getUser();
}