List of usage examples for twitter4j QueryResult getTweets
List<Status> getTweets();
From source file:alberapps.java.noticias.tw.tw4j.ProcesarTwitter4j.java
License:Open Source License
/** * Buscar//from w w w . ja v a2s . com * * @return lista */ public List<TwResultado> recuperarSearch() { List<TwResultado> listaResultados = null; try { Query query = new Query("from:Alicante_City"); QueryResult resultados = twitter.search(query); List<Status> timeline = resultados.getTweets(); listaResultados = new ArrayList<>(); TwResultado resultado = null; for (int i = 0; i < timeline.size(); i++) { resultado = new TwResultado(); resultado.setId(Long.toString(timeline.get(i).getId())); resultado.setFechaDate(timeline.get(i).getCreatedAt()); resultado.setNombreCompleto(timeline.get(i).getUser().getName()); resultado.setUsuario(timeline.get(i).getUser().getScreenName()); resultado.setMensaje(timeline.get(i).getText()); resultado.setImagen(timeline.get(i).getUser().getMiniProfileImageURLHttps()); // Imagen de perfil resultado.setImagenBitmap(recuperaImagen(resultado.getImagen())); resultado.setUrl(""); listaResultados.add(resultado); } } catch (TwitterException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listaResultados; }
From source file:android.stickynotes.StickyNotesActivity.java
License:Apache License
private void getTweets(String twit) { wifi.setWifiEnabled(true);/*from w ww . j a v a 2 s . co m*/ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("TvywVhWx7r7QQev2UGfA4g") .setOAuthConsumerSecret("Nv22zsyf1VS0vvi6hwAMyvJk9LUtSXwRUB4xwp2gRs"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { QueryResult result = twitter.search(new Query(twit)); List<Tweet> tweets = result.getTweets(); textStatus.setText(""); textStatus.append("Recent tweets about '" + twit + "':\n"); for (Tweet tweet : tweets) { textStatus.append("@" + tweet.getFromUser() + " - " + tweet.getText() + "\n\n"); } } catch (TwitterException te) { te.printStackTrace(); textStatus.append("Failed to search tweets: " + te.getMessage() + " " + twit); } }
From source file:apptwitter.Metodos.java
public void buscarTrending(String busqueda) throws TwitterException { Query query = new Query(busqueda); QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); }// w w w. j ava 2 s . co m }
From source file:au.com.infiniterecursion.hashqanda.MainActivity.java
public boolean loadTweets() { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("Q2DfeCNOxprbDp66fWlw") .setOAuthConsumerSecret("TgyJ26CKXz1SxGiEJx4HG9rytFsqiMZlEPeCO7S9g"); Twitter twitter = new TwitterFactory(cb.build()).getInstance(); // clear tweet list. MainActivity.this.runOnUiThread(new Runnable() { public void run() { // add to it , via the runOnUIThread app.getTweetList().clear();// w ww . java2 s .com } }); try { Log.d(TAG, " starting Tweets loading "); Query q = new Query("#qanda"); q.setRpp(numberTweets); QueryResult result = twitter.search(q); List<Tweet> tweets = result.getTweets(); for (Tweet tweet : tweets) { // Log.d(TAG, "@" + tweet.getFromUser() + " - " + // tweet.getText()); // Log.d(TAG, " img url " + tweet.getProfileImageUrl()); final CachedBitmapAndTweet cachedbmtwt = new CachedBitmapAndTweet(); cachedbmtwt.twt = tweet; try { URL url = new URL(tweet.getProfileImageUrl()); InputStream is = (InputStream) url.getContent(); if (is != null) { Bitmap bitmap = BitmapFactory.decodeStream(is); cachedbmtwt.bm = bitmap; } else { cachedbmtwt.bm = null; } } catch (MalformedURLException e) { e.printStackTrace(); cachedbmtwt.bm = null; } catch (IOException e) { e.printStackTrace(); cachedbmtwt.bm = null; } catch (NullPointerException npe) { npe.printStackTrace(); cachedbmtwt.bm = null; } MainActivity.this.runOnUiThread(new Runnable() { public void run() { // add to it , via the runOnUIThread app.getTweetList().add(cachedbmtwt); } }); } Log.d(TAG, " finished Tweets loading "); return true; } catch (TwitterException te) { te.printStackTrace(); Log.d(TAG, "Failed to search tweets: " + te.getMessage()); return false; } }
From source file:au.net.moon.tSearchArchiver.SearchArchiver.java
License:Open Source License
SearchArchiver() { Twitter twitter;/*from ww w .j av a 2 s . co m*/ int waitBetweenRequests = 2000; // 2 sec delay between requests to avoid maxing out the API. Status theTweet; Query query; QueryResult result; // String[] searches; ArrayList<String> searchQuery = new ArrayList<String>(); ArrayList<Integer> searchId = new ArrayList<Integer>(); int searchIndex; int totalTweets; SimpleDateFormat myFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"); System.out.println("tSearchArchiver: Loading search queries..."); // Set timezone to UTC for the Twitter created at dates myFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); twitterAuthorise twitterAuth = new twitterAuthorise(false); twitter = twitterAuth.getTwitter(); // Open the old twitter_archive database openSQLDataBase(); if (isDatabaseReady()) { // probably should have these in an object not separate arrays? try { rs = stmt.executeQuery("select * from searches where active = true"); // perform each search while (rs.next()) { // if (searchQuery searchQuery.add(rs.getString("query")); searchId.add(rs.getInt("id")); } if (rs.wasNull()) { System.out.println("tSearchArchiver: No searches in the table \"searches\""); System.exit(30); } else { System.out.println("tSearchArchiver: Found " + searchQuery.size() + " searches."); } } catch (SQLException e) { System.out.println("tSearchArchiver: e:" + e.toString()); } searchIndex = 0; totalTweets = 0; // set initial value of i to start from middle of search set while (searchIndex < searchQuery.size()) { query = new Query(); query.setQuery(searchQuery.get(searchIndex)); // check to see if their are any tweets already in the database for // this search //TODO: Change this to look in new raw data files for each search instead long max_tw_id = 0; try { rs = stmt.executeQuery("select max(tweet_id) as max_id from archive where search_id = " + searchId.get(searchIndex)); if (rs.next()) { max_tw_id = rs.getLong("max_id"); // System.out.println("MaxID: " + max_tw_id); query.setSinceId(max_tw_id); } } catch (SQLException e1) { System.err.println("tSearchArchiver: Error looking for maximum tweet_id for " + query.getQuery() + " in archive"); e1.printStackTrace(); } // System.out.println("Starting searching for tweets for: " + // query.getQuery()); // new style replacement for pagination // Query query = new Query("whatEverYouWantToSearch"); // do { // result = twitter.search(query); // System.out.println(result); // do something // } while ((query = result.nextQuery()) != null); // TODO: check if twitter4j is doing all the backing off handling already int tweetCount = 0; Boolean searching = true; do { // delay waitBetweenRequests milliseconds before making request // to make sure not overloading API try { Thread.sleep(waitBetweenRequests); } catch (InterruptedException e1) { System.err.println("tSearchArchiver: Sleep between requests failed."); e1.printStackTrace(); } try { result = twitter.search(query); } catch (TwitterException e) { System.out.println(e.getStatusCode()); System.out.println(e.toString()); if (e.getStatusCode() == 503) { // TODO use the Retry-After header value to delay & then // retry the request System.out .println("tSearchArchiver: Delaying for 10 minutes before making new request"); try { Thread.sleep(600000); } catch (InterruptedException e1) { System.err.println( "tSearchArchiver: Sleep for 10 minutes because of API load failed."); e1.printStackTrace(); } } result = null; } if (result != null) { List<Status> results = result.getTweets(); if (results.size() == 0) { searching = false; } else { tweetCount += results.size(); for (int j = 0; j < results.size(); j++) { theTweet = (Status) results.get(j); String cleanText = theTweet.getText(); cleanText = cleanText.replaceAll("'", "'"); cleanText = cleanText.replaceAll("\"", """); try { stmt.executeUpdate("insert into archive values (0, " + searchId.get(searchIndex) + ", '" + theTweet.getId() + "', now())"); } catch (SQLException e) { System.err.println("tSearchArchiver: Insert into archive failed."); System.err.println(searchId.get(searchIndex) + ", " + theTweet.getId()); e.printStackTrace(); } // TODO: change to storing in file instead of database try { rs = stmt.executeQuery("select id from tweets where id = " + theTweet.getId()); } catch (SQLException e) { System.err.println( "tSearchArchiver: checking for tweet in tweets archive failed."); e.printStackTrace(); } Boolean tweetNotInArchive = false; try { tweetNotInArchive = !rs.next(); } catch (SQLException e) { System.err.println( "tSearchArchiver: checking for tweet in archive failed at rs.next()."); e.printStackTrace(); } if (tweetNotInArchive) { String tempLangCode = ""; // getIsoLanguageCode() has been removed from twitter4j // looks like it might be added back in in the next version // if (tweet.getIsoLanguageCode() != null) { // if (tweet.getIsoLanguageCode().length() > 2) { // System.out // .println("tSearchArchiver Error: IsoLanguageCode too long: >" // + tweet.getIsoLanguageCode() // + "<"); // tempLangCode = tweet // .getIsoLanguageCode() // .substring(0, 2); // } else { // tempLangCode = tweet // .getIsoLanguageCode(); // } // } double myLatitude = 0; double myLongitude = 0; int hasGeoCode = 0; if (theTweet.getGeoLocation() != null) { System.out.println("GeoLocation: " + theTweet.getGeoLocation().toString()); myLatitude = theTweet.getGeoLocation().getLatitude(); myLongitude = theTweet.getGeoLocation().getLongitude(); hasGeoCode = 1; } Date tempCreatedAt = theTweet.getCreatedAt(); String myDate2 = myFormatter .format(tempCreatedAt, new StringBuffer(), new FieldPosition(0)) .toString(); totalTweets++; try { stmt.executeUpdate("insert into tweets values (" + theTweet.getId() + ", '" + tempLangCode + "', '" + theTweet.getSource() + "', '" + cleanText + "', '" + myDate2 + "', '" + theTweet.getInReplyToUserId() + "', '" + theTweet.getInReplyToScreenName() + "', '" + theTweet.getUser().getId() + "', '" + theTweet.getUser().getScreenName() + "', '" + hasGeoCode + "'," + myLatitude + ", " + myLongitude + ", now())"); } catch (SQLException e) { System.err.println("tSearchArchiver: Insert into tweets failed."); System.err.println(theTweet.getId() + ", '" + tempLangCode + "', '" + theTweet.getSource() + "', '" + cleanText + "', '" + myDate2 + "', '" + theTweet.getInReplyToUserId() + "', '" + theTweet.getInReplyToScreenName() + "', '" + theTweet.getUser().getId() + "', '" + theTweet.getUser().getScreenName()); e.printStackTrace(); } } } } } } while ((query = result.nextQuery()) != null && searching); if (tweetCount > 0) { System.out.println("tSearchArchiver: New Tweets Found for \"" + searchQuery.get(searchIndex) + "\" = " + tweetCount); } else { // System.out.println("tSearchArchiver: No Tweets Found for \"" // + searchQuery.get(searchIndex) + "\" = " + tweetCount); } try { stmt.executeUpdate("update searches SET lastFoundCount=" + tweetCount + ", lastSearchDate=now() where id=" + searchId.get(searchIndex)); } catch (SQLException e) { System.err.println("tSearchArchiver: failed to update searches with lastFoundCount=" + tweetCount + " and datetime for search: " + searchId.get(searchIndex)); e.printStackTrace(); } searchIndex++; } System.out.println("tSearchArchiver: Completed all " + searchQuery.size() + " searches"); System.out.println("tSearchArchiver: Archived " + totalTweets + " new tweets"); } }
From source file:Beans.Crawler.java
public String teste() { String result = ""; int totalTweets = 0; long maxID = -1; GeoLocation geo = new GeoLocation(Double.parseDouble("-19.9225"), Double.parseDouble("-43.9450")); result += geo.getLatitude() + " " + geo.getLongitude() + "<br><br>"; Twitter twitter = getTwitter();//from w w w. ja v a2 s . c om try { Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets"); result += "You have " + searchTweetsRateLimit.getRemaining() + " calls remaining out of " + searchTweetsRateLimit.getLimit() + ", Limit resets in " + searchTweetsRateLimit.getSecondsUntilReset() + " seconds<br/><br/>"; for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) { // Do we need to delay because we've already hit our rate limits? if (searchTweetsRateLimit.getRemaining() == 0) { // Yes we do, unfortunately ... // 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_TERM); //.geoCode((geo), 100, "mi"); // Search for tweets that contains this term q.setCount(TWEETS_PER_QUERY); // How many tweets, max, to retrieve // q.setGeoCode(geo, 100, Query.Unit.mi); // q.setSince("2012-02-20"); // // 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. In this sample program, we just print them // out, but in a real application you might save them to a database, a CSV file, do some // analysis on them, whatever... for (Status s : r.getTweets()) // Loop through all the tweets... { // Increment our count of tweets retrieved totalTweets++; // 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.... result += "ID: " + s.getId() + " Data " + s.getCreatedAt().toString() + " user " + s.getUser().getScreenName() + " texto: " + cleanText(s.getText()) + " <br/>"; } // 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 } result += "<br><br>" + totalTweets + "<br>"; return result; }
From source file:Beans.Crawler.java
public List search(Categoria categoria, Localizacao localizacao) throws Exception { long maxID = -1; List<Tweet> list = new ArrayList<Tweet>(); Twitter twitter = getTwitter();/*from w w w. j a va 2s . co m*/ try { Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets"); for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) { if (searchTweetsRateLimit.getRemaining() == 0) { } String works = localizacao.getPalavrasChaves(); String[] arrWorks = works.split(","); String keywork = "", or = "OR"; for (int i = 0; i < arrWorks.length; i++) { if ((i + 1) >= arrWorks.length) { or = ""; } keywork += " \"" + arrWorks[i] + "\" " + or; } System.out.println("exclude:retweets " + categoria.getDescricao() + keywork); Query q = new Query("exclude:retweets " + categoria.getDescricao() + keywork); q.setCount(TWEETS_PER_QUERY); if (maxID != -1) { q.setMaxId(maxID - 1); } QueryResult r = twitter.search(q); if (r.getTweets().size() == 0) { break; } for (Status s : r.getTweets()) { if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } Tweet t = new Tweet(); t.setUsuario(s.getUser().getId()); String dataPostagem = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(s.getCreatedAt()); t.setDataPostagem(dataPostagem); t.setTweet(s.getText()); t.setTweetId(s.getId()); t.setCategoriaId(categoria.getId()); t.setLocalizacaoId(localizacao.getId()); list.add(t); } searchTweetsRateLimit = r.getRateLimitStatus(); } } catch (Exception e) { throw e; } return list; }
From source file:br.com.controller.TweetController.java
public String search() { Categoria c = new CategoriaDAO().find(Integer.parseInt(categoria)); Localizacao l = new LocalizacaoDAO().find(Integer.parseInt(localizacao)); long maxID = -1; Twitter twitter = getTwitter();/* w w w . jav a2s . c o m*/ try { Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets"); for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) { if (searchTweetsRateLimit.getRemaining() == 0) { } String works = c.getPalavrasChaves(); String[] arrWorks = works.split(","); String keywork = "", or = "OR", query = ""; for (int i = 0; i < arrWorks.length; i++) { if ((i + 1) >= arrWorks.length) { or = ""; } keywork += " \"" + arrWorks[i] + "\" " + or; } query = "exclude:retweets " + keywork; works = l.getPalavrasChaves(); arrWorks = works.split(","); keywork = ""; or = "OR"; for (int i = 0; i < arrWorks.length; i++) { if ((i + 1) >= arrWorks.length) { or = ""; } keywork += " \"" + arrWorks[i] + "\" " + or; } query += keywork; Query q = new Query(query); q.setCount(TWEETS_PER_QUERY); if (maxID != -1) { q.setMaxId(maxID - 1); } QueryResult r = twitter.search(q); if (r.getTweets().size() == 0) { break; } for (Status s : r.getTweets()) { if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } Tweet t = new Tweet(); t.setUsuario(s.getUser().getId()); t.setDataPostagem(s.getCreatedAt()); t.setTweet(s.getText()); if (!new DAO.TweetDAO().hastTweet(s.getId())) { t.setTweetId(s.getId()); t.setCategoria(c); t.setLocalizacao(l); jpa.saveOrUpdate(t); } } searchTweetsRateLimit = r.getRateLimitStatus(); } } catch (Exception e) { } return "index"; }
From source file:br.com.porcelli.hornetq.integration.twitter.stream.reclaimer.AbstractBaseReclaimLostTweets.java
License:Apache License
protected void loadQuery(final String query, final Long lastTweetId, final Twitter twitter) throws Exception { try {//from w w w.j a v a2 s .co m if (lastTweetId == null) { return; } int page = 1; while (true) { final Query qry = new Query(query).sinceId(lastTweetId).page(page); final QueryResult qr = twitter.search(qry); if (qr.getTweets().size() == 0) { break; } for (final Tweet activeTweet : qr.getTweets()) { message.postMessage(activeTweet, true); } page++; } } catch (Exception e) { exceptionNotifier.notifyException(e); } }
From source file:br.unisal.twitter.bean.TwitterBean.java
public void consultarTweets() { TwitterFactory TwitterFactory = new TwitterFactory(); Twitter twitter = TwitterFactory.getSingleton(); List<Status> tweets = new ArrayList<>(); Query query = new Query(getTwittQuery()); try {//from w ww . j a va 2 s .c om QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); StringBuilder builder = new StringBuilder(); double lon = 0; double lat = 0; for (Status s : tweets) { if ((s.getGeoLocation() != null)) { lon = s.getGeoLocation().getLongitude(); lat = s.getGeoLocation().getLatitude(); } Tweet t = new Tweet(s.getUser().getName(), s.getUser().getLocation(), s.getText(), s.getCreatedAt(), lat, lon); dao.insert(t); builder.append(t.toString()); } this.getUiResultQuery().setSubmittedValue(builder.toString()); } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); } }