List of usage examples for twitter4j Status getCreatedAt
Date getCreatedAt();
From source file:twitterapi.TwitterAPI.java
public static void timeline() throws TwitterException, SQLException { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query("ssrotterdam"); query.setCount(100);// w ww . j a v a2 s .c om /** ** setSince kan alleen tot 7 dagen terug worden gebruikt*** */ QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { String locationCity = null; String locationCountry = null; 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: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(/*from ww w . jav a2 s .co m*/ "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:twitterbot.TwitterActions.java
public void searchTweetandRetweet(String hashtag) { Query query = new Query(hashtag); query.count(40);/*from ww w.j a v a 2 s. co m*/ int check = 0; int alreadyused = 0; int remove = 0; try { QueryResult queryresult = this.twitter.search(query); this.tweets = (ArrayList<Status>) queryresult.getTweets(); Collections.reverse(tweets); for (Status status : tweets) { if (!status.isRetweetedByMe() && status.getCreatedAt().getTime() > this.lastStatusTime) { try { this.retweetTweet(status); this.lastStatusTime = status.getCreatedAt().getTime(); this.writeTimeToFile(); Thread.sleep(10000); } catch (TwitterException tex) { System.out.println("Twitter Exception - Already Retweeted"); } } } } catch (TwitterException ex) { Logger.getLogger(TwitterActions.class.getName()).log(Level.SEVERE, null, ex); } catch (InterruptedException ex) { Logger.getLogger(TwitterActions.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:twitterbot.TwitterActions.java
public void retweetAllTweetsFromTimeline() { try {/*ww w.jav a 2s .c o m*/ this.tweets = (ArrayList<Status>) twitter.getHomeTimeline(); Collections.reverse(tweets); for (Status status : tweets) { if (!status.isRetweetedByMe() && status.getCreatedAt().getTime() > this.lastStatusTime) { this.retweetTweet(status); this.lastStatusTime = status.getCreatedAt().getTime(); this.writeTimeToFile(); try { Thread.sleep(5000); } catch (InterruptedException ex) { Logger.getLogger(TwitterActions.class.getName()).log(Level.SEVERE, null, ex); } } } } catch (TwitterException ex) { Logger.getLogger(TwitterActions.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:TwitterDownload.TwitterExel.java
public static String writeTweets(long ID, List<Status> tweets, String path) { try {//w w w . j a v a2s . c o m path = path + "Tweets"; File theDir = new File(path); // if the directory does not exist, create it if (!theDir.exists()) { theDir.mkdir(); } String exlPath = path + "/" + ID + ".xls"; File exlFile = new File(exlPath); WritableWorkbook writableWorkbook = null; WritableSheet writableSheet = null; int i = 0; while (exlFile.exists()) { i++; exlPath = path + "/" + ID + "_" + i + ".xls"; exlFile = new File(exlPath); } writableWorkbook = Workbook.createWorkbook(exlFile); writableSheet = writableWorkbook.createSheet("FerretData", 0); try { Workbook existing = Workbook.getWorkbook(exlFile); writableWorkbook = Workbook.createWorkbook(exlFile, existing); writableSheet = writableWorkbook.getSheet(0); } catch (BiffException be) { } //Create Cells with contents of different data types. //Also specify the Cell coordinates in the constructor i = 0; i = writableSheet.getRows(); if (i == 0) { Label text = new Label(0, 0, "Tweeted Text"); Label date = new Label(1, 0, "Tweeted Date"); Label reTweets = new Label(2, 0, "ReTweet Count"); Label favor = new Label(3, 0, "Favourite Count"); Label place = new Label(4, 0, "Place"); Label geo = new Label(5, 0, "GeoLocation"); Label link = new Label(6, 0, "Link"); Label user = new Label(7, 0, "User"); //Add the created Cells to the sheet writableSheet.addCell(text); writableSheet.addCell(date); writableSheet.addCell(reTweets); writableSheet.addCell(favor); writableSheet.addCell(place); writableSheet.addCell(geo); writableSheet.addCell(link); writableSheet.addCell(user); i = 1; } for (int j = 0; j < tweets.size(); j++) { Status s = tweets.get(j); String placeString = s.getPlace() != null ? s.getPlace().toString() : ""; if (placeString.contains("{")) placeString = placeString.substring(placeString.indexOf("{"), placeString.length() - 1); Label text = new Label(0, i + j, s.getText()); DateTime date = new DateTime(1, i + j, s.getCreatedAt()); Number reTweets = new Number(2, i + j, s.getRetweetCount()); Number favor = new Number(3, i + j, s.getFavoriteCount()); Label place = new Label(4, j + 1, placeString); Label geo = new Label(5, j + 1, s.getGeoLocation() != null ? s.getGeoLocation().toString() : ""); String link = "https://twitter.com/" + s.getUser().getScreenName() + "/status/" + s.getId(); URL url = new URL(link); WritableHyperlink hl = new WritableHyperlink(6, j + 1, url); Label user = new Label(7, j + 1, s.getUser().getScreenName()); //Add the created Cells to the sheet writableSheet.addCell(text); writableSheet.addCell(date); writableSheet.addCell(reTweets); writableSheet.addCell(favor); writableSheet.addCell(place); writableSheet.addCell(geo); writableSheet.addHyperlink(hl); writableSheet.addCell(user); } //Write and close the workbook writableWorkbook.write(); writableWorkbook.close(); return exlPath; } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } return null; }
From source file:twitteremoji.FXMLDocumentController.java
private void startCrawling(String term) { crawling = true;/*w ww .ja v a2s . co m*/ (new Thread() { public void run() { try { // crawler // just do once for debugging //while(crawling) { Query query = new Query(term); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { //String emoji = cleanTweetLeaveEmoji(tweet.getText()); crawlerTableData.add( new StatusWrapper(DateFormat.getDateTimeInstance().format(tweet.getCreatedAt()), tweet.getUser().getName(), tweet.getText(), "")); } //} } catch (TwitterException ex) { statusLabel.setText(STATUS_PREFIX + STATUS_ERROR); } } }).start(); }
From source file:twittermongodbapp.SaveTweets.java
static public void saveTweets(DB db, twitter4j.Twitter twitter) throws TwitterException { DBCollection collection = db.getCollection("collection2"); DBCollection savedCollection = db.getCollection("savedCollection"); DBCollection ConnectionCollection = db.getCollection(" ConnectionCollection"); BasicDBObject document0 = new BasicDBObject(); savedCollection.remove(document0);//w ww.j a va2s .c om ConnectionCollection.remove(document0); Status savedTweet; //Read Tweets from Database System.out.println("Saved tweets: "); DBCursor cursor = collection.find(); List<String> allUsers = new ArrayList<>(); int count = 1; while (cursor.hasNext()) { DBObject obj = cursor.next(); savedTweet = TwitterObjectFactory.createStatus(obj.toString()); String name = savedTweet.getUser().getScreenName(); String date = savedTweet.getCreatedAt().toString(); boolean exist = false; BasicDBObject document = new BasicDBObject("User", name); BasicDBObject searchDocument = new BasicDBObject("User", name); DBObject theObj = null; if (!allUsers.contains(name)) { allUsers.add(name); } else { exist = true; DBCursor cursor2 = savedCollection.find(searchDocument); if (cursor2.hasNext()) { theObj = cursor2.next(); } } // BasicDBList allHashtags = new BasicDBList(); List<String> allHashtags = new ArrayList<>(); List<String> allsortURLS = new ArrayList<>(); List<String> allcompleteURLS = new ArrayList<>(); //BasicDBList allURLS = new BasicDBList(); List<String> allmentionedUsers = new ArrayList<>(); List<String> allTweets = new ArrayList<>(); if (exist) { allHashtags = (ArrayList) theObj.get("Hashtags"); } HashtagEntity[] hashtagsEntities = savedTweet.getHashtagEntities(); for (HashtagEntity hashtagsEntitie : hashtagsEntities) { if (!allHashtags.contains(hashtagsEntitie.getText())) { allHashtags.add(hashtagsEntitie.getText()); } saveConnection(date, name, new BasicDBObject("hashtag", hashtagsEntitie.getText()), 1, count, ConnectionCollection); count++; } document.append("Hashtags", allHashtags); if (exist) { allsortURLS = (ArrayList) theObj.get("sortUrls"); allcompleteURLS = (ArrayList) theObj.get("completeUrls"); } URLEntity[] urlEntities = savedTweet.getURLEntities(); if (savedTweet.getURLEntities().length > 0) { for (int i = 0; i < savedTweet.getURLEntities().length; i++) { if (urlEntities[i].getStart() < urlEntities[i].getEnd()) { BasicDBObject document1 = new BasicDBObject("url", urlEntities[i].getURL()); String completeURL = urlEntities[i].getExpandedURL(); document1.append("completeURL", completeURL); if (!allsortURLS.contains(document1)) { allsortURLS.add(urlEntities[i].getURL()); allcompleteURLS.add(urlEntities[i].getExpandedURL()); } saveConnection(date, name, document1, 2, count, ConnectionCollection); count++; } } } document.append("sortUrls", allsortURLS); document.append("completeUrls", allsortURLS); if (exist) { allmentionedUsers = (ArrayList) theObj.get("Mentions"); } UserMentionEntity[] mentionEntities = savedTweet.getUserMentionEntities(); for (UserMentionEntity mentionEntitie : mentionEntities) { BasicDBObject document2 = new BasicDBObject("mentioned_user", mentionEntitie.getText()); if (!allmentionedUsers.contains(mentionEntitie.getText())) { allmentionedUsers.add(mentionEntitie.getText()); } saveConnection(date, name, document2, 3, count, ConnectionCollection); count++; } document.append("Mentions", allmentionedUsers); if (exist) { allTweets = (ArrayList) theObj.get("Tweets"); } String tweetText = " "; if (savedTweet.isRetweet()) { tweetText = savedTweet.getRetweetedStatus().getText(); } else { tweetText = savedTweet.getText(); } BasicDBObject document2 = new BasicDBObject("Tweet", tweetText); if (!allTweets.contains(tweetText)) { allTweets.add(tweetText); } saveConnection(date, name, document2, 4, count, ConnectionCollection); count++; document.append("Tweets", allTweets); if (exist) { savedCollection.remove(searchDocument); } savedCollection.insert(document); } JaccardSimilarity js = new JaccardSimilarity(); List<Map<List<String>, List<Float>>> list = new ArrayList<>();//This is the final list you need Map<List<String>, List<Float>> map1 = new HashMap<>();//This is one instance of the map you want to store in the above map List<String> usersNames = new ArrayList<>(); List<Float> usersResults = new ArrayList<>(); BasicDBObject doc1; BasicDBObject doc2; DBCursor cursor1; DBCursor cursor2; DBObject obj1; DBObject obj2; List<String> tl1 = new ArrayList(); List<String> tl2 = new ArrayList(); float countSimilarity = 0; for (int i = 0; i < allUsers.size(); i++) { for (int j = i + 1; j < allUsers.size(); j++) { //System.out.println(i+" "+j); System.out.print(allUsers.get(i) + " " + allUsers.get(j) + " "); usersNames.add(allUsers.get(i)); usersNames.add(allUsers.get(j)); doc1 = new BasicDBObject("User", allUsers.get(i)); doc2 = new BasicDBObject("User", allUsers.get(j)); cursor1 = savedCollection.find(doc1); cursor2 = savedCollection.find(doc2); if (cursor1.hasNext() && cursor2.hasNext()) { obj1 = cursor1.next(); obj2 = cursor2.next(); tl1 = (ArrayList) obj1.get("Hashtags"); tl2 = (ArrayList) obj2.get("Hashtags"); countSimilarity = countSimilarity + js.findSimilarity(tl1, tl2); usersResults.add(js.findSimilarity(tl1, tl2)); System.out.print(js.findSimilarity(tl1, tl2) + " "); tl1 = (ArrayList) obj1.get("Mentions"); tl2 = (ArrayList) obj2.get("Mentions"); countSimilarity = countSimilarity + js.findSimilarity(tl1, tl2); usersResults.add(js.findSimilarity(tl1, tl2)); System.out.print(js.findSimilarity(tl1, tl2) + " "); tl1 = (ArrayList) obj1.get("Tweets"); tl2 = (ArrayList) obj2.get("Tweets"); countSimilarity = countSimilarity + js.findSimilarity(tl1, tl2); usersResults.add(js.findSimilarity(tl1, tl2)); System.out.print(js.findSimilarity(tl1, tl2) + " "); tl1 = (ArrayList) obj1.get("sortUrls"); tl2 = (ArrayList) obj2.get("sortUrls"); countSimilarity = countSimilarity + js.findSimilarity(tl1, tl2); usersResults.add(js.findSimilarity(tl1, tl2)); System.out.print(js.findSimilarity(tl1, tl2) + " "); usersResults.add((float) (countSimilarity / 4)); System.out.print((float) (countSimilarity / 4) + " "); System.out.println(); countSimilarity = 0; } } map1.put(usersNames, usersResults); } list.add(map1); //System.out.println(savedCollection.count()); /* // Read every Element Example DBCursor cursor2 = savedCollection.find(searchDocument); if (cursor2.hasNext()) { theObj = cursor2.next(); //String l = ( String) cursor2.one().get("exist").toString(); } BasicDBList list = new BasicDBList(); list = (BasicDBList) theObj.get("Hashtags"); BasicDBList l2 = new BasicDBList(); for (int i = 0; i < list.size(); i++) { BasicDBObject bj = (BasicDBObject) list.get(i); System.out.println(bj.getString("hashtag")); } DBCursor cursor2 = savedCollection.find(); List<String> list = new ArrayList(); while (cursor2.hasNext()) { BasicDBObject document2 = (BasicDBObject) cursor2.next(); String bj = (String) document2.get("User"); System.out.println(bj); for (int i = 0; i < list.size(); i++) { // String bj = (String) list.get(i); // System.out.println(bj.getString("hashtag")); System.out.println(bj); } */ }
From source file:twitterrest.SearchTweet.java
License:Apache License
public static void main(String[] args) throws TwitterException { //?/*from www.java 2 s. 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(); 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.Timeline.java
License:Apache License
public static void main(String[] args) throws TwitterException { Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY) .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN) .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build(); Twitter tw = new TwitterFactory(configuration).getInstance(); List<Status> list = tw.getUserTimeline("masason");//ScreenName[anondroid5] for (Status status : list) { System.out.print(status.getCreatedAt() + " ");//CreatedDate System.out.print(status.getUser().getScreenName() + " ");//ScreenName System.out.println(status.getText());//tweet }/*from w w w .j a va 2 s. com*/ }
From source file:twitterrest.UserSearch.java
License:Apache License
public static void main(String[] args) throws TwitterException { //?//from w ww .j a v a 2 s . com 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());// } }