Example usage for twitter4j Status getCreatedAt

List of usage examples for twitter4j Status getCreatedAt

Introduction

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

Prototype

Date getCreatedAt();

Source Link

Document

Return the created_at

Usage

From source file:twittersentimentanalysis.TwitterSentimentAnalysis.java

private static Tweet getTweetObject(Status status) {
    Tweet tweet = new Tweet();
    int sentimentScore = StanfordCoreNLPTool.findSentiment(status.getText());
    if (sentimentScore != -1) {
        tweet.setDateTime(status.getCreatedAt());
        tweet.setTweetText(status.getText());
        tweet.setUsername(status.getUser().getScreenName());
        tweet.setSentimentScore(sentimentScore);
        GeoLocation geoLocation = status.getGeoLocation();
        if (geoLocation != null) {
            tweet.setLongitude(geoLocation.getLongitude() + "");
            tweet.setLatitude(geoLocation.getLatitude() + "");
        } else {//from   w  w w .  ja  v a  2 s.c  om
            tweet.setLongitude(null);//
            tweet.setLatitude(null);//
        }
        Place place = status.getPlace();
        if (place != null) {
            tweet.setCountry(place.getCountry());
            tweet.setPlace(place.getFullName());
        } else {
            tweet.setCountry(null);//
            tweet.setPlace(null);//
        }
    } else
        tweet = null;
    return tweet;
}

From source file:TwitterStats.Facade.Twitter.java

private Map<String, Integer> historicoHorario(List<Status> tuits) {
    Comparator<String> comparator = new Comparator<String>() {
        public int compare(String o1, String o2) {
            if (Integer.parseInt(o1.substring(0, o1.length() - 1)) > Integer
                    .parseInt(o2.substring(0, o2.length() - 1))) {
                return 1;
            } else if (Integer.parseInt(o1.substring(0, o1.length() - 1)) > Integer
                    .parseInt(o2.substring(0, o2.length() - 1))) {
                return -1;
            } else {
                return 0;
            }//w ww .  j av a2s.co m
        }
    };

    SortedMap<String, Integer> porHoras = new TreeMap<String, Integer>(comparator);
    GregorianCalendar cal = new GregorianCalendar();

    for (int i = 0; i < 24; i++) {
        porHoras.put(i + "h", 0);
    }

    for (Status tuit : tuits) {
        cal.setTime(tuit.getCreatedAt());
        int hour = cal.get(Calendar.HOUR_OF_DAY);

        porHoras.put(hour + "h", porHoras.get(hour + "h") + 1);
    }

    return porHoras;
}

From source file:TwitterStats.Facade.Twitter.java

private Map<String, Integer> historicoSemanal(List<Status> tuits) {
    String apoyo = "LMXJVSD";

    Comparator<String> comparator = new Comparator<String>() {
        public int compare(String o1, String o2) {
            if (apoyo.indexOf(o1) > apoyo.indexOf(o2)) {
                return 1;
            } else if (apoyo.indexOf(o1) < apoyo.indexOf(o2)) {
                return -1;
            } else {
                return 0;
            }//from   w w w  . j  av  a  2  s .  co m
        }
    };

    SortedMap<String, Integer> semanal = new TreeMap<>(comparator);
    GregorianCalendar cal = new GregorianCalendar();
    String[] semana = new String[] { "_", "D", "L", "M", "X", "J", "V", "S" };

    for (int i = 2; i < 8; i++) {
        semanal.put(semana[i], 0);
    }
    semanal.put(semana[1], 0);

    for (Status tuit : tuits) {

        cal.setTime(tuit.getCreatedAt());
        int sem = cal.get(Calendar.DAY_OF_WEEK);

        if (semanal.containsKey(semana[sem])) {
            semanal.put(semana[sem], semanal.get(semana[sem]) + 1);
        } else {
            semanal.put(semana[sem], 0);
        }
    }

    return semanal;
}

From source file:TwitterStats.Facade.Twitter.java

private Map<String, Integer> historicoDiario(List<Status> tuits, String mes) {
    Comparator<String> comparator = new Comparator<String>() {
        public int compare(String o1, String o2) {
            if (Integer.parseInt(o1) > Integer.parseInt(o2)) {
                return 1;
            } else if (Integer.parseInt(o1) < Integer.parseInt(o2)) {
                return -1;
            } else {
                return 0;
            }//from  w  ww.  jav a  2s  .  c  o  m
        }
    };

    SortedMap<String, Integer> porDias = new TreeMap<String, Integer>(comparator);
    GregorianCalendar cal = new GregorianCalendar();

    for (int i = 1; i <= Integer.parseInt(mes); i++) {
        porDias.put(i + "", 0);
    }

    for (Status tuit : tuits) {
        cal.setTime(tuit.getCreatedAt());
        int day = cal.get(Calendar.DAY_OF_MONTH);

        porDias.put(day + "", porDias.get(day + "") + 1);
    }

    return porDias;
}

From source file:twitterswingclient.TwitterClient.java

private void updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateActionPerformed
    // TODO add your handling code here:
    String consKey = "Your key";
    String consSecret = "Your secret";
    String accToken = "Your key";
    String accSecret = "Your secret";
    try {/*from  w  w  w.j ava 2s. c  o  m*/

        TwitterFactory twitterFactory = new TwitterFactory();

        Twitter twitter = twitterFactory.getInstance();

        twitter.setOAuthConsumer(consKey, consSecret);

        twitter.setOAuthAccessToken(new AccessToken(accToken, accSecret));

        StatusUpdate statusUpdate = new StatusUpdate(status.getText());

        statusUpdate.setMedia("Feeling great",
                new URL("http://media3.giphy.com/media/el1tH0BzEWm4w/giphy.gif").openStream());

        Status stat = twitter.updateStatus(statusUpdate);

        textArea.append("status.toString() = " + stat.toString());
        textArea.append("status.getInReplyToScreenName() = " + stat.getInReplyToScreenName());
        textArea.append("status.getSource() = " + stat.getSource());
        textArea.append("status.getText() = " + stat.getText());
        textArea.append("status.getContributors() = " + Arrays.toString(stat.getContributors()));
        textArea.append("status.getCreatedAt() = " + stat.getCreatedAt());
        textArea.append("status.getCurrentUserRetweetId() = " + stat.getCurrentUserRetweetId());
        textArea.append("status.getGeoLocation() = " + stat.getGeoLocation());
        textArea.append("status.getId() = " + stat.getId());
        textArea.append("status.getInReplyToStatusId() = " + stat.getInReplyToStatusId());
        textArea.append("status.getInReplyToUserId() = " + stat.getInReplyToUserId());
        textArea.append("status.getPlace() = " + stat.getPlace());
        textArea.append("status.getRetweetCount() = " + stat.getRetweetCount());
        textArea.append("status.getRetweetedStatus() = " + stat.getRetweetedStatus());
        textArea.append("status.getUser() = " + stat.getUser());
        textArea.append("status.getAccessLevel() = " + stat.getAccessLevel());
        textArea.append("status.getHashtagEntities() = " + Arrays.toString(stat.getHashtagEntities()));
        textArea.append("status.getMediaEntities() = " + Arrays.toString(stat.getMediaEntities()));

        if (stat.getRateLimitStatus() != null) {
            textArea.append("status.getRateLimitStatus().getLimit() = " + stat.getRateLimitStatus().getLimit());
            textArea.append(
                    "status.getRateLimitStatus().getRemaining() = " + stat.getRateLimitStatus().getRemaining());
            textArea.append("status.getRateLimitStatus().getResetTimeInSeconds() = "
                    + stat.getRateLimitStatus().getResetTimeInSeconds());
            textArea.append("status.getRateLimitStatus().getSecondsUntilReset() = "
                    + stat.getRateLimitStatus().getSecondsUntilReset());
            textArea.append("status.getRateLimitStatus().getRemainingHits() = "
                    + stat.getRateLimitStatus().getRemaining());
        }
        textArea.append("status.getURLEntities() = " + Arrays.toString(stat.getURLEntities()));
        textArea.append("status.getUserMentionEntities() = " + Arrays.toString(stat.getUserMentionEntities()));

    } catch (IOException ex) {
        textArea.append("IO Exception");
    } catch (TwitterException tw) {
        textArea.append("Twitter Exception");
    }
}

From source file:twittertestingagain.TwitterTesting.java

/**
 * @param args the command line arguments
 * @throws twitter4j.TwitterException/*from   w  w  w . j  a v a2s.c  o  m*/
 * @throws java.io.IOException
 */
public static void main(String[] args) throws TwitterException, IOException {

    /* ---------------------------Setting up twitter account authentication-------------------------------*/
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("YjICBJeNlnxAf3tFw7awLaCzS")
            .setOAuthConsumerSecret("8IfPzkr4opePnhCLLloKMP6X44IeNav0fLDrmtBrPbaHoxd1nO")
            .setOAuthAccessToken("4146680697-oOEPVezvvZ82vB7iP9HSbkoTG9ze9gH69XLrSCP")
            .setOAuthAccessTokenSecret("HZjsaabmVjeSkSX6vvVFdT3GWZek8xJ9RKfwaR57RDyEG");

    /* ---------------------------------File Writing Variables------------------------------------------------*/

    File outfile = new File("output.txt");
    FileWriter fwriter = new FileWriter(outfile);

    try (PrintWriter pWriter = new PrintWriter(fwriter)) {

        /*----------------------------------Search Parameters-------------------------------------*/

        String search = "chinese food";
        String lang = "en";
        /*------------------------End Search Parameters----------------------------------------*/

        int numTweets = 0;
        long maxID = -1;
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        try {

            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
            //System.out.println(rateLimitStatus);
            RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");

            /*System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n",
                searchTweetsRateLimit.getRemaining(),
                searchTweetsRateLimit.getLimit(),
                searchTweetsRateLimit.getSecondsUntilReset());
            */

            for (int queryNumber = 0; queryNumber < maxQueries; queryNumber++) {

                System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                pWriter.println("\n\n!!! Starting iteration #" + queryNumber + "\n\n");

                if (searchTweetsRateLimit.getRemaining() == 0) {
                    System.out.printf("!!! Sleeping for %d seconds due to rate limits\n",
                            searchTweetsRateLimit.getSecondsUntilReset());
                    Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                }
                //here is where we can send an object to the query
                Query query = new Query(search);
                query.setCount(tweetsPerQuery);
                query.resultType(Query.ResultType.recent);
                query.setLang(lang);

                if (maxID != -1) {
                    query.setMaxId(maxID - 1);
                }

                QueryResult result = twitter.search(query);

                if (result.getTweets().size() == 0) {
                    break;
                }

                for (Status s : result.getTweets()) {

                    numTweets++;

                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }

                    System.out.printf("On %s, @%-20s said: %s\n", s.getCreatedAt().toString(),
                            s.getUser().getScreenName(), cleanText(s.getText()));

                    pWriter.println("On " + s.getCreatedAt().toString() + " @" + s.getUser().getScreenName()
                            + " " + cleanText(s.getText()));

                }

                searchTweetsRateLimit = result.getRateLimitStatus();

            }

        }

        catch (Exception e) {

            System.out.println("Broken");

            e.printStackTrace();
        }
        System.out.printf("\n\nA total of %d tweets retrieved\n", numTweets);
        pWriter.println("\n\nA total of " + numTweets + " tweets retrieved\n\n");
        pWriter.close();

        /*while (result.hasNext()){
            numTweets += result.getCount();
        System.out.println(numTweets);
         for (Status status : result.getTweets()) {
             System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
         }  
         result.nextQuery();
        }
                   
                     
                 
                 
        /*
         QueryForm qf = new QueryForm();
           qf.show();
        */

    }

}

From source file:TwitterUserTimelineTweets.timeliner.java

public static void main(String[] args) throws JSONException, ParseException, InterruptedException {

    Postgresql.DBBaglan();// w  ww  .  j a v  a  2 s .  c  o  m
    Postgresql.DBSelect();
    Twitter twitter = new TwitterFactory().getInstance();
    int pageno = 1;
    //String user = "gasanyasan";
    List statuses = new ArrayList();

    for (int i = 0; i < 5; i++) {
        System.out.println("ARANAN KULLANICI  :  " + sonuc[i]);
        while (true) {
            try {
                int size = statuses.size();
                Paging page = new Paging(pageno++, 100);
                statuses.addAll(twitter.getUserTimeline(sonuc[i], page));
                if (statuses.size() == size)

                    break;
            } catch (TwitterException e) {

                if (e.getErrorCode() == 88) {
                    System.out.println("SORGU LMT AILDI.....UYKUYA GRYOR...");
                    Thread.sleep(900000);

                }

                //e.printStackTrace();
            }
        }
    }

    for (Object statuse : statuses) {
        Status a = (Status) statuse;
        System.out.println(a.getText());
        System.out.println(a.getCreatedAt());
        System.out.println(a.getUser().getScreenName());
        System.out.println(a.getId());
    }

    System.out.println("Total: " + statuses.size());
    // System.out.println(stats.get(0).getText());     

}

From source file:twittynumnum.BackwardGrinder.java

public void grind(String queryString) {

    try {/*www .j  av  a 2 s.  co m*/
        Query query = new Query(queryString);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " - "
                        + tweet.getCreatedAt());
            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twittynumnum.FutureListener.java

public void listen(String[] keywords) {

    StatusListener listener = new StatusListener() {
        @Override/*w  w  w .  j  ava2s . co  m*/
        public void onException(Exception arg0) {

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice arg0) {

        }

        @Override
        public void onScrubGeo(long arg0, long arg1) {

        }

        @Override
        public void onStatus(Status status) {
            User user = status.getUser();
            String username = user.getScreenName();
            String profileLocation = user.getLocation();
            long tweetId = status.getId();
            String content = status.getText();
            Date tweetDate = status.getCreatedAt();
            out.print(tweetId + "\t" + tweetDate + "\t" + username + "\t" + profileLocation + "\t"
                    + content.replaceAll("\n", "/n") + "\n");
        }

        @Override
        public void onTrackLimitationNotice(int arg0) {

        }

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

    };

    FilterQuery filter = new FilterQuery();

    filter.track(keywords);
    twitterStream.addListener(listener);
    twitterStream.filter(filter);
}

From source file:uk.ac.susx.tag.method51.twitter.Tweet.java

License:Apache License

public Tweet(Status status) {
    this();//from  w  w  w. j a  v a2  s  . com
    created = status.getCreatedAt();
    id = status.getId();
    text = status.getText();

    inReplyToStatusId = status.getInReplyToStatusId();
    inReplyToUserId = status.getInReplyToUserId();

    originalText = null;
    retweetId = -1;
    isTruncated = status.isTruncated();
    isRetweet = status.isRetweet();
    Status entities = status;
    if (isRetweet) {
        Status origTweet = status.getRetweetedStatus();
        entities = origTweet;
        retweetId = origTweet.getId();
        originalText = text;
        text = origTweet.getText();
    }

    StringBuilder sb = new StringBuilder();

    for (HashtagEntity e : entities.getHashtagEntities()) {
        sb.append(e.getText());
        sb.append(" ");
    }
    hashtags = sb.toString();
    sb = new StringBuilder();

    for (UserMentionEntity e : entities.getUserMentionEntities()) {
        sb.append(e.getScreenName());
        sb.append(" ");
    }
    mentions = sb.toString();
    sb = new StringBuilder();

    for (URLEntity e : entities.getURLEntities()) {
        //String url = e.getURL();
        String url = e.getExpandedURL();
        if (url == null) {
            url = e.getURL();
            if (url != null) {
                sb.append(url);
            }

        } else {
            sb.append(url);
        }
        sb.append(" ");
    }
    urls = sb.toString();
    sb = new StringBuilder();

    //seems to be null if no entries
    MediaEntity[] mediaEntities = entities.getMediaEntities();
    if (mediaEntities != null) {
        for (MediaEntity e : mediaEntities) {
            String url = e.getMediaURL();
            sb.append(url);
            sb.append(" ");
        }
        mediaUrls = sb.toString();
    } else {
        mediaUrls = "";
    }

    received = new Date();

    source = status.getSource();
    GeoLocation geoLoc = status.getGeoLocation();
    Place place = status.getPlace();

    if (geoLoc != null) {

        geoLong = geoLoc.getLongitude();
        geoLat = geoLoc.getLatitude();
    } else if (place != null && place.getBoundingBoxCoordinates() != null
            && place.getBoundingBoxCoordinates().length > 0) {

        GeoLocation[] locs = place.getBoundingBoxCoordinates()[0];

        double avgLat = 0;
        double avgLon = 0;

        for (GeoLocation loc : locs) {

            avgLat += loc.getLatitude();
            avgLon += loc.getLongitude();
        }

        avgLat /= locs.length;
        avgLon /= locs.length;

        geoLat = avgLat;
        geoLong = avgLon;
    } else {

        geoLong = null;
        geoLat = null;
    }

    twitter4j.User user = status.getUser();

    if (user != null) {
        userId = user.getId();
        location = user.getLocation();
        screenName = user.getScreenName();
        following = user.getFriendsCount();
        name = user.getName();
        lang = user.getLang();
        timezone = user.getTimeZone();
        userCreated = user.getCreatedAt();
        followers = user.getFollowersCount();
        statusCount = user.getStatusesCount();
        description = user.getDescription();
        url = user.getURL();
        utcOffset = user.getUtcOffset();
        favouritesCount = user.getFavouritesCount();

        this.user = new User(user);
    }
}