Example usage for twitter4j QueryResult getTweets

List of usage examples for twitter4j QueryResult getTweets

Introduction

In this page you can find the example usage for twitter4j QueryResult getTweets.

Prototype

List<Status> getTweets();

Source Link

Usage

From source file:com.eventattend.portal.bl.TwitterBL.java

License:Open Source License

public List searchTweets(String msg, AccessToken accessToken, String userTimeZone, TwitterDTO twitterDTO)
        throws BaseAppException {

    twitter.setOAuthAccessToken(accessToken);
    List twitterSearchList = null;
    DateUtility dateUtility = new DateUtility();
    twitterSearchList = new ArrayList();
    // TwitterDTO twitterDTO = null;      
    String tweetContect = null;//from   w  w  w.  j a  v  a2s .  c om
    String lang = null;
    Query query = null;
    QueryResult result = null;
    try {
        //query.setSince("2010-10-09"); 
        if (twitterDTO.getEventTags() != null) {
            String[] eventTags = twitterDTO.getEventTags();
            for (int i = 0; i < eventTags.length; i++) {
                query = new Query(eventTags[i]);
                result = twitter.search(query);
                int tweetBreak = 0;
                if (APP_MODE.equalsIgnoreCase("DEVELOPMENT")) {
                    tweetBreak = 1;
                } else {
                    tweetBreak = 5;
                }

                int initTweetCount = 0;
                for (Tweet tweet : result.getTweets()) {

                    twitterDTO = new TwitterDTO();
                    User user = null;
                    lang = tweet.getIsoLanguageCode();

                    /*To include RichContent to the Tweet Created Time*/
                    Date dt = tweet.getCreatedAt();
                    /*To convert the Tweeted date user Time Zone*/
                    TimeZone userTimeZ = TimeZone.getTimeZone(userTimeZone);
                    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    df.setTimeZone(userTimeZ);
                    String today = df.format(dt);
                    String createdTime = today;
                    String tweetCreatedAt = dateUtility.sessionCommentTimeCheck(createdTime, userTimeZone);
                    //System.out.println(initTweetCount +" "+tweet.getIsoLanguageCode()+" "+tweet.getCreatedAt()+" "+tweet.getFromUserId()+" <<>> "+tweet.getFromUser()+" <<>> "+tweet.getText()+" << >> "+tweet.getProfileImageUrl());
                    if (lang.equals("en")) {
                        initTweetCount++;
                        System.out.println(
                                initTweetCount + " " + tweet.getIsoLanguageCode() + " " + tweet.getCreatedAt()
                                        + " " + tweet.getFromUserId() + " <<>> " + tweet.getFromUser()
                                        + " <<>> " + tweet.getText() + " << >> " + tweet.getProfileImageUrl());

                        try {
                            if (tweet.getFromUser() != null) {
                                user = twitter.showUser(tweet.getFromUser());
                            }

                        } catch (TwitterException e) {
                            processTwitterException(e);
                        }

                        if (user != null) {
                            if (tweet.getFromUser() != null) {
                                twitterDTO.setTweetCreatedAt(tweetCreatedAt);
                                twitterDTO.setUserImg(tweet.getProfileImageUrl());
                                twitterDTO.setUserScreeName("http://twitter.com/" + tweet.getFromUser());
                                twitterDTO.setUserName(user.getName());
                                tweetContect = tweet.getText();

                                /*To include RichContent to the Tweet*/
                                StringBuffer tweetText = new StringBuffer(tweetContect);
                                String delimiters = " ";
                                String rep = null;
                                String repText = tweetText.toString();
                                repText = changeTweetToRichContent(repText);
                                //System.out.println("repText  "+repText);
                                twitterDTO.setTweet(repText);

                            }
                        }
                        twitterSearchList.add(twitterDTO);
                    }

                    if (tweetBreak == initTweetCount) {
                        break;
                    }
                }
            }
        } else {
            query = new Query(msg);
            result = twitter.search(query);
            int tweetBreak = 0;
            if (APP_MODE.equalsIgnoreCase("DEVELOPMENT")) {
                tweetBreak = 1;
            } else {
                tweetBreak = 5;
            }
            int initTweetCount = 0;
            for (Tweet tweet : result.getTweets()) {

                twitterDTO = new TwitterDTO();
                User user = null;
                lang = tweet.getIsoLanguageCode();

                /*To include RichContent to the Tweet Created Time*/
                Date dt = tweet.getCreatedAt();
                /*To convert the Tweeted date user Time Zone*/
                TimeZone userTimeZ = TimeZone.getTimeZone(userTimeZone);
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                df.setTimeZone(userTimeZ);
                String today = df.format(dt);
                String createdTime = today;
                String tweetCreatedAt = dateUtility.sessionCommentTimeCheck(createdTime, userTimeZone);

                if (lang.equals("en")) {
                    initTweetCount++;
                    System.out.println(
                            initTweetCount + " " + tweet.getIsoLanguageCode() + " " + tweet.getCreatedAt() + " "
                                    + tweet.getFromUserId() + " <<>> " + tweet.getFromUser() + " <<>> "
                                    + tweet.getText() + " << >> " + tweet.getProfileImageUrl());

                    try {
                        if (tweet.getFromUser() != null) {
                            user = twitter.showUser(tweet.getFromUser());
                        }

                    } catch (TwitterException e) {
                        processTwitterException(e);
                    }

                    if (user != null) {
                        if (tweet.getFromUser() != null) {
                            twitterDTO.setTweetCreatedAt(tweetCreatedAt);
                            twitterDTO.setUserImg(tweet.getProfileImageUrl());
                            twitterDTO.setUserScreeName("http://twitter.com/" + tweet.getFromUser());
                            twitterDTO.setUserName(user.getName());
                            tweetContect = tweet.getText();

                            /*To include RichContent to the Tweet*/
                            StringBuffer tweetText = new StringBuffer(tweetContect);
                            String delimiters = " ";
                            String rep = null;
                            String repText = tweetText.toString();
                            repText = changeTweetToRichContent(repText);
                            //System.out.println("repText  "+repText);
                            twitterDTO.setTweet(repText);

                        }
                    }
                    twitterSearchList.add(twitterDTO);
                }

                if (tweetBreak == initTweetCount) {
                    break;
                }
            }
        }
    } catch (TwitterException e) {

        processTwitterException(e);

    }
    return twitterSearchList;
}

From source file:com.firewallid.crawling.TwitterApp.java

public List<Status> replyTo(Status status) {
    String userScreenName = status.getUser().getScreenName();
    String date = new SimpleDateFormat("YYYY-MM-DD").format(status.getCreatedAt());
    Query query = new Query("to:" + userScreenName + " since:" + date);
    List<Status> repliesAll = new ArrayList<>();

    while (query != null) {
        QueryResult result = search(query);

        List<Status> replies = result.getTweets().parallelStream()
                /* Only reply to status's id*/
                .filter(tweet -> tweet.getInReplyToStatusId() == status.getId()).collect(Collectors.toList());

        repliesAll.addAll(replies);/*from   w ww  . j a va2 s  . c o  m*/
        query = result.nextQuery();
    }

    return repliesAll;
}

From source file:com.firewallid.crawling.TwitterApp.java

public List<Status> searchTweet(String keyword, int limit) {
    List<Status> result = new ArrayList<>();
    Query query = new Query(keyword);
    while (query != null && result.size() <= limit) {
        QueryResult search = search(query);
        result.addAll(search.getTweets());
        query = search.nextQuery();/*from w  w  w.  j  a  v  a2 s  .com*/
    }
    return result;
}

From source file:com.fsatir.twitter.TwitterManagedBean.java

public List<Media> trendImageList(Twitter twitter, String trendName) {

    Query query = new Query(trendName + " AND filter:images");
    query.setCount(1);/*from  w ww  .j  a v  a2 s  .  c  o m*/
    QueryResult result;
    try {
        do {
            result = twitter.search(query);

            List<twitter4j.Status> tweets = result.getTweets();
            int counter = 0;
            for (twitter4j.Status status : tweets) {

                Media myMedia = new Media();
                int control = 0;
                for (MediaEntity me : status.getMediaEntities()) {
                    //Tek grsel almay kesinletirmek iin kontrol.
                    //leride modeldeki trendImgURL diziye dntrlerek kontrol kaldrlabilir.
                    if (control < 1)
                        myMedia.setTrendImgURL(me.getMediaURLHttps());
                    control++;
                }
                // URL null deilse, grsel ve bigileri list'e eklenir.
                if (myMedia.getTrendImgURL() != null) {
                    myMedia.setTweetID(status.getId());
                    myMedia.setFavorite_count(status.getFavoriteCount());
                    myMedia.setRetweet_count(status.getRetweetCount());
                    //myMedia.setTrendImgURL(status.getMediaEntities()[0].getMediaURLHttps());
                    myMedia.setTrendName(trendName);
                    myMedia.setName(Long.toString(status.getId()));
                    myMedia.setType(status.getMediaEntities()[0].getType());

                    myMediaList.add(counter++, myMedia);
                }
            }
        } while ((query = result.nextQuery()) != null && result.getRateLimitStatus().getRemaining() > 0);

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

    myMediaListFiltered = filterList(myMediaList);

    return myMediaListFiltered;

}

From source file:com.fuzuapp.model.resultados.TwitterAdapter.java

@Override
public List<Resultado> getResultados(GeoPoint ponto, double raio) {

    List<Resultado> resultados = new ArrayList();
    try {/*w  w w . j  a  v a  2 s . c om*/
        Query query = new Query("");
        GeoLocation geo = new GeoLocation(ponto.getLatitude(), ponto.getLongitude());
        query.setGeoCode(geo, raio, Query.KILOMETERS);
        query.resultType(Query.RECENT);
        query.setCount(20);
        QueryResult result = twitter.search(query);

        for (Status status : result.getTweets()) {
            Resultado r = new Resultado();

            r.setDescricao(status.getText());
            r.setUrl("http://twitter.com/statuses/" + String.valueOf(status.getId()));
            r.setNomeUsuario(status.getUser().getName());
            r.setHorario(new SimpleDateFormat("dd/MM HH:mm").format(status.getCreatedAt()));
            r.setFotoUrl(status.getUser().getProfileImageURL());
            //r.setLocal(new GeoPoint(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));
            r.setTipo(Resultado.TEXTO);

            resultados.add(r);

        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterAdapter.class.getName()).log(Level.SEVERE, null, ex);
    }

    return resultados;
}

From source file:com.happy_coding.viralo.twitter.FriendDiscoverer.java

License:Apache License

/**
 * Returns list of Twitter Friends by the given keywords.
 *
 * @param keywords/*from w w  w . java  2 s .c  o m*/
 * @return
 */
public List<Contact> findFriends(List<String> keywords) {

    Joiner joiner = Joiner.on(" ").skipNulls();

    String twitterKeywords = joiner.join(keywords);

    Twitter twitter = new TwitterFactory().getInstance();
    List<Contact> contacts = new ArrayList<Contact>();

    for (int i = 1; i <= MAX_FRIENDS_ITERATIONS; i++) {

        Query query = new Query(twitterKeywords);
        query.setPage(i);
        query.setRpp(FRIENDS_PER_PAGE);

        QueryResult result = null;
        try {
            result = twitter.search(query);
        } catch (TwitterException e) {
            logger.error("can't find friends", e);
            return null;
        }

        List<String> tmpFriendList = new ArrayList<String>();

        for (Tweet tweet : result.getTweets()) {
            String user = tweet.getFromUser();

            if (!tmpFriendList.contains(user)) {
                Contact newContact = new Contact(user);
                newContact.setUid(tweet.getFromUserId());
                contacts.add(newContact);
                tmpFriendList.add(user);
            }
        }
        try {
            Thread.sleep(WAIT_BETWEEN_KEYWORD_SEARCH_IN_MS);
        } catch (InterruptedException e) {
            logger.error("can't find friends", e);
            return null;
        }
    }

    return contacts;
}

From source file:com.happy_coding.viralo.twitter.SmartPoster.java

License:Apache License

/**
 * Returns tweet for keywords.//w w  w. jav a 2s. c o  m
 *
 * @param keywords
 * @return
 */
public ContactTweet getTweet(String keywords) {

    Query query = new Query(keywords);
    query.setPage(1);
    query.setRpp(TWEETS_PER_PAGE);

    Twitter twitter = new TwitterFactory().getInstance();

    QueryResult result = null;

    try {
        result = twitter.search(query);
    } catch (TwitterException e) {
        logger.error("can't load tweet", e);
        return null;
    }

    /*
    just get the first tweet.
     */
    Tweet firstTweet = result.getTweets().get(0);

    Contact contact = new Contact(firstTweet.getFromUserId());
    contact.setName(firstTweet.getFromUser());

    ContactTweet contactTweet = new ContactTweet(contact, firstTweet.getText());

    return contactTweet;
}

From source file:com.ibm.TwitterAsyncService.java

License:Open Source License

@Override
public void run() {
    String bookTitle = ac.getRequest().getParameter("title");
    String bookAuthor = ac.getRequest().getParameter("author");
    boolean translate = Boolean.parseBoolean(ac.getRequest().getParameter("enable"));

    logger.debug("Requested book title {} and author {}", bookTitle, bookAuthor);

    Query query = new Query(bookTitle + " " + bookAuthor);
    query.setResultType(Query.RECENT);

    Twitter twitter = TwitterFactory.getSingleton();

    try {/* w  w w  .ja v a 2 s .com*/
        PrintWriter writer = ac.getResponse().getWriter();
        Locale locale = ac.getRequest().getLocale();
        WatsonTranslate watson = new WatsonTranslate(locale);

        // Just get the first page of results to avoid exceeding the Twitter rate limit
        QueryResult result = twitter.search(query);

        Alchemy alchemy = new Alchemy();

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

        logger.debug("Current tweets {}", tweets.toString());

        for (Status tweetMessage : tweets) {
            JSONObject json = new JSONObject();
            JSONObject tweet = new JSONObject();
            // We need to put the tweet and link into an inner object
            // so that we can use a special formatter in bootstrap table

            json.put("screenName", tweetMessage.getUser().getScreenName());

            if (translate) {
                String message = watson.translate(tweetMessage.getText());
                tweet.put("message", message);
                json.put("sentiment", alchemy.getSentiment(message));
            } else {
                tweet.put("message", tweetMessage.getText());
                json.put("sentiment", alchemy.getSentiment(tweetMessage.getText()));
            }

            String url = "https://twitter.com/" + tweetMessage.getUser().getScreenName() + "/status/"
                    + tweetMessage.getId();

            tweet.put("link", url);

            json.put("tweet", tweet);

            writer.write(("data: " + json.toString() + "\n\n"));
            writer.flush();
        }

        writer.write(("event: finished\n"));
        writer.write(("data: \n\n"));
        writer.flush();
        writer.close();
    } catch (TwitterException e) {
        logger.error("Twitter Error {}", e.getMessage());
    } catch (IOException e) {
        logger.error("could not write SSE {}", e.getMessage());
    } catch (NullPointerException e) {
        logger.error("Exception Twitter Async Service {}", e.getMessage());
    } finally {
        ac.complete();
    }
}

From source file:com.infine.android.devoxx.service.TwitterService.java

License:Apache License

public void triggerRefresh() {
    try {//  ww  w  .j a  va 2s.  c  om
        final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        long lastTweetId = prefs.getLong(LAST_TWEET_ID, 0);
        Query query = new Query(TWEETS_QUERY);
        if (lastTweetId > 0) {
            query.setSinceId(lastTweetId);
        }
        QueryResult result = mTwitter.search(query);
        Log.i("Twitter", "nombre de tweets recu:" + result.getTweets().size());
        ArrayList<ContentProviderOperation> databaseOps = new ArrayList<ContentProviderOperation>();
        long maxId = 0;
        for (Status status : result.getTweets()) {
            maxId = Math.max(maxId, status.getId());
            databaseOps.add(buildCPOperation(status));
        }
        // batch update
        if (!databaseOps.isEmpty()) {
            mResolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, databaseOps);
        }
        if (maxId > 0) {
            prefs.edit().putLong(LAST_TWEET_ID, maxId);
        }

    } catch (TwitterException e) {
        // pas de message c'est qui doit pas avoir de reseau
        // Toast.makeText(this, "Erreur durant la rcupration des Tweets",
        // Toast.LENGTH_SHORT).show();
    } catch (RemoteException e) {
        // pas de message
        e.printStackTrace();
    } catch (OperationApplicationException e) {
        // pas de message
        e.printStackTrace();
    }
}

From source file:com.javielinux.api.loaders.SearchLoader.java

License:Apache License

@Override
public BaseResponse loadInBackground() {

    try {/*from   w  w w. j a va  2 s.c o m*/
        SearchResponse response = new SearchResponse();

        ConnectionManager.getInstance().open(getContext());

        if (entitySearch.getInt("notifications") == 1) {
            response.setInfoSaveTweets(entitySearch.saveTweets(getContext(), false, since_id));
        } else {
            response.setInfoSaveTweets(null);

            ArrayList<InfoTweet> infoTweets = new ArrayList<InfoTweet>();

            if (entitySearch.isUser()) {
                // La bsqueda es de un usuario, as que buscamos en twitter directamente
                ResponseList<Status> statuses = ConnectionManager.getInstance().getUserForSearchesTwitter()
                        .getUserTimeline(entitySearch.getString("from_user"));
                for (twitter4j.Status status : statuses) {
                    infoTweets.add(new InfoTweet(status));
                }
            } else {
                Query query = entitySearch.getQuery(getContext());
                if (since_id != -1)
                    query.setSinceId(since_id);
                QueryResult result = ConnectionManager.getInstance().getUserForSearchesTwitter().search(query);
                ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();
                for (Status tweet : tweets) {
                    infoTweets.add(new InfoTweet(tweet));
                }
            }

            response.setInfoTweets(infoTweets);
        }

        return response;
    } catch (Exception e) {
        e.printStackTrace();
        ErrorResponse response = new ErrorResponse();
        response.setError(e, e.getMessage());
        return response;
    }
}