Example usage for twitter4j Status getId

List of usage examples for twitter4j Status getId

Introduction

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

Prototype

long getId();

Source Link

Document

Returns the id of the status

Usage

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();
}

From source file:nl.utwente.bigdata.bolts.TimelineBolt.java

License:Apache License

private List<Status> getTimeline(long id) throws Exception {
    int COUNT = 10;
    int GET = 10;
    List<Status> stati = new LinkedList<Status>();
    int page = 1;
    long timelineMaxId = Integer.MAX_VALUE;
    while (stati.size() < GET) {
        while (timelineRemaining < 5) {
            getRateLimit();/*from  w  w w .  j a v  a2  s  .c  o  m*/
            long sleep = Math.max(timelineNextTime - System.currentTimeMillis(), 10000);
            System.out.println("Sleeping " + sleep);
            Thread.sleep(Math.min(sleep, 60 * 1000));
        }
        Paging paging = new Paging(page, COUNT, 1, timelineMaxId - 1);
        List<Status> statuses = twitter.getUserTimeline(id, paging);

        for (Status status : statuses) {
            if (status != null) {
                stati.add(status);
                timelineMaxId = Math.min(status.getId(), timelineMaxId);
            }
        }

    }
    return stati;
}

From source file:nl.utwente.bigdata.bolts.TimelineBolt.java

License:Apache License

@Override
public void execute(Tuple tuple, BasicOutputCollector collector) {
    if (twitter == null)
        return;/* w w  w . j  a  v  a2s .c  o  m*/

    try {
        System.out.println(tuple);
        String d = tuple.getString(0);
        System.out.println("Retrieving id: " + d);
        long id = Long.parseLong(d);

        for (Status s : getTimeline(id)) {
            String statusS = DataObjectFactory.getRawJSON(s);
            collector.emit(new Values(s.getId() + "", statusS));
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:nlptexthatespeechdetection.NLPTextHateSpeechDetection.java

/**
 * @param args the command line arguments
 *//*from  ww  w .j a  v  a2 s . c o  m*/
public static void main(String[] args) throws TwitterException, NotDirectoryException, IOException {
    HateSpeechClassifier1 classifier = new HateSpeechClassifier1();
    AnnotatedDataFolder data = new AnnotatedDataFolder("data");
    boolean overSampling = false;
    classifier.train(data.getDateSortedLabeledData(overSampling));

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    StatusListener listener = new StatusListener() {
        int numHateSpeech = 0;
        int numTweets = 0;

        @Override
        public void onStatus(Status status) {
            if (status.getLang().equals("in")) {
                numTweets++;
                if (classifier.isHateSpeech(status.getText(), 0.5)) {
                    System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * "
                            + status.getId() + " # " + status.getLang() + " $ "
                            + (status.getGeoLocation() == null ? "NULLGEO"
                                    : status.getGeoLocation().toString()));
                    System.out.println();
                    System.out.println("lang: " + status.getLang());
                    System.out.println("number of detected hate speech: " + numHateSpeech);
                    System.out.println("total number of streamed tweets: " + numTweets);
                    System.out.println();
                    System.out.println();
                    numHateSpeech++;
                }
            } else {
                System.out.println("ignoring non-Indonesian tweet");
            }
            //                if (status.getGeoLocation() != null) {
            //                    System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * " + status.getId() + " $ " + status.getGeoLocation().toString());
            //                }
            //                if (status.getLang().equals("id")) {
            //                    System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + " * " + status.getId() + " # " + status.getLang() + " $ " + (status.getGeoLocation() == null ? "NULLGEO" : status.getGeoLocation().toString()));
            //                }
        }

        @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);

    FilterQuery filterQuery = new FilterQuery();
    filterQuery.track(new String[] { "a", "i", "u", "e", "o" });
    filterQuery.language("in");
    twitterStream.filter(filterQuery);

    twitterStream.sample();
}

From source file:noki.preciousshot.helper.TwitterHelper.java

License:Apache License

public static void tweetMedia(String text, File file) {

    Thread thread = new Thread() {
        private String text;
        private File file;

        public Thread setArgs(String text, File file) {
            this.text = text;
            this.file = file;
            return this;
        }//from w  ww .j a va 2s  .  co m

        @Override
        public void run() {
            ConfigurationBuilder cb = new ConfigurationBuilder();
            cb.setDebugEnabled(true).setOAuthConsumerKey(PreciousShotData.twitterKeys[0])
                    .setOAuthConsumerSecret(PreciousShotData.twitterKeys[1])
                    .setOAuthAccessToken(PreciousShotData.twitterKeys[2])
                    .setOAuthAccessTokenSecret(PreciousShotData.twitterKeys[3]);
            TwitterFactory tf = new TwitterFactory(cb.build());
            Twitter twitter = tf.getInstance();

            try {
                Status status = twitter.updateStatus(new StatusUpdate(this.text).media(this.file));
                if (status != null && status.getId() != 0) {
                    String url = String.format("https://twitter.com/%s/status/%s", twitter.getScreenName(),
                            status.getId());
                    PreciousShotCore.log("the url is %s.", url);
                    LangHelper.sendChatWithUrl(LangKey.TWITTER_SUCCESS, LangKey.TWITTER_URL, url);
                } else {
                    LangHelper.sendChat(LangKey.TWITTER_FAILED);
                }
            } catch (TwitterException e) {
                LangHelper.sendChat(LangKey.TWITTER_FAILED);
            }
        }
    }.setArgs(text, file);

    thread.start();

}

From source file:nz.net.speakman.android.dreamintweets.twitterstream.TwitterStreamAdapter.java

License:Apache License

private String getTweetUrl(Status tweet) {
    return String.format(URL_FORMAT_TWEET_LINK, tweet.getUser().getScreenName(), tweet.getId());
}

From source file:ontoSentiment.Busca.java

public void buscarPorAssunto(String busca, String lang) throws TwitterException {
    int totalTweets = 0;
    long maxID = -1;
    Query q = new Query(busca + " -filter:retweets -filter:links -filter:replies -filter:images");
    q.setCount(Util.TWEETS_PER_QUERY); // How many tweets, max, to retrieve 
    q.resultType(Query.ResultType.recent); // Get all tweets 
    q.setLang(lang);//from   w w  w .ja  v  a2  s .co m
    QueryResult r = Util.getTwitter().search(q);
    do {
        for (Status s : r.getTweets()) {
            totalTweets++;
            if (maxID == -1 || s.getId() < maxID) {
                maxID = s.getId();
            }

            //System.out.printf("O tweet de id %s disse as %s, @%-20s disse: %s\n", new Long(s.getId()).toString(), s.getCreatedAt().toString(), s.getUser().getScreenName(), Util.cleanText(s.getText()));
            System.out.println(Util.cleanText(s.getText()));
        }
        q = r.nextQuery();
        if (q != null) {
            q.setMaxId(maxID);
            r = Util.getTwitter().search(q);
            System.out.println("Total tweets: " + totalTweets);
            System.out.println("Maximo ID: " + maxID);
            Util.imprimirRateLimit(Util.RATE_LIMIT_OPTION_SEARCH_TWEETS);
        }
    } while (q != null);
}

From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java

/** Contacts the Twitter API and gets any number of tweets corresponding to a certain query. The main
 * purpose of this function is to avoid the limit of 100 tweets that can be extracted at once.
 *
 * @param numberOfTweets the number of tweets to be printed
 * @param query the query to be searched by the twitter client
 * @param twitter the twitter client//ww  w . j  a  va 2  s  .c o  m
 *
 * @return A JSON string containing a Data object with either a list containing the tweets as a payload
 * (when successful) or a String payload (for errors).
 */
private Data getTweetsByCount(int numberOfTweets, Query query, Twitter twitter) {
    ArrayList<Status> tweets = new ArrayList<>();
    if (!(numberOfTweets > 0)) {
        // Default of 15 tweets
        numberOfTweets = 15;
    }
    // Set the last ID to the maximum possible value as a default
    long lastID = Long.MAX_VALUE;
    int original;
    try {
        while (tweets.size() < numberOfTweets) {

            // Keep number of original to avoid infinite looping when not getting enough tweets
            original = tweets.size();
            // If there are more than 100 tweets left to be extracted, extract
            // 100 during the next query, since 100 is the limit to retrieve at once
            if (numberOfTweets - tweets.size() > 100)
                query.setCount(100);
            else
                query.setCount(numberOfTweets - tweets.size());
            // Extract tweets corresponding to the query then add them to the list
            QueryResult result = twitter.search(query);
            tweets.addAll(result.getTweets());
            // Iterate through the list and get the lastID to know where to start from
            // if there are more tweets to be extracted
            for (Status status : tweets)
                if (status.getId() < lastID)
                    lastID = status.getId();
            query.setMaxId(lastID - 1);
            // Break the loop if the tweet count didn't change. This would prevent an infinite loop when
            // tweets for the specified query are not available
            if (tweets.size() == original)
                break;
        }
    }

    catch (TwitterException te) {
        // Put the list of tweets in Data format then output as JSon String.
        // Since we checked earlier for errors, we assume that an error occuring at this point due
        // to Rate Limits is caused by a too high request. Thus, we output the retrieved tweets and log
        // the error
        String errorDataJson = generateError(te.getMessage());
        logger.error(errorDataJson);
        if (te.exceededRateLimitation() && tweets.size() > 0) {
            Data<ArrayList<Status>> tweetsData = new Data<>();
            tweetsData.setDiscriminator(Discriminators.Uri.LIST);
            tweetsData.setPayload(tweets);
            return tweetsData;
        } else {
            return Serializer.parse(errorDataJson, Data.class);
        }
    }

    // Return a special error message if no tweets are found
    if (tweets.size() == 0) {
        String noTweetsMessage = "No tweets found for the following query. "
                + "Note: Twitter's REST API only retrieves tweets from the past week.";
        String errorDataJson = generateError(noTweetsMessage);
        return Serializer.parse(errorDataJson, Data.class);
    }

    else {
        // Put the list of tweets in Data format then output as JSon String.
        Data<ArrayList<Status>> tweetsData = new Data<>();
        tweetsData.setDiscriminator(Discriminators.Uri.LIST);
        tweetsData.setPayload(tweets);
        return tweetsData;
    }
}

From source file:org.anhonesteffort.ads.twitter.TweetModel.java

License:Open Source License

public TweetModel(Status status) {
    id = status.getId();
    timeMs = status.getCreatedAt().getTime();
    handle = status.getUser().getScreenName();
    accountPic = status.getUser().getProfileImageURLHttps();
    text = status.getText();/*from w ww.j  av  a  2s  . c  om*/
}

From source file:org.apache.asterix.external.input.record.reader.twitter.TwitterPullRecordReader.java

License:Apache License

@Override
public IRawRecord<Status> next() throws IOException, InterruptedException {
    if (result == null || nextTweetIndex >= result.getTweets().size()) {
        Thread.sleep(1000 * requestInterval);
        query.setSinceId(lastTweetIdReceived);
        try {// w ww  .  j av a 2 s  . c o  m
            result = twitter.search(query);
        } catch (TwitterException e) {
            throw new HyracksDataException(e);
        }
        nextTweetIndex = 0;
    }
    if (result != null && !result.getTweets().isEmpty()) {
        List<Status> tw = result.getTweets();
        Status tweet = tw.get(nextTweetIndex++);
        if (lastTweetIdReceived < tweet.getId()) {
            lastTweetIdReceived = tweet.getId();
        }
        record.set(tweet);
        return record;
    } else {
        return null;
    }
}