List of usage examples for twitter4j Twitter search
QueryResult search(Query query) throws TwitterException;
From source file:twitterapidemo.TwitterAPIDemo.java
License:Apache License
public static void main(String[] args) throws IOException, TwitterException { //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo(); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(consumerKey); builder.setOAuthConsumerSecret(consumerSecret); Configuration configuration = builder.build(); TwitterFactory twitterFactory = new TwitterFactory(configuration); Twitter twitter = twitterFactory.getInstance(); twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); Scanner sc = new Scanner(System.in); System.out.println(// w w w .ja v a 2 s .c om "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic"); int choice = sc.nextInt(); switch (choice) { case 1: System.out.println("What's happening: "); String post = sc.next(); StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI"); Status status = twitter.updateStatus(statusUpdate); System.out.println("status.toString() = " + status.toString()); System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName()); System.out.println("status.getSource() = " + status.getSource()); System.out.println("status.getText() = " + status.getText()); System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors())); System.out.println("status.getCreatedAt() = " + status.getCreatedAt()); System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId()); System.out.println("status.getGeoLocation() = " + status.getGeoLocation()); System.out.println("status.getId() = " + status.getId()); System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId()); System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId()); System.out.println("status.getPlace() = " + status.getPlace()); System.out.println("status.getRetweetCount() = " + status.getRetweetCount()); System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus()); System.out.println("status.getUser() = " + status.getUser()); System.out.println("status.getAccessLevel() = " + status.getAccessLevel()); System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities())); System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities())); if (status.getRateLimitStatus() != null) { System.out.println( "status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit()); System.out.println("status.getRateLimitStatus().getRemaining() = " + status.getRateLimitStatus().getRemaining()); System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = " + status.getRateLimitStatus().getResetTimeInSeconds()); System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = " + status.getRateLimitStatus().getSecondsUntilReset()); } System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities())); System.out.println( "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities())); break; case 2: System.out.println("Enter keyword"); String keyword = sc.next(); try { Query query = new Query(keyword); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); } } while ((query = result.nextQuery()) != null); System.exit(0); } catch (TwitterException te) { System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); break; } case 3: //WOEID for India = 23424848 Trends trends = twitter.getPlaceTrends(23424848); int count = 0; for (Trend trend : trends.getTrends()) { if (count < 3) { Query query = new Query(trend.getName()); QueryResult result; int numberofpost = 0; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { numberofpost++; } } while ((query = result.nextQuery()) != null); System.out .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost); count++; } else break; } break; default: System.out.println("Invalid input"); } }
From source file:twitterrest.GeoSearch.java
License:Apache License
public static void main(String[] args) throws TwitterException { // ?//from ww w . j a va 2s .c o m Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN) .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build(); Twitter twitter = new TwitterFactory(configuration).getInstance(); Query query = new Query(); // ?????10kmIP?????? GeoLocation geo = new GeoLocation(35.69384, 139.703549); query.setGeoCode(geo, 10.0, Query.KILOMETERS); // QueryResult result = twitter.search(query); // ???Tweet??placegeoLocation?????? for (Status tweet : result.getTweets()) { System.out.println(tweet.getText()); System.out.println(tweet.getPlace() + " : " + tweet.getGeoLocation()); } }
From source file:twitterrest.SearchTweet.java
License:Apache License
public static void main(String[] args) throws TwitterException { //?//w w w . j a v a 2s . co m Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN) .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build(); Twitter twitter = new TwitterFactory(configuration).getInstance(); Query query = new Query(); try { File file = new File("./file/tweets.txt"); PrintWriter pw; //??? pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true))); // ??? query.setQuery("?"); query.setLang("ja"); // 1????Tweet?100? query.setCount(100); //????????? //query.setSince("2013-06-13"); //query.setUntil("2013-06-17"); // 150015 for (int i = 1; i <= 15; i++) { // QueryResult result = twitter.search(query); System.out.println(": " + result.getTweets().size()); System.out.println(" : " + new Integer(i).toString()); // ??? for (Status tweet : result.getTweets()) { // String str = tweet.getText(); System.out.println(str); // System.out.println(tweet.getUser()); // System.out.println(tweet.getCreatedAt()); // ??URL? StringTokenizer sta = new StringTokenizer(str, " "); //? while (sta.hasMoreTokens()) { String wk = sta.nextToken(); if (wk.indexOf("#") == -1 && wk.indexOf("http") == -1 && wk.indexOf("RT") == -1 && wk.indexOf("@") == -1) { pw.println(wk); } } String u = tweet.getUser().getName(); pw.println(u); } if (result.hasNext()) { query = result.nextQuery(); } else { break; } } pw.close(); } catch (IOException e) { e.printStackTrace(); } }
From source file:twitterrest.UserSearch.java
License:Apache License
public static void main(String[] args) throws TwitterException { //?/*from w ww. j a v a 2s . c om*/ Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN) .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build(); Twitter twitter = new TwitterFactory(configuration).getInstance(); Query query = new Query(); // masason?Tweet //query.setQuery("from:anondroid3 OR to:anondroid3"); query.setQuery("from:anondroid3"); // ??? QueryResult result = twitter.search(query); // System.out.println(":" + result.getTweets().size()); // 1????Tweet?100? query.setCount(100); for (Status tweet : result.getTweets()) { System.out.println("tweet:" + tweet.getText());// System.out.println("UserID:" + tweet.getUser().getId());//ID System.out.println("Application:" + tweet.getSource());// System.out.println("Created Date:" + tweet.getCreatedAt());//? System.out.println("GeoLocation:" + tweet.getGeoLocation());// } }
From source file:twittersentimentanalysis.TwitterSentimentAnalysis.java
private static ArrayList<Tweet> getAllTweets(Twitter twitter) { logger.info("getAllTweets"); List<Status> listTweets = null; ArrayList<Tweet> listOfTweets = new ArrayList<Tweet>(); try {//w ww. j av a 2 s . c o m Trends trends = twitter.getPlaceTrends(23424977); // System.out.println(trends.getLocation()); Trend trend[] = trends.getTrends(); logger.info("Number of Trends : " + trend.length); for (Trend trendTemp : trend) { //System.out.println("Name = " + trendTemp.getName()); //System.out.println("***************"); Query query = new Query(trendTemp.getQuery()); query.setCount(100); QueryResult queryResult = twitter.search(query); listTweets = queryResult.getTweets(); StanfordCoreNLPTool.init(); for (Status status : listTweets) { //System.out.println(status.getText()); Tweet tweet = getTweetObject(status); if (tweet != null) { tweet.setTrend(trendTemp.getName()); listOfTweets.add(tweet); } } } } catch (TwitterException ex) { Logger.getLogger(TwitterSentimentAnalysis.class.getName()).log(Level.SEVERE, null, ex); logger.info(ex.getMessage()); } return listOfTweets; }
From source file:twittertestingagain.TwitterTesting.java
/** * @param args the command line arguments * @throws twitter4j.TwitterException/* w ww . j av a 2 s .c o m*/ * @throws java.io.IOException */ public static void main(String[] args) throws TwitterException, IOException { /* ---------------------------Setting up twitter account authentication-------------------------------*/ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("YjICBJeNlnxAf3tFw7awLaCzS") .setOAuthConsumerSecret("8IfPzkr4opePnhCLLloKMP6X44IeNav0fLDrmtBrPbaHoxd1nO") .setOAuthAccessToken("4146680697-oOEPVezvvZ82vB7iP9HSbkoTG9ze9gH69XLrSCP") .setOAuthAccessTokenSecret("HZjsaabmVjeSkSX6vvVFdT3GWZek8xJ9RKfwaR57RDyEG"); /* ---------------------------------File Writing Variables------------------------------------------------*/ File outfile = new File("output.txt"); FileWriter fwriter = new FileWriter(outfile); try (PrintWriter pWriter = new PrintWriter(fwriter)) { /*----------------------------------Search Parameters-------------------------------------*/ String search = "chinese food"; String lang = "en"; /*------------------------End Search Parameters----------------------------------------*/ int numTweets = 0; long maxID = -1; TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); try { Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search"); //System.out.println(rateLimitStatus); RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets"); /*System.out.printf("You have %d calls remaining out of %d, Limit resets in %d seconds\n", searchTweetsRateLimit.getRemaining(), searchTweetsRateLimit.getLimit(), searchTweetsRateLimit.getSecondsUntilReset()); */ for (int queryNumber = 0; queryNumber < maxQueries; queryNumber++) { System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber); pWriter.println("\n\n!!! Starting iteration #" + queryNumber + "\n\n"); if (searchTweetsRateLimit.getRemaining() == 0) { System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset()); Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l); } //here is where we can send an object to the query Query query = new Query(search); query.setCount(tweetsPerQuery); query.resultType(Query.ResultType.recent); query.setLang(lang); if (maxID != -1) { query.setMaxId(maxID - 1); } QueryResult result = twitter.search(query); if (result.getTweets().size() == 0) { break; } for (Status s : result.getTweets()) { numTweets++; if (maxID == -1 || s.getId() < maxID) { maxID = s.getId(); } System.out.printf("On %s, @%-20s said: %s\n", s.getCreatedAt().toString(), s.getUser().getScreenName(), cleanText(s.getText())); pWriter.println("On " + s.getCreatedAt().toString() + " @" + s.getUser().getScreenName() + " " + cleanText(s.getText())); } searchTweetsRateLimit = result.getRateLimitStatus(); } } catch (Exception e) { System.out.println("Broken"); e.printStackTrace(); } System.out.printf("\n\nA total of %d tweets retrieved\n", numTweets); pWriter.println("\n\nA total of " + numTweets + " tweets retrieved\n\n"); pWriter.close(); /*while (result.hasNext()){ numTweets += result.getCount(); System.out.println(numTweets); for (Status status : result.getTweets()) { System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); } result.nextQuery(); } /* QueryForm qf = new QueryForm(); qf.show(); */ } }
From source file:twittervis.TwitterVis.java
public void retrieveTweets(String keyword, boolean topic) { Twitter twitter = tf.getInstance(); Query query = new Query(keyword); // The query parameter ("keyword") can be modified to make more // specific search queries based on language, users, time, etc. //Query query = new Query(keyword +" AND lang:en AND until:2016-12-01"); //number of tweets needed for each topic. query.count(240);// w ww. j a v a 2s .c om // Assign the tweets to the corresponding Emotion Node if (topic == true) { JoyNode = "Joy1"; SadnessNode = "Sadness1"; AngerNode = "Anger1"; DisgustNode = "Disgust1"; FearNode = "xFear1"; } else { JoyNode = "Joy2"; SadnessNode = "Sadness2"; AngerNode = "Anger2"; DisgustNode = "Disgust2"; FearNode = "xFear2"; } //Try making the query request. try { QueryResult result = twitter.search(query); // Process the analysis results and create new edges and nodes accordingly result.getTweets().forEach((status) -> { status.getText(); //get the textual info from a tweet // String userName = status.getUser().getScreenName(); String TwtText = status.getText(); System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText()); String twtEmotion = getTweetEmotion(TwtText); // A switch to assign the tweet to the correct node switch (twtEmotion) { case "Joy": System.out.println("Joy (*^__^*)"); graph.addEdge(TwtText, JoyNode, TwtText); break; case "Sadness": System.out.println("Sad (*T_T*)"); graph.addEdge(TwtText, SadnessNode, TwtText); break; case "Anger": System.out.println("Anger ()"); graph.addEdge(TwtText, AngerNode, TwtText); break; case "Fear": System.out.println("Fear ?|||"); graph.addEdge(TwtText, FearNode, TwtText); break; case "Disgust": System.out.println("Disgust (*~)"); graph.addEdge(TwtText, DisgustNode, TwtText); break; } }); } catch (TwitterException ex) { //fallback if exceptions occur System.out.println("Couldn't connect: " + ex); } }
From source file:uk.ac.essex.wonderland.modules.twitter.client.TwitterPanel.java
License:Open Source License
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchButtonActionPerformed if (DEBUG) {//from ww w . ja v a 2 s.c o m String queryString = queryField.getText().trim(); if (queryString.isEmpty()) { return; } Query query = new Query(queryString); query.setLang("en"); Twitter twitter = new TwitterFactory().getInstance(); try { QueryResult result = twitter.search(query); String warning = result.getWarning(); if (warning != null) { System.err.println(warning); } @SuppressWarnings("unchecked") List<Tweet> tweets = result.getTweets(); for (Tweet tweet : tweets) { addTweet(tweet); } } catch (TwitterException ex) { Logger.getLogger(TwitterPanel.class.getName()).log(Level.SEVERE, null, ex); } } else { String query = queryField.getText().trim(); if (!query.isEmpty()) { cell.performQuery(query); } } }
From source file:uta.ak.CollectTweets.java
public void collectTweetsByFileList(String sinceDate, String untilDate, String tag) { try {/*from w w w .j a v a 2 s. c om*/ // The factory instance is re-useable and thread safe. System.out.println("Start to collect tweets from :"); Set<String> mediaList = new HashSet<String>(); Resource res = new ClassPathResource("new-social-meida-list.txt"); // File stopwords=res.getFile(); // File stopwords=new File("/Users/zhangcong/dev/corpus/StopWordTable2.txt"); InputStreamReader isr = new InputStreamReader(res.getInputStream()); // File medias=new File(path); // BufferedReader mdsreader = new BufferedReader(new FileReader(medias)); BufferedReader mdsreader = new BufferedReader(isr); String tempString = mdsreader.readLine(); while ((tempString = mdsreader.readLine()) != null) { System.out.println(tempString.toLowerCase()); mediaList.add(tempString.toLowerCase()); } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("LuhVZOucqdHX6x0lcVgJO6QK3") .setOAuthConsumerSecret("6S7zbGLvHMXDMgRXq7jRIA6QmMpdI8i5IJNpnjlB55vpHpFMpj") .setOAuthAccessToken("861637891-kLunD37VRY8ipAK3TVOA0YKOKxeidliTqMtNb7wf") .setOAuthAccessTokenSecret("vcKDxs6qHnEE8fhIJr5ktDcTbPGql5o3cNtZuztZwPYl4"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); /* Connection con = null; //MYSQL Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL System.out.println("connection yes"); String insertSQL="INSERT INTO c_rawtext(mme_lastupdate, mme_updater, title, text, tag, text_createdate) " + "VALUES (NOW(), \"AK\", ?, ?, ?, ?)"; PreparedStatement insertPS = con.prepareStatement(insertSQL); */ //?usttmp?? String restUrl = "http://192.168.0.103:8991/usttmp_textreceiver/rest/addText"; Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); for (String mediastr : mediaList) { Query query = new Query("from:" + mediastr); query.setSince(sinceDate); query.setUntil(untilDate); query.setCount(100); query.setLang("en"); QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { System.out.println("@" + status.getUser().getScreenName() + " | " + status.getCreatedAt().toString() + ":" + status.getText()); System.out.println("Inserting the record into the table..."); String formattedDate = format1.format(status.getCreatedAt()); /* insertPS.setString (1, status.getUser().getScreenName()); insertPS.setString (2, status.getText()); insertPS.setString (3, tag); insertPS.setString (4, formattedDate); insertPS.addBatch();*/ // if(null!=status.getText()){ // break; // } String interfaceMsg = "<message> " + " <title> " + ((null != status.getUser().getScreenName()) ? status.getUser().getScreenName() : "NO TITLE") + " </title> " + " <text> " + StringEscapeUtils.escapeXml10(status.getText()) + " </text> " + " <textCreatetime> " + formattedDate + " </textCreatetime> " + " <tag> " + tag + " </tag> " + "</message>"; // String restUrl="http://127.0.0.1:8991/usttmp_textreceiver/rest/addText"; RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.TEXT_XML); headers.setAccept(Arrays.asList(MediaType.TEXT_XML)); // headers.setContentLength(); HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers); ResponseEntity<String> resresult = restTemplate.exchange(restUrl, HttpMethod.POST, entity, String.class); System.out.println(resresult.getBody()); if (resresult.getBody().contains("<result>failed</result>")) { throw new RuntimeException("response message error"); } } } // System.out.println("Start to insert records..."); // insertPS.clearParameters(); // int[] results = insertPS.executeBatch(); } catch (Exception te) { te.printStackTrace(); System.out.println("Failed: " + te.getMessage()); System.exit(-1); } }
From source file:uta.ak.CollectTweets.java
public void collectTweetsByKeyWords(String keyWords, String sinceDate, String untilDate, String tag) { try {// w ww . ja v a 2 s . c o m ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("LuhVZOucqdHX6x0lcVgJO6QK3") .setOAuthConsumerSecret("6S7zbGLvHMXDMgRXq7jRIA6QmMpdI8i5IJNpnjlB55vpHpFMpj") .setOAuthAccessToken("861637891-kLunD37VRY8ipAK3TVOA0YKOKxeidliTqMtNb7wf") .setOAuthAccessTokenSecret("vcKDxs6qHnEE8fhIJr5ktDcTbPGql5o3cNtZuztZwPYl4"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); Connection con = null; //MYSQL Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL System.out.println("connection yes"); String insertSQL = "INSERT INTO c_rawtext(mme_lastupdate, mme_updater, title, text, tag, text_createdate) VALUES (NOW(), \"AK\", ?, ?, ?, ?)"; PreparedStatement insertPS = con.prepareStatement(insertSQL); Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, 1); SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); Query query = new Query(keyWords); query.setSince(sinceDate); query.setUntil(untilDate); query.setCount(100); query.setLang("en"); QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { // System.out.println("@" + status.getUser().getScreenName() + // " | " + status.getCreatedAt().toString() + // ":" + status.getText()); // System.out.println("Inserting the record into the table..."); String formattedDate = format1.format(status.getCreatedAt()); insertPS.setString(1, status.getUser().getScreenName()); insertPS.setString(2, status.getText()); insertPS.setString(3, tag); insertPS.setString(4, formattedDate); insertPS.addBatch(); } System.out.println("Start to insert records..."); insertPS.clearParameters(); int[] results = insertPS.executeBatch(); } catch (Exception te) { te.printStackTrace(); System.out.println("Failed: " + te.getMessage()); System.exit(-1); } }