List of usage examples for twitter4j QueryResult getTweets
List<Status> getTweets();
From source file:StringMatching.GetTweet.java
/** * @param args the command line arguments *///w w w. java2s . co m public static void main(String[] args) throws JSONException, IOException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH") .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK") .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA") .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC") .setHttpProxyHost("cache.itb.ac.id").setHttpProxyPort(8080).setHttpProxyUser("jonathan.benedict") .setHttpProxyPassword("rollingonthefloor"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); JSONObject obj = new JSONObject(); int counterTweet = 0; FileWriter file = new FileWriter("C:\\Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt"); file.flush(); try { Query query = new Query("barca".toLowerCase()); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { counterTweet++; System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); obj.put("user", tweet.getUser().getScreenName()); obj.put("tweets", tweet.getText()); //Tulis file ke dalam txt try { file.write(obj.toString()); System.out.println("Successfully Copied JSON Object to File..."); System.out.println("\nJSON Object: " + obj); } catch (IOException e) { e.printStackTrace(); } } } while (counterTweet < 1000); file.close(); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } System.exit(0); }
From source file:summarizer.NewApplication.java
private void HashtagSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HashtagSearchButtonActionPerformed // TODO add your handling code here: ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("uEeExq1FHARMvAGTJAY0dGxPh") .setOAuthConsumerSecret("jMcofTKFsayd4bpA6HFNlgkMfiveoS3ffRSCy9FCSs9pWYqdAD") .setOAuthAccessToken("2443437752-PrbVsDrQCxthX3T7lV3dtHs3FCXFXfBBHsdNrOS") .setOAuthAccessTokenSecret("MbauBu7R6vUUKqFD9ogK7VTIfce4nmvewYsgYqBOQ2ZbC"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance();//from w w w.j av a 2 s.co m String hashtag; hashtag = HashtagTextField.getText(); Query query = new Query(hashtag); query.count(100); if (TwitterComboBox.getSelectedIndex() == 0) { query.resultType(Query.ResultType.mixed); } else if (TwitterComboBox.getSelectedIndex() == 0) { query.resultType(Query.ResultType.recent); } else { query.resultType(Query.ResultType.popular); } QueryResult result = null; try { result = twitter.search(query); } catch (TwitterException ex) { Logger.getLogger(NewApplication.class.getName()).log(Level.SEVERE, null, ex); } String alltweets = "", temp = ""; for (Status status : result.getTweets()) { temp = status.getText(); temp = temp.replaceAll("[\\t\\n\\r]", " "); if (!"".equals(temp)) { if ("RT".equals(temp.substring(0, 2))) { temp = temp.split(":", 2)[1]; } alltweets += (temp + "\n"); } } InputTextArea.setText(alltweets); }
From source file:t.twitter.TTwitterModule.java
License:Open Source License
@Kroll.method public void connect(HashMap args) { KrollDict arg = new KrollDict(args); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(arg.optString("apikey", "")) .setOAuthConsumerSecret(arg.optString("apisecret", "")) .setOAuthAccessToken(arg.optString("accesstoken", "")) .setOAuthAccessTokenSecret(arg.optString("accesssecret", "")); AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build()); twitter = tf.getInstance();/*from www.j a v a 2 s . c o m*/ twitter.addListener(new TwitterAdapter() { @Override public void updatedStatus(Status status) { Log.d("Twitter", "text: " + status.getText()); } @Override public void searched(QueryResult result) { HashMap<String, KrollDict[]> event = new HashMap<String, KrollDict[]>(); List<Status> tweets = result.getTweets(); KrollDict[] dList = new KrollDict[tweets.size()]; // sort tweets Collections.sort(tweets, new Comparator<Status>() { public int compare(Status o1, Status o2) { if (desc) { if (o2.getId() < o1.getId()) { return 1; } else { return -1; } } else { if (o2.getId() > o1.getId()) { return 1; } else { return -1; } } } }); // return tweets to titanium int i = 0; for (Status tweet : tweets) { if (lastID == -1 || lastID < tweet.getId()) { KrollDict d = new KrollDict(); d.put("username", tweet.getUser().getScreenName()); d.put("userimage", tweet.getUser().getProfileImageURL()); d.put("text", tweet.getText()); d.put("date", tweet.getCreatedAt()); d.put("id", Long.toString(tweet.getId())); dList[i] = d; lastID = tweet.getId(); i++; } } KrollDict[] dList2 = new KrollDict[i]; // shorten array System.arraycopy(dList, 0, dList2, 0, i); event.put("tweets", dList2); success.call(getKrollObject(), event); synchronized (LOCK) { LOCK.notify(); } } @Override public void verifiedCredentials(User user) { HashMap<String, KrollDict> event = new HashMap<String, KrollDict>(); KrollDict d = new KrollDict(); d.put("user_name", user.getName()); d.put("screen_name", user.getScreenName()); d.put("image_path", user.getProfileImageURL()); event.put("user_info", d); success.call(getKrollObject(), event); synchronized (LOCK) { LOCK.notify(); } } @Override public void onException(TwitterException e, TwitterMethod method) { synchronized (LOCK) { LOCK.notify(); } Log.e("twitter", "error: " + e.getErrorMessage()); } }); Log.d("Twitter", "connected"); }
From source file:teambootje.TwitterAPI.java
public static void timeline() throws TwitterException, SQLException { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query("ssrotterdam"); query.setCount(100);//from w ww. j a v a 2s.c o m /** ** setSince kan alleen tot 7 dagen terug worden gebruikt*** */ QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { if (status.getPlace() != null) { cityVar = status.getPlace().getName(); countryVar = status.getPlace().getCountry(); } else { countryVar = null; cityVar = null; } java.util.Date utilDate = status.getCreatedAt(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); date = sqlDate; post = status.getText(); screenName = status.getUser().getScreenName(); try { ImportIntoSQL.TwitterImport(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:timeline.CmdSearchTerm.java
License:Apache License
public static void main(String[] args) throws ClassNotFoundException, SQLException, JSONException, IOException { // Check how many arguments were passed in if ((args == null) || (args.length != 6)) { System.err.println("Please provide command as following."); System.err.println("java -cp twitter4j-multi-oauth-0.5.jar " + "timeline.CmdSearchTerm consumer_key consumer_secret" + " user_token user_secret output_path " + "term "); System.exit(-1);/* ww w .j ava 2 s . c om*/ } AppOAuth AppOAuths = new AppOAuth(); String endpoint = "/search/tweets"; String consumer_key = null; try { consumer_key = StringEscapeUtils.escapeJava(args[0]); } catch (Exception e) { System.err.println("Argument" + args[0] + " must be an String."); System.exit(-1); } String consumer_secret = null; try { consumer_secret = StringEscapeUtils.escapeJava(args[1]); } catch (Exception e) { System.err.println("Argument" + args[1] + " must be an String."); System.exit(-1); } String user_token = null; try { user_token = StringEscapeUtils.escapeJava(args[2]); } catch (Exception e) { System.err.println("Argument" + args[2] + " must be an String."); System.exit(-1); } String user_secret = null; try { user_secret = StringEscapeUtils.escapeJava(args[3]); } catch (Exception e) { System.err.println("Argument" + args[3] + " must be an String."); System.exit(-1); } String OutputDirPath = null; try { OutputDirPath = StringEscapeUtils.escapeJava(args[4]); } catch (Exception e) { System.err.println("Argument" + args[4] + " must be an String."); System.exit(-1); } String term = ""; try { term = StringEscapeUtils.escapeJava(args[5]); } catch (Exception e) { System.err.println("Argument" + args[5] + " must be an String."); System.exit(-1); } try { TwitterFactory tf = AppOAuths.loadOAuthUser(endpoint, consumer_key, consumer_secret, user_token, user_secret); Twitter twitter = tf.getInstance(); int RemainingCalls = AppOAuths.RemainingCalls - 2; int RemainingCallsCounter = 0; System.out.println("Remianing Calls: " + RemainingCalls); // screen_name / user_id provided by arguments System.out.println("Trying to create output directory"); String filesPath = OutputDirPath + "/"; File theDir = new File(filesPath); // If the directory does not exist, create it if (!theDir.exists()) { try { theDir.mkdirs(); } catch (SecurityException se) { System.err.println("Could not create output " + "directory: " + OutputDirPath); System.err.println(se.getMessage()); System.exit(-1); } } String fileName = filesPath + term.replace(" ", ""); PrintWriter writer = new PrintWriter(fileName, "UTF-8"); Query query = new Query(term); QueryResult result; List<Status> statuses = new ArrayList<>(); int totalTweets = 0; int numberOfTweetsToGet = 5000; long lastID = Long.MAX_VALUE; while (totalTweets < numberOfTweetsToGet) { if (numberOfTweetsToGet - totalTweets > 100) { query.setCount(100); } else { query.setCount(numberOfTweetsToGet - totalTweets); } try { result = twitter.search(query); statuses.addAll(result.getTweets()); if (statuses.size() > 0) { for (Status status : statuses) { String rawJSON = TwitterObjectFactory.getRawJSON(status); writer.println(rawJSON); totalTweets += 1; if (status.getId() < lastID) { lastID = status.getId(); } } } else { break; } System.out.println("totalTweets: " + totalTweets); statuses.clear(); } catch (TwitterException e) { // e.printStackTrace(); System.out.println("Tweets Get Exception: " + e.getMessage()); // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { System.out.println("No more remianing calls"); } if (totalTweets < 1) { writer.close(); // Remove file if tweets not found File fileToDelete = new File(fileName); fileToDelete.delete(); break; } } query.setMaxId(lastID - 1); // If rate limit reached then switch Auth user RemainingCallsCounter++; if (RemainingCallsCounter >= RemainingCalls) { System.out.println("No more remianing calls"); break; } } if (totalTweets > 0) { System.out.println("Total dumped tweets of " + term + " are: " + totalTweets); } else { // Remove file if tweets not found File fileToDelete = new File(fileName); fileToDelete.delete(); } writer.close(); } catch (TwitterException te) { // te.printStackTrace(); System.out.println("Failed to get term results because: " + te.getMessage()); System.exit(-1); } System.out.println("!!!! DONE !!!!"); }
From source file:tiofortwitter.TioForTwitter.java
/** * @param args the command line arguments *///from ww w . ja v a 2 s .c om public static void main(String[] args) throws JSONException, IOException { ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH") .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK") .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA") .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); JSONObject obj = new JSONObject(); int counterTweet = 0; FileWriter file = new FileWriter("Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt"); file.flush(); try { Query query = new Query("Satria"); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { counterTweet++; System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); obj.put("user", tweet.getUser().getScreenName()); obj.put("tweets", tweet.getText()); //Tulis file ke dalam txt try { file.write(obj.toString()); System.out.println("Successfully Copied JSON Object to File..."); System.out.println("\nJSON Object: " + obj); } catch (IOException e) { e.printStackTrace(); } } } while (counterTweet < 1000); file.close(); System.exit(0); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } System.exit(0); }
From source file:tweekan.kotikan.com.tweekan.twitter.BasicTwitterClient.java
License:Open Source License
@Override public void tweetsForQuery(final String query, final Twitter.Callback callback) { new AsyncTask<String, Void, QueryResult>() { @Override/* w w w . ja va 2 s .c o m*/ protected QueryResult doInBackground(String... params) { QueryResult result = null; try { result = instance.search().search(new Query(params[0])); } catch (TwitterException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(QueryResult queryResult) { final Twitter.ServerResponse response = queryResult != null ? Twitter.ServerResponse.SUCCESS : Twitter.ServerResponse.FAILURE; final ArrayList<String> results = new ArrayList<String>(); if (queryResult != null) { for (twitter4j.Status tweet : queryResult.getTweets()) { String name = tweet.getUser().getName(); String tweetText = tweet.getText(); results.add(String.format("user : %s" + "\nmsg : %s", name, tweetText)); } } callback.onRequestComplete(new Twitter.Result() { @Override public Twitter.ServerResponse response() { return response; } @Override public List<String> tweets() { return results; } }); } }.execute(query); }
From source file:tweet.Miner.java
License:Apache License
/** * Usage: java twitter4j.examples.search.SearchTweets [query] * * @param toSearch //from w ww . jav a2 s. co m */ public List<Status> mine(String toSearch) { List<Status> results = new ArrayList<Status>(); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET) .setOAuthAccessToken(OAUTH_ACCESS_TOKEN).setOAuthAccessTokenSecret(OAUTH_ACCESS_TOKEN_SECRET); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Query query = new Query(toSearch); query.setCount(100); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); results.addAll(result.getTweets()); for (Status tweet : tweets) { System.out.println( tweet.getId() + " @ " + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); } catch (Exception e) { e.printStackTrace(); } return results; }
From source file:tweetcrawling.TweetCrawler.java
public void getTweets(TwitterConfiguration tc_) throws IOException, InterruptedException { try {/*from w w w .j ava 2s . c o m*/ for (String query_ : Queries) { // Ngambil tweet dari tiap page lalu disimpan di Statuses int maxTweetCrawled = 3240; // This is the number of the latest tweets that we can crawl, specified by Twitter Query query = new Query(query_); query.setLang("id"); QueryResult result; do { rateLimitHandler(tc_, "/search/tweets"); // Check rate limit first //System.out.println("kanya sini"); result = tc_.getTwitter().search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { ArrayList<String> ValToWrite = getValueToWrite(tweet); writeValue(ValToWrite, OutputFile); System.out.println( "@" + tweet.getUser().getScreenName() + " - " + tweet.getText().replace("\n", " ")); } addStatuses(tweets); } while ((query = result.nextQuery()) != null); //printTweets(OutputFile); // Printing out crawling result per page of this keywords //emptyStatuses(); // Empty out the current attribute Statuses so that it can be used for other keywords } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); if (te.exceededRateLimitation()) { System.out.println("Rate limit status: " + te.getRateLimitStatus()); } System.exit(-1); } }
From source file:tweetdownloader.cnr_stable.version.TweetDownload.java
/** * this method return an ArrayList of dataOfTweets * @param allMyTweets// w w w. j a v a 2s . c o m * @return allMyTweet */ public ArrayList<dataOfTweet> downloadMyTweet(ArrayList<dataOfTweet> allMyTweets) { { try { Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets"); for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) { dataOfTweet tweet = new dataOfTweet(); //System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber); if (searchTweetsRateLimit.getRemaining() == 0) { try { //System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset()); Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l); } catch (InterruptedException ex) { java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex); } } Query q = new Query(SEARCH_TERM); q.setCount(TWEETS_PER_QUERY); q.setLang("it"); if (maxID != -1) { q.setMaxId(maxID - 1); } QueryResult r = twitter.search(q); if (r.getTweets().isEmpty()) { break; } for (Status s : r.getTweets()) { totalTweets++; if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } if (s.isRetweeted() == false) { tweet.setUsername(s.getUser().getScreenName()); tweet.setCreatedAt(s.getCreatedAt().toString()); tweet.setTweetText(s.getText()); if (s.getGeoLocation() != null) { tweet.setLat(s.getGeoLocation().getLatitude()); tweet.setLongi(s.getGeoLocation().getLongitude()); } } } allMyTweets.add(tweet); } } catch (TwitterException ex) { java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex); } } return allMyTweets; }