Example usage for twitter4j Status getText

List of usage examples for twitter4j Status getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text of the status

Usage

From source file:cojoytuerto.CojoYTuertoFrame.java

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
    // TODO add your handling code here:
    if (evt.getClickCount() == 2) {
        Status ms = mensajes.get(jTable1.getSelectedRow());
        DefaultTableModel tm = (DefaultTableModel) jTable1.getModel();

        if (jTable1.getColumnName(jTable1.getSelectedColumn()).equals("FV")) {
            //FV/*w w  w.  j a v a2 s. c o m*/

            System.out.println("FV: " + ms.getText());
            try {
                twitter.createFavorite(ms.getId());
            } catch (TwitterException ex) {
                Logger.getLogger(CojoYTuertoFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
            tm.setValueAt("FV", jTable1.getSelectedRow(), jTable1.getSelectedColumn());

        } else if (jTable1.getColumnName(jTable1.getSelectedColumn()).equals("RT")) {
            //RT
            if (!ms.isRetweetedByMe()) {
                try {
                    twitter.retweetStatus(ms.getId());
                    System.out.println("RT: " + mensajes.get(jTable1.getSelectedRow()).getText());
                } catch (TwitterException ex) {
                    Logger.getLogger(CojoYTuertoFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            tm.setValueAt("RT", jTable1.getSelectedRow(), jTable1.getSelectedColumn());
        }
    }
}

From source file:Collector.TweetCollector.java

public static List<Status> getTweets(final String q) {
    Timer timer = new Timer();
    TimerTask hourlyTask = new TimerTask() {

        @Override//from  w  w  w  . j a v  a 2  s  .  co m
        public void run() {

            long amountOfTweets = 0;

            try {

                long maxID = -1;

                Query query = new Query(q);
                //printTimeLine(query);
                Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
                RateLimitStatus searchLimit = rateLimitStatus.get("/search/tweets");
                for (int batchNumber = 0; MAX_QUERIES < 10; batchNumber++) {

                    System.out.printf("\n\n!!! batch %d\n\n", batchNumber);

                    if (searchLimit.getRemaining() == 0) {
                        // so as to not get blocked by twitter
                        Thread.sleep(searchLimit.getSecondsUntilReset() + 3 * 1001);
                    }

                    query.setCount(TWEETS_PER_QUERY);// constant value of 100
                    query.setResultType(Query.ResultType.recent);
                    query.setLang("en");// only english tweets

                    if (maxID != -1) {
                        query.setMaxId(maxID - 1);// so the first querys not set to previous max
                    }
                    QueryResult result = twitter.search(query);
                    if (result.getTweets().size() == 0) {
                        break;
                    }

                    for (Status s : result.getTweets()) {
                        amountOfTweets++;
                        if (maxID == -1 || s.getId() < maxID) {
                            maxID = s.getId();
                        }
                        storeTweet(s);// where stored in db

                        System.out.printf("At%s : %s\n", // debugging purposes
                                s.getCreatedAt().toString(), s.getText());
                        searchLimit = result.getRateLimitStatus(); //resets
                        System.out.printf("\n\nA total of %d tweet retrieved\n", amountOfTweets);

                    }

                }

            } catch (TwitterException te) {

                System.out.println("Error Code :" + te.getErrorCode());
                System.out.println("Exception Code " + te.getExceptionCode());
                System.out.println("Status Code " + te.getStatusCode());

                if (te.getStatusCode() == 401) {
                    System.out.println("Twitter Error :\nAuthentication "
                            + "credentials (https://dev.twitter.com/auth) "
                            + " are either missing of incorrect, " + "\nplease check consumer key /secret");
                }
            } catch (InterruptedException ex) {

            }

        }
    };

    // schedule the task to run starting now and then every hour...
    timer.schedule(hourlyTask, 0l, 1000 * 60 * 60);
    return statuses;

}

From source file:Collector.TweetCollector.java

public static List<Status> printTimeLine(String account) {

    try {//ww  w .j a v  a2  s.  com
        Query query = new Query(account);

        QueryResult result = twitter.search(query);

        List<Status> tweets = result.getTweets();

        for (Status tweet : tweets) {
            System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
        }
        return tweets;

    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
    return null;
}

From source file:Collector.TweetCollector.java

public static void storeTweet(Status tweet) {

    BasicDBObject basicOBJ = new BasicDBObject();
    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());
    basicOBJ.put("created_at", tweet.getCreatedAt());

    try {//w  w  w  .j  a v  a2s.c om
        items.insert(basicOBJ);

    } catch (Exception e) {
        System.out.println("Could not store Tweet please try again" + e.getMessage());

    }

}

From source file:collector.TwitterCollector.java

public LinkedHashSet<Tweet> search(String queryExpression, int maxResults) {
    Query query = new Query(queryExpression);
    int numberOfTweets = maxResults;//512;
    long lastID = Long.MAX_VALUE;
    query = query.lang("pt");
    List<Status> tweets = new ArrayList<>();
    boolean finish = false;
    while ((tweets.size() < numberOfTweets) && !finish) {
        System.out.print(".");
        if (numberOfTweets - tweets.size() > 100) {//100) {
            query.setCount(100);//100);
        } else {//from www  .j a  v  a 2 s.co m
            query.setCount(numberOfTweets - tweets.size());
        }
        try {
            QueryResult result = twitter.search(query);
            List<Status> resultList = result.getTweets();
            if (resultList == null || resultList.isEmpty()) {
                finish = true;
                System.out.println("no foram encontrados mais tweets");
            } else {
                tweets.addAll(resultList);
                for (Status t : tweets) {
                    if (t.getId() < lastID) {
                        lastID = t.getId();
                    }
                }
            }
        } catch (TwitterException ex) {
            System.err.println(ex.getMessage());
        }
        query.setMaxId(lastID - 1);
    }
    LinkedHashSet<Tweet> out = new LinkedHashSet<>();
    for (Status status : tweets) {
        if (!status.getText().startsWith("RT")) {
            TwitterUser user;
            user = new TwitterUser().addID(status.getUser().getId()).addName(status.getUser().getName())
                    .addLocation(status.getUser().getLocation()).addDateSignin(status.getUser().getCreatedAt())
                    .addCountTweets(status.getUser().getStatusesCount())
                    .addCountFavorites(status.getUser().getFavouritesCount())
                    .addCountFriends(status.getUser().getFriendsCount())
                    .addCountFollowers(status.getUser().getFollowersCount());
            Tweet tweet = new Tweet().addUser(user).addText(status.getText()).addID(status.getId())
                    .addDate(status.getCreatedAt())
                    .addLatitude(status.getGeoLocation() != null ? status.getGeoLocation().getLatitude()
                            : Double.MAX_VALUE)
                    .addLongitude(status.getGeoLocation() != null ? status.getGeoLocation().getLongitude()
                            : Double.MAX_VALUE);
            out.add(tweet);
        }
    }
    return out;
}

From source file:collector.TwitterCollector.java

public LinkedHashSet<Tweet> userSearchData(String userName, int maxResults) {

    LinkedHashSet<Tweet> out = new LinkedHashSet<>();
    Paging paging = new Paging(1, 180);
    int numberOfTweets = maxResults;//512;
    long lastID = Long.MAX_VALUE;
    ArrayList<Status> status = new ArrayList<>();
    while (status.size() < numberOfTweets) {
        if (numberOfTweets - status.size() > 180) {//100) {
            paging.setCount(180);//100);
        } else {/*from  w w  w .ja v a2  s .  c  o  m*/
            paging.setCount(numberOfTweets - status.size());
        }
        try {
            List<Status> timeLine = twitter.getUserTimeline(userName, paging);
            status.addAll(timeLine);
            for (Status t : status) {
                if (t.getId() < lastID) {
                    lastID = t.getId();
                }
            }
        } catch (TwitterException ex) {
            System.err.println(ex.getMessage());
        }
        paging.setMaxId(lastID - 1);
    }

    //armazenar os atributos interessantes a analise dos tweets
    int qtdretweet = 0;
    for (Status sta : status) {
        String text = sta.getText();
        if (!sta.isRetweet() && !sta.isRetweeted() && !text.startsWith("RT")) { //&& !TweetMediaDetect.detect(text)) {
            TwitterUser user;
            user = new TwitterUser().addID(sta.getUser().getId()).addName(sta.getUser().getName())
                    .addLocation(sta.getUser().getLocation()).addDateSignin(sta.getUser().getCreatedAt())
                    .addCountTweets(sta.getUser().getStatusesCount())
                    .addCountFavorites(sta.getUser().getFavouritesCount())
                    .addCountFriends(sta.getUser().getFriendsCount())
                    .addCountFollowers(sta.getUser().getFollowersCount());
            Tweet tweet = new Tweet().addUser(user).addText(sta.getText()).addID(sta.getId())
                    .addDate(sta.getCreatedAt())
                    .addLatitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLatitude()
                            : Double.MAX_VALUE)
                    .addLongitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLongitude()
                            : Double.MAX_VALUE);
            out.add(tweet);
        } else {
            qtdretweet++;
        }
    }

    return out;
}

From source file:com.adobe.acs.commons.twitter.impl.TwitterFeedUpdaterImpl.java

License:Apache License

private String processTweet(Status status) {
    String tweet = status.getText();

    for (URLEntity entity : status.getURLEntities()) {
        String url = String.format("<a target=\"_blank\" href=\"%s\">%s</a>", entity.getURL(), entity.getURL());
        tweet = tweet.replace(entity.getURL(), url);
    }/*from  w w  w. ja  v  a 2 s  .  c  om*/

    return tweet;

}

From source file:com.ahuralab.mozaic.db.Message.java

License:Open Source License

public static Message create(Status status) {

    User user = status.getUser();/*  w  ww . ja v  a2s .  c  om*/

    return new Message(status.getText(), status.getCreatedAt(), status.getRetweetCount(), user.getId(),
            user.getName(), user.getScreenName(), user.getLocation(), user.getDescription(),
            user.getProfileImageURL(), status.getId(), 0, 0, user.getFollowersCount(), user.getStatusesCount());
}

From source file:com.alainesp.fan.sanderson.SummaryFragment.java

License:Open Source License

private String getTweetText(twitter4j.Status tweet) {
    SpannableStringBuilder text = new SpannableStringBuilder(tweet.getText());

    URLEntity[] urls = tweet.getURLEntities();
    MediaEntity[] medias = tweet.getMediaEntities();

    for (MediaEntity media : medias)
        if ("photo".equals(media.getType())) {
            InternetHelper.getRemoteFile(media.getMediaURLHttps());
            text.setSpan(new ImageSpan(null, media.getMediaURLHttps()), media.getStart(), media.getEnd(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }/* w  w w .jav  a  2s .  c om*/

    for (URLEntity url : urls) {
        text.setSpan(new URLSpan(url.getURL()), url.getStart(), url.getEnd(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        text.replace(url.getStart(), url.getEnd(), url.getExpandedURL());
    }

    return Html.toHtml(text);
}

From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java

License:Open Source License

@Command(name = "twitter", desc = "displays the last tweet of a twitter user", aliases = { "twit" })
@Usage(".twitter <user>")
public CommandResult twitter(CommandSource source, CommandContext context) {
    if (source.getSource() == CommandSource.Source.USER
            && (context.getPrefix() == null || !context.getPrefix().equals("."))) {
        return null;
    }//w  w  w  . jav a 2s . co  m
    if (context.getArgs() == null || context.getArgs().length < 1) {
        return get(ReturnType.NOTICE, "Correct usage is .twitter <user>", source, context);
    }

    try {
        List<Status> statusList = twitter.getUserTimeline(context.getArgs()[0]);
        if (statusList == null || statusList.size() < 1) {
            return get(ReturnType.MESSAGE, "User has no tweets!", source, context);
        }
        Status status = statusList.get(0);
        status.getUser();
        StringBuilder builder = new StringBuilder();
        builder.append(status.getUser().getScreenName()).append(Colors.BLUE).append(": ").append(Colors.NORMAL)
                .append(status.getText()).append(" (");

        Period period = new Period(new DateTime(status.getCreatedAt()), new DateTime());
        if (period.getWeeks() > 2 || period.getMonths() > 1 || period.getYears() > 1) {
            builder.append(longTimeFormatter.print(period));
        } else {
            builder.append(timeFormatter.print(period));
        }
        builder.append(" ago)");
        return get(ReturnType.MESSAGE, builder.toString().replace(lineBreak, " "), source, context);
    } catch (TwitterException e) {
        if (e.getStatusCode() == 404) {
            return get(ReturnType.MESSAGE, "User not found!", source, context);
        } else if (e.getStatusCode() == 401) {
            return get(ReturnType.MESSAGE, "Access denied by Twitter!", source, context);
        } else {
            e.printStackTrace();
            return get(ReturnType.MESSAGE, "There was an internal error!", source, context);
        }
    }
}