List of usage examples for twitter4j Twitter search
QueryResult search(Query query) throws TwitterException;
From source file:es.portizsan.twitrector.tasks.TweetSearchTask.java
License:Open Source License
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) { long before = System.currentTimeMillis() - (1000 * 60 * 15); try {/*from w w w .ja v a2 s . c o m*/ List<Twitrector> trl = new TwitrectorService().getTwitrectors(); if (trl == null || trl.isEmpty()) { logger.log(Level.WARNING, "No Twitrectors found!!!!!"); return; } for (Twitrector tr : trl) { logger.info("Searching for :" + tr.getQuery()); String search = tr.getQuery(); Twitter twitter = new TwitterService().getTwitterInstance(); Query query = new Query(search); query.setLocale("es"); query.setCount(100); if (tr.getLocation() != null) { GeoLocation location = new GeoLocation(tr.getLocation().getLatitude(), tr.getLocation().getLongitude()); Unit unit = Unit.valueOf(tr.getLocation().getUnit().name()); query.setGeoCode(location, tr.getLocation().getRadius(), unit); } QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { if (tweet.getCreatedAt().getTime() < before) continue; Queue queue = QueueFactory.getQueue("default"); queue.add(TaskOptions.Builder.withUrl("/tasks/tweetReply") .param("statusId", String.valueOf(tweet.getId())) .param("message", "@" + tweet.getUser().getScreenName() + " " + String.valueOf(tr.getResponse()))); logger.info("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); } } catch (TwitterException te) { logger.log(Level.WARNING, "Failed to search tweets: ", te); } }
From source file:es.upm.oeg.entity.extractor.extractor.gate.TwitterCorpus.java
public void createCorpus() { repository = new FarolasRepo(); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try {/*from w w w .ja v a 2 s.c om*/ corpus = Factory.newCorpus("tweetcorpus"); Query query = new Query(queryString); //"oddfarolas" QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { Document doc = Factory.newDocument(tweet.getText()); doc.setName(String.valueOf(tweet.getId())); corpus.add(doc); logger.info(tweet.getId() + " @" + tweet.getUser().getScreenName() + " - " + tweet.getText() + " -" + tweet.getGeoLocation()); repository.instanciateNew(String.valueOf(tweet.getId()), tweet.getUser().getScreenName(), tweet.getText(), tweet.getGeoLocation()); } } catch (TwitterException te) { logger.error(te); logger.error("Failed to search tweets: " + te.getMessage()); System.exit(-1); } catch (ResourceInstantiationException ex) { logger.error(ex); } logger.info("corpus size" + corpus.size()); }
From source file:gui.project2.v1.FXMLDocumentController.java
@FXML public void searchloaction() throws InterruptedException { int maxFollowerCount = 0; userslocations = new ArrayList<>(); nodes = new ArrayList<>(); GraphicsContext gc = graph.getGraphicsContext2D(); gc.setFill(Color.GAINSBORO);/*from w ww.ja va2 s. co m*/ gc.fillRect(0, 0, 308, 308); Twitter twitter; twitter = tf.getInstance(); ArrayList<User> users = new ArrayList<>(); try { Query query = new Query(""); GeoLocation location; location = new GeoLocation(parseDouble(latitude.getText()), parseDouble(longitude.getText())); Query.Unit unit = Query.KILOMETERS; query.setGeoCode(location, parseDouble(radius.getText()), unit); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); boolean q = false; if (userslocations != null && !userslocations.isEmpty()) { for (int i = 0; i < userslocations.size(); i++) { if (userslocations.get(i).getName().equals(tweet.getUser().getScreenName())) { q = true; break; } } } if (!q && tweet.getGeoLocation() != null) { pair n; String latString = ""; String lonString = ""; int la = 0; int lo = 0; String geoString = tweet.getGeoLocation().toString(); for (int i = 0; i < geoString.length(); i++) { if (geoString.charAt(i) == '=') { if (la == 0) { la = 1; } else if (la == -1) { lo = 1; } } else if (geoString.charAt(i) == ',') { la = -1; } else if (geoString.charAt(i) == '}') { lo = -1; } else if (la == 1) { latString = latString + geoString.charAt(i); } else if (lo == 1) { lonString = lonString + geoString.charAt(i); } } User thisUser; thisUser = tweet.getUser(); double lat = parseDouble(latString); double lon = parseDouble(lonString); System.out.println(tweet.getGeoLocation().toString()); n = new pair(tweet.getUser().getScreenName(), lat, lon); userslocations.add(n); users.add(thisUser); if (thisUser.getFollowersCount() > maxFollowerCount) { maxFollowerCount = thisUser.getFollowersCount(); } } } } while ((query = result.nextQuery()) != null); for (int i = 0; i < users.size(); i++) { if (i % 14 == 0 && i != 0) { Thread.sleep(1000 * 60 * 15 + 30); } IDs friends; friends = twitter.getFriendsIDs(users.get(i).getId(), -1); for (long j : friends.getIDs()) { for (int k = i + 1; k < users.size(); k++) { if (users.get(k).getId() == j) { nodes.add(users.get(i).getScreenName() + ":" + users.get(k).getScreenName()); } } } } } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } double xmin; double xmax; double ymin; double ymax; xmin = userslocations.get(0).getA(); xmax = userslocations.get(0).getA(); ymin = userslocations.get(0).getB(); ymax = userslocations.get(0).getB(); for (int i = 1; i < userslocations.size(); i++) { if (xmin > userslocations.get(i).getA()) { xmin = userslocations.get(i).getA(); } if (xmax < userslocations.get(i).getA()) { xmax = userslocations.get(i).getA(); } if (ymin > userslocations.get(i).getB()) { ymin = userslocations.get(i).getB(); } if (ymax < userslocations.get(i).getB()) { ymax = userslocations.get(i).getB(); } } for (int i = 0; i < userslocations.size(); i++) { if (userslocations.get(i).getA() - xmin >= 0 && userslocations.get(i).getB() - ymin >= 0) { gc.setLineWidth(users.get(i).getFollowersCount() / maxFollowerCount * 3 + 1); gc.strokeOval((userslocations.get(i).getA() - xmin) / (xmax - xmin) * 300 + 4, (userslocations.get(i).getB() - ymin) / (ymax - ymin) * 300 + 4, 4, 4); } } ObservableList<String> usersLeftList = FXCollections.observableArrayList(); for (int i = 0; i < users.size() - 1; i++) { User k = null; for (int j = i + 1; j < users.size(); j++) { if (users.get(j).getFollowersCount() > users.get(i).getFollowersCount()) { k = users.get(i); users.set(i, users.get(j)); users.set(j, k); } } } for (int i = 0; i < users.size() / 5; i++) { usersLeftList.add(users.get(i).getScreenName() + " " + users.get(i).getFollowersCount()); } listView.setItems(usersLeftList); gc.setLineWidth(1); gc.setFill(Color.BLUE); for (int i = 0; i < nodes.size(); i++) { String user1 = ""; String user2 = ""; int p = 0; double x1 = 0; double x2 = 0; double y1 = 0; double y2 = 0; for (int j = 0; j < nodes.get(i).length(); j++) { if (nodes.get(i).charAt(j) == ':') { p = 1; } else if (p == 0) { user1 = user1 + nodes.get(i).charAt(j); } else if (p == 1) { user2 = user2 + nodes.get(i).charAt(j); } } for (int j = 0; j < userslocations.size(); j++) { if (userslocations.get(j).getName().equals(user1)) { x1 = (userslocations.get(j).getA() - xmin) / (xmax - xmin) * 300 + 6; y1 = (userslocations.get(j).getB() - ymin) / (ymax - ymin) * 300 + 6; } else if (userslocations.get(j).getName().equals(user2)) { x2 = (userslocations.get(j).getA() - xmin) / (xmax - xmin) * 300 + 6; y2 = (userslocations.get(j).getB() - ymin) / (ymax - ymin) * 300 + 6; } } gc.strokeLine(x1, y1, x2, y2); gc.fillOval(x1 - 2, y1 - 2, 4, 4); gc.fillOval(x2 - 2, y2 - 2, 4, 4); } }
From source file:it.greenvulcano.gvesb.social.twitter.directcall.TwitterOperationSearch.java
License:Open Source License
@Override public void execute(SocialAdapterAccount account) throws SocialAdapterException { try {//from w w w .j a v a 2 s.c o m Twitter twitter = (Twitter) account.getProxyObject(); Query q = new Query(); if ((query != null) && !"".equals(query)) { q.setQuery(query); } if ((sinceId != null) && !"".equals(sinceId)) { q.setSinceId(Long.parseLong(sinceId)); } if ((maxId != null) && !"".equals(maxId)) { q.setMaxId(Long.parseLong(maxId)); } if ((since != null) && !"".equals(since)) { q.setSince(since); } if ((until != null) && !"".equals(until)) { q.setUntil(until); } if ((count != null) && !"".equals(count)) { q.setCount(Integer.parseInt(count)); } XMLUtils parser = null; try { parser = XMLUtils.getParserInstance(); doc = parser.newDocument("TwitterQuery"); Element root = doc.getDocumentElement(); parser.setAttribute(root, "user", twitter.getScreenName()); parser.setAttribute(root, "userId", String.valueOf(twitter.getId())); parser.setAttribute(root, "createdAt", DateUtils.nowToString(DateUtils.FORMAT_ISO_DATETIME_UTC)); QueryResult result; do { result = twitter.search(q); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { dumpTweet(parser, root, tweet); } } while ((q = result.nextQuery()) != null); } catch (Exception exc) { logger.error("Error formatting TwitterOperationSearch query[" + query + "], sinceId[" + sinceId + "], maxId[" + maxId + "], since[" + since + "], until[" + until + "] and count[" + count + "] response.", exc); throw new SocialAdapterException("Error formatting TwitterOperationSearch query[" + query + "], sinceId[" + sinceId + "], maxId[" + maxId + "], since[" + since + "], until[" + until + "] and count[" + count + "] response.", exc); } finally { XMLUtils.releaseParserInstance(parser); } } catch (NumberFormatException exc) { logger.error("Call to TwitterOperationSearch failed. Check query[" + query + "], sinceId[" + sinceId + "], maxId[" + maxId + "], since[" + since + "], until[" + until + "] and count[" + count + "] format.", exc); throw new SocialAdapterException("Call to TwitterOperationSearch failed. Check query[" + query + "], sinceId[" + sinceId + "], maxId[" + maxId + "], since[" + since + "], until[" + until + "] and count[" + count + "] format.", exc); } }
From source file:Jums.SearchTweets.java
License:Apache License
/** * Usage: java twitter4j.examples.search.SearchTweets [query] * * @param args search query//from ww w . ja va 2 s . co m */ public void main(String args) { System.out.println("java twitter4j.examples.search.SearchTweets [query]"); System.exit(-1); Twitter twitter = new TwitterFactory().getInstance(); try { Query query = new Query(args); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } 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:mashup.MashTweetManager.java
public static ArrayList<String> getTweets(String topic) throws IOException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthAccessToken(Common.AccessToken) .setOAuthAccessTokenSecret(Common.AccessTokenSecret).setOAuthConsumerKey(Common.ConsumerKey) .setOAuthConsumerSecret(Common.ConsumerSecret); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); //Twitter twitter = new TwitterFactory().getInstance(); // twitter.setOAuthAccessToken(null); ArrayList<String> tweetList = new ArrayList<>(); try {/* ww w . j a v a2s .c om*/ Query query = new Query(topic.toLowerCase().trim()); query.setCount(100); query.setLocale("en"); query.setLang("en"); QueryResult result = null; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { String data = tweet.getText().replaceAll("[^\\p{L}\\p{Z}]", ""); HinghlishStopWords.removeStopWords(data.trim()); // Remove Special... Characters // Remove stop words tweetList.add(tweet.getText().replaceAll("[^\\p{L}\\p{Z}]", "")); } } while ((query = result.nextQuery()) != null); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); } return tweetList; }
From source file:mitwitter.MiTwitter.java
/** * @param args the command line arguments *//*from w w w. jav a 2 s. c o m*/ public static void main(String[] args) throws TwitterException { // TODO code application logic here //camobios Twitter twitter = new TwitterFactory().getInstance(); //CODIGO CAMBIAR ESTADO Status miStatus = twitter.updateStatus("Tercer ejemplo");//cambia el estado de twitter System.out.println(miStatus.getText()); //CODIGO TIMELINE List<Status> statuses = twitter.getHomeTimeline(); System.out.println("Showing home timeline.");//aparecen los ultimos twitts for (Status status : statuses) { System.out.println(status.getUser().getName() + ":" + status.getText()); } //CODIGO BUSCAR TAGS Query query = new Query("Chelsea"); //Dentro del String va el tag que quieres buscar QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); } }
From source file:moderation.Moderate.java
public List getTwitterpost() { List posts = new ArrayList(); try {/*from w w w . ja v a2 s .c om*/ List savedpost = getSavedList(album_id); String tagname = this.hash; Twitter twitter = setting.TwitterToken.twitterObject(); Query query = new Query(tagname); query.setCount(50); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("\n\n\n" + tweet); PostModel post = new PostModel(); post.setAlbum_id(this.album_id); if (savedpost.contains(tweet.getId())) post.setStatus("old"); else post.setStatus("new"); post.setPost_id("" + tweet.getId()); post.setSender_name(URLEncoder.encode(tweet.getUser().getScreenName(), "UTF-8")); post.setCaption_text(URLEncoder.encode(tweet.getText(), "UTF-8")); post.setSender_pic(tweet.getUser().getProfileImageURL()); post.setSender_id("" + tweet.getUser().getId()); for (MediaEntity mediaEntity : tweet.getMediaEntities()) { post.setImage_standard(mediaEntity.getMediaURL()); post.setImage_low(mediaEntity.getMediaURL()); } post.setPost_time(tweet.getCreatedAt().toString()); post.setType("twitter_post"); post.setLink(null); post.setParam("post_id=" + post.getPost_id() + "&album_id=" + post.getAlbum_id() + "&type=" + post.getType() + "&post_time=" + post.getPost_time() + "&link=" + post.getLink() + "&pic_low=" + post.getImage_low() + "&pic_standard=" + post.getImage_standard() + "&post_message=" + post.getCaption_text() + "&sender_name=" + post.getSender_name() + "&sender_id=" + post.getSender_id() + "&sender_pic=" + post.getSender_pic()); posts.add(post); } this.twitternext = result.nextQuery(); } catch (Exception e) { System.err.println("Exception occure in getTwitter " + e); } return posts; }
From source file:nl.b3p.viewer.stripes.TwitterActionBean.java
License:Open Source License
public Resolution create() throws JSONException { JSONObject json = new JSONObject(); json.put("success", Boolean.FALSE); String error = null;/*from w w w. ja v a 2s. c om*/ try { // The factory instance is re-useable and thread safe. Twitter twitter = new TwitterFactory().getInstance(); Query query = new Query(term); if (latestId != null) { Long longVal = Long.valueOf(latestId); query.setSinceId(longVal); } QueryResult result = twitter.search(query); JSONArray tweets = new JSONArray(); for (Status tweet : result.getTweets()) { //System.out.println(tweet.getFromUser() + ":" + tweet.getText()); JSONObject t = new JSONObject(); t.put("id_str", String.valueOf(tweet.getId())); t.put("text", tweet.getText()); t.put("user_from", tweet.getUser().getScreenName()); t.put("img_url", tweet.getUser().getProfileImageURL()); JSONObject geo = new JSONObject(); if (tweet.getGeoLocation() != null) { geo.put("lat", tweet.getGeoLocation().getLatitude()); geo.put("lon", tweet.getGeoLocation().getLongitude()); } t.put("geo", geo); tweets.put(t); } json.put("tweets", tweets); if (tweets.length() > 0) { json.put("maxId", String.valueOf(result.getMaxId())); } else { json.put("maxId", String.valueOf(latestId)); } json.put("success", Boolean.TRUE); } catch (Exception e) { error = e.toString(); if (e.getCause() != null) { error += "; cause: " + e.getCause().toString(); } } if (error != null) { json.put("error", error); } return new StreamingResolution("application/json", new StringReader(json.toString())); }
From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java
/** Contacts the Twitter API and gets any number of tweets corresponding to a certain query. The main * purpose of this function is to avoid the limit of 100 tweets that can be extracted at once. * * @param numberOfTweets the number of tweets to be printed * @param query the query to be searched by the twitter client * @param twitter the twitter client//from w ww .ja v a 2s .c o m * * @return A JSON string containing a Data object with either a list containing the tweets as a payload * (when successful) or a String payload (for errors). */ private Data getTweetsByCount(int numberOfTweets, Query query, Twitter twitter) { ArrayList<Status> tweets = new ArrayList<>(); if (!(numberOfTweets > 0)) { // Default of 15 tweets numberOfTweets = 15; } // Set the last ID to the maximum possible value as a default long lastID = Long.MAX_VALUE; int original; try { while (tweets.size() < numberOfTweets) { // Keep number of original to avoid infinite looping when not getting enough tweets original = tweets.size(); // If there are more than 100 tweets left to be extracted, extract // 100 during the next query, since 100 is the limit to retrieve at once if (numberOfTweets - tweets.size() > 100) query.setCount(100); else query.setCount(numberOfTweets - tweets.size()); // Extract tweets corresponding to the query then add them to the list QueryResult result = twitter.search(query); tweets.addAll(result.getTweets()); // Iterate through the list and get the lastID to know where to start from // if there are more tweets to be extracted for (Status status : tweets) if (status.getId() < lastID) lastID = status.getId(); query.setMaxId(lastID - 1); // Break the loop if the tweet count didn't change. This would prevent an infinite loop when // tweets for the specified query are not available if (tweets.size() == original) break; } } catch (TwitterException te) { // Put the list of tweets in Data format then output as JSon String. // Since we checked earlier for errors, we assume that an error occuring at this point due // to Rate Limits is caused by a too high request. Thus, we output the retrieved tweets and log // the error String errorDataJson = generateError(te.getMessage()); logger.error(errorDataJson); if (te.exceededRateLimitation() && tweets.size() > 0) { Data<ArrayList<Status>> tweetsData = new Data<>(); tweetsData.setDiscriminator(Discriminators.Uri.LIST); tweetsData.setPayload(tweets); return tweetsData; } else { return Serializer.parse(errorDataJson, Data.class); } } // Return a special error message if no tweets are found if (tweets.size() == 0) { String noTweetsMessage = "No tweets found for the following query. " + "Note: Twitter's REST API only retrieves tweets from the past week."; String errorDataJson = generateError(noTweetsMessage); return Serializer.parse(errorDataJson, Data.class); } else { // Put the list of tweets in Data format then output as JSon String. Data<ArrayList<Status>> tweetsData = new Data<>(); tweetsData.setDiscriminator(Discriminators.Uri.LIST); tweetsData.setPayload(tweets); return tweetsData; } }