Example usage for twitter4j Twitter search

List of usage examples for twitter4j Twitter search

Introduction

In this page you can find the example usage for twitter4j Twitter search.

Prototype

QueryResult search(Query query) throws TwitterException;

Source Link

Document

Returns tweets that match a specified query.

Usage

From source file:com.daiv.android.twitter.ui.profile_viewer.fragments.sub_fragments.ProfileMentionsFragment.java

License:Apache License

public void getMore() {
    canRefresh = false;//from  www .ja v a  2  s  .co  m

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);

                QueryResult result = twitter.search(query);

                for (twitter4j.Status status : result.getTweets()) {
                    tweets.add(status);
                }

                if (result.hasNext()) {
                    query = result.nextQuery();
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter.notifyDataSetChanged();
                        canRefresh = true;

                        if (!hasMore) {
                            View footer = inflater.inflate(R.layout.mentions_footer, null);
                            listView.addFooterView(footer);
                            listView.setFooterDividersEnabled(false);
                        }
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        canRefresh = false;
                        hasMore = false;
                    }
                });

            }

        }
    }).start();
}

From source file:com.daiv.android.twitter.ui.search.TwitterSearchFragment.java

License:Apache License

public void onRefreshStarted() {
    new Thread(new Runnable() {
        @Override/*w  ww  .  java2s.co  m*/
        public void run() {
            final long topId;
            if (tweets.size() > 0) {
                topId = tweets.get(0).getId();
            } else {
                topId = 0;
            }

            try {
                Twitter twitter = Utils.getTwitter(context, settings);
                query = new Query(searchQuery);
                if (topTweets) {
                    query.setResultType(Query.POPULAR);
                } else {
                    query.setResultType(null);
                }
                QueryResult result = twitter.search(query);

                tweets.clear();

                for (twitter4j.Status status : result.getTweets()) {
                    tweets.add(status);
                }

                if (result.hasNext()) {
                    query = result.nextQuery();
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        int top = 0;
                        for (int i = 0; i < tweets.size(); i++) {
                            if (tweets.get(i).getId() == topId) {
                                top = i;
                                break;
                            }
                        }

                        adapter = new TimelineArrayAdapter(context, tweets, onlyStatus);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);
                        listView.setSelection(top);

                        spinner.setVisibility(View.GONE);

                        mPullToRefreshLayout.setRefreshing(false);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                        mPullToRefreshLayout.setRefreshing(false);
                    }
                });
            }
        }
    }).start();
}

From source file:com.daiv.android.twitter.ui.search.TwitterSearchFragment.java

License:Apache License

public void doSearch(final String mQuery) {
    spinner.setVisibility(View.VISIBLE);

    if (listView.getVisibility() != View.GONE) {
        listView.setVisibility(View.GONE);
    }// w  ww.j  av a 2  s . c o  m

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, settings);
                Log.v("Test_searching", "query in frag: " + mQuery);
                query = new Query(mQuery);
                if (topTweets) {
                    query.setResultType(Query.ResultType.popular);
                } else {
                    query.setResultType(null);
                }
                QueryResult result = twitter.search(query);

                tweets.clear();

                for (twitter4j.Status status : result.getTweets()) {
                    tweets.add(status);
                }

                if (result.hasNext()) {
                    query = result.nextQuery();
                    hasMore = true;
                } else {
                    hasMore = false;
                }

                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapter = new TimelineArrayAdapter(context, tweets, onlyStatus);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);

                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        spinner.setVisibility(View.GONE);
                    }
                });
            }
        }
    }).start();
}

From source file:com.daiv.android.twitter.ui.search.TwitterSearchFragment.java

License:Apache License

public void getMore() {
    if (hasMore) {
        canRefresh = false;/*from ww  w  .ja  v  a  2 s .  co  m*/
        mPullToRefreshLayout.setRefreshing(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Twitter twitter = Utils.getTwitter(context, settings);
                    QueryResult result = twitter.search(query);

                    for (twitter4j.Status status : result.getTweets()) {
                        tweets.add(status);
                    }

                    if (result.hasNext()) {
                        query = result.nextQuery();
                        hasMore = true;
                    } else {
                        hasMore = false;
                    }

                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            adapter.notifyDataSetChanged();
                            mPullToRefreshLayout.setRefreshing(false);
                            canRefresh = true;
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    ((Activity) context).runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mPullToRefreshLayout.setRefreshing(false);
                            canRefresh = true;
                        }
                    });
                }
            }
        }).start();
    }
}

From source file:com.data.dataanalytics.twitter.TwitterFeed.java

public List<Tweet> getTweets(String search) {
    //   We're curious how many tweets, in total, we've retrieved.  Note that TWEETS_PER_QUERY is an upper limit,
    //   but Twitter can and often will retrieve far fewer tweets

    twitter4j.Twitter twitter = getTwitter();

    /*   This variable is the key to our retrieving multiple blocks of tweets.  In each batch of tweets we retrieve,
       we use this variable to remember the LOWEST tweet ID.  Tweet IDs are (java) longs, and they are roughly
       sequential over time.  Without setting the MaxId in the query, Twitter will always retrieve the most
       recent tweets.  Thus, to retrieve a second (or third or ...) batch of Tweets, we need to set the Max Id
       in the query to be one less than the lowest Tweet ID we've seen already.  This allows us to page backwards
       through time to retrieve additional blocks of tweets*/
    long maxID = -1;

    try {/* w w w  .  j av a2s  .  c o m*/
        //   There are limits on how fast you can make API calls to Twitter, and if you have hit your limit
        //   and continue to make calls Twitter will get annoyed with you.  I've found that going past your
        //   limits now and then doesn't seem to be problematic, but if you have a program that keeps banging
        //   the API when you're not allowed you will eventually get shut down.
        //
        //   Thus, the proper thing to do is always check your limits BEFORE making a call, and if you have
        //   hit your limits sleeping until you are allowed to make calls again.
        //
        //   Every time you call the Twitter API, it tells you how many calls you have left, so you don't have
        //   to ask about the next call.  But before the first call, we need to find out whether we're already
        //   at our limit.

        //   This returns all the various rate limits in effect for us with the Twitter API
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");

        //   This finds the rate limit specifically for doing the search API call we use in this program
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");

        //   Always nice to see these things when debugging code...
        System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n",
                searchTweetsRateLimit.getRemaining(), searchTweetsRateLimit.getLimit(),
                searchTweetsRateLimit.getSecondsUntilReset());

        //   This is the loop that retrieve multiple blocks of tweets from Twitter
        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
            //   Delay
            if (searchTweetsRateLimit.getRemaining() == 0) {
                System.out.printf("!!! Sleeping for %d seconds due to rate limits\n",
                        searchTweetsRateLimit.getSecondsUntilReset());

                //   If you sleep exactly the number of seconds, you can make your query a bit too early
                //   and still get an error for exceeding rate limitations
                //
                //    Adding two seconds seems to do the trick. Sadly, even just adding one second still triggers a
                //   rate limit exception more often than not.  I have no idea why, and I know from a Comp Sci
                //   standpoint this is really bad, but just add in 2 seconds and go about your business.  Or else.
                Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
            }

            Query q = new Query(search); // Search for tweets that contains this term
            q.setCount(TWEETS_PER_QUERY); // How many tweets, max, to retrieve
            //q.resultType("recent");                  // Get all tweets
            q.setLang("en"); // English language tweets, please

            //   If maxID is -1, then this is our first call and we do not want to tell Twitter what the maximum
            //   tweet id is we want to retrieve.  But if it is not -1, then it represents the lowest tweet ID
            //   we've seen, so we want to start at it-1 (if we start at maxID, we would see the lowest tweet
            //   a second time...
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }

            //   This actually does the search on Twitter and makes the call across the network
            QueryResult r = twitter.search(q);

            //   If there are NO tweets in the result set, it is Twitter's way of telling us that there are no
            //   more tweets to be retrieved.  Remember that Twitter's search index only contains about a week's
            //   worth of tweets, and uncommon search terms can run out of week before they run out of tweets
            if (r.getTweets().size() == 0) {
                break; // Nothing? We must be done
            }

            //   loop through all the tweets and process them. Need to save as CSV file for database
            for (Status s : r.getTweets()) { // Loop through all the tweets...
                //   Increment our count of tweets retrieved

                //   Keep track of the lowest tweet ID.  If you do not do this, you cannot retrieve multiple
                //   blocks of tweets...
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }

                //   Do something with the tweet....
                ta.processTweets(s, new Date());

            }

            //   As part of what gets returned from Twitter when we make the search API call, we get an updated
            //   status on rate limits.  We save this now so at the top of the loop we can decide whether we need
            //   to sleep or not before making the next call.
            searchTweetsRateLimit = r.getRateLimitStatus();
        }

    } catch (Exception e) {
        //   Catch all -- you're going to read the stack trace and figure out what needs to be done to fix it
        System.out.println("That didn't work well...wonder why?");

        e.printStackTrace();

    }

    System.out.printf("\n\nA total of %d tweets retrieved\n", ta.getTotalTweets());
    System.out.println("The total amount of tweets in an hour " + ta.getTweetsInAnHour());
    ta.checkIfTrending(ta.getTweetsInAnHour(), ta.getTotalTweets());

    return ta.getTweetList();
}

From source file:com.example.leonid.twitterreader.Twitter.TwitterGetTweets.java

License:Apache License

@Override
protected List<CreateTweet> doInBackground(String... params) {
    mTweetsInfo = new ArrayList<>();
    List<String> texts = new ArrayList<>();
    List<String> titles = new ArrayList<>();
    List<String> images = new ArrayList<>();
    List<String> date = new ArrayList<>();
    if (!isCancelled()) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET)
                .setOAuthAccessToken(ACCESS_KEY).setOAuthAccessTokenSecret(ACCESS_SECRET);
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        //query search result
        Query query = new Query(params[0]);
        //how much tweets need to be displayed(max 200)
        query.count(200);/*w  ww .  ja v  a2  s.co  m*/
        try {
            mResult = twitter.search(query);
            for (twitter4j.Status status : mResult.getTweets()) {
                if (!isCancelled()) {
                    texts.add(status.getText());
                    titles.add(status.getUser().getName());
                    images.add(status.getUser().getBiggerProfileImageURL());
                    String cleanDate = status.getCreatedAt().toString();
                    date.add(cleanDate.substring(0, cleanDate.length() - 15) + " "
                            + cleanDate.substring(cleanDate.length() - 4));
                }
            }
        } catch (TwitterException e) {
            Log.e("exeption", e.toString());
        }
        //loop teuth results and create array list for list view
        for (int i = 0; i < texts.size(); i++) {
            mTweetsInfo.add(new CreateTweet(titles.get(i), images.get(i), texts.get(i), date.get(i)));
        }

    }
    return mTweetsInfo;
}

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  ww w.ja v  a  2  s .c om*/
    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.happy_coding.viralo.twitter.FriendDiscoverer.java

License:Apache License

/**
 * Returns list of Twitter Friends by the given keywords.
 *
 * @param keywords//  w w w.j  a  va 2 s  .co  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./*from w ww.j  a  v  a2 s  .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 {//from   w  ww  .  j a  va  2  s  .  c om
        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();
    }
}