List of usage examples for twitter4j Status getRetweetedStatus
Status getRetweetedStatus();
From source file:testtweet.TweetUsingTwitter4jExample.java
/** * @param args the command line arguments *///from w w w .j a v a 2 s .com public static void main(String[] args) throws IOException, TwitterException { //Instantiate a re-usable and thread-safe factory TwitterFactory twitterFactory = new TwitterFactory(Data.getConf().build()); //Instantiate a new Twitter instance Twitter twitter = twitterFactory.getInstance(); /* //setup OAuth Consumer Credentials twitter.setOAuthConsumer(consumerKey, consumerSecret); //setup OAuth Access Token twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); */ //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate( //your tweet or status message "Twitter API #Hacked"); //attach any media, if you want to /* statusUpdate.setMedia( //title of media "http://h1b-work-visa-usa.blogspot.com" , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream()); */ //tweet or update status Status status = twitter.updateStatus(statusUpdate); //response from twitter server 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.getRateLimitStatus().getRemainingHits() = " + status.getRateLimitStatus().getRemaining()); } System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities())); System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities())); }
From source file:Twitter.Frame.java
public Document statustoJSON(Status status) { Document doc = new Document(); if (status.getText() != null) doc.append("tweet", status.getText()); if (status.getUser().getName() != null) doc.append("name", status.getUser().getName()); if (status.getPlace() != null) doc.append("place", status.getPlace().toString()); if (status.getUser().getScreenName() != null) doc.append("nick", status.getUser().getScreenName()); if (status.getGeoLocation() != null) doc.append("gloc", status.getGeoLocation().toString()); doc.append("fcont", status.getFavoriteCount()); doc.append("rcunt", status.getRetweetCount()); if (status.getRetweetedStatus() != null) doc.append("rstate", status.getRetweetedStatus().getText()); tacol.setText(tacol.getText() + doc.toJson() + "\n");//imprimimos el tweet en el frame return doc;// www . j a va 2s . co m }
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. j a va2 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:twittermarkovchain.Main.java
public static void main(String[] args) throws TwitterException, IOException { Args.parseOrExit(Main.class, args); Twitter twitter = TwitterFactory.getSingleton(); List<String> tweets = new ArrayList<>(); File file = new File(user + ".txt"); if (file.exists()) { BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); String line;/* w w w . j a va 2s . c o m*/ while ((line = br.readLine()) != null) { tweets.add(line); } } else { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); int total = 0; int page = 1; int size; do { ResponseList<Status> statuses = twitter.timelines().getUserTimeline(user, new Paging(page++, 200)); size = statuses.size(); total += size; for (Status status : statuses) { if (status.getInReplyToUserId() == -1 && status.getRetweetedStatus() == null) { String text = status.getText().replaceAll("\n", " "); bw.write(text); bw.newLine(); tweets.add(text); } } } while (size > 0); bw.close(); } // We need to generate a map of pair frequencies indexed by the first in the pair Map<String, Map<String, Integer>> frequencyMap = tweets.stream().flatMap((String s) -> { Stream.Builder<Pair> builder = Stream.builder(); String last = null; for (String current : s.toLowerCase().replaceAll("https?://.+\\b", "").replaceAll("[^a-z@# ]", "") .split(" ")) { if (current.equals("")) continue; if (last == null) { builder.add(new Pair("", current)); } else { builder.add(new Pair(last, current)); } last = current; } if (last != null) { builder.add(new Pair(last, "")); } return builder.build(); }).collect(Collectors.toMap(p -> p.s1, p -> ImmutableMap.of(p.s2, 1), (m1, m2) -> { HashMap<String, Integer> newmap = new HashMap<>(m1); for (Map.Entry<String, Integer> e : m2.entrySet()) { String key = e.getKey(); Integer integer = newmap.get(key); if (integer == null) { newmap.put(key, 1); } else { newmap.put(key, integer + e.getValue()); } } return newmap; })); // Random! Random random = new SecureRandom(); // Check using language JLanguageTool language = new JLanguageTool(Language.ENGLISH); for (int i = 0; i < 1000; i++) { StringBuilder sb = new StringBuilder(); // Now that we have the frequency map we can generate a message. String word = ""; do { Map<String, Integer> distribution = frequencyMap.get(word); int total = 0; for (Map.Entry<String, Integer> e : distribution.entrySet()) { total += e.getValue(); } int which = random.nextInt(total); int current = 0; for (Map.Entry<String, Integer> e : distribution.entrySet()) { Integer value = e.getValue(); if (which >= current && which < current + value) { word = e.getKey(); } current += value; } if (sb.length() > 0) { if (word.length() > 0) { sb.append(" "); sb.append(word); } } else { sb.append(word.substring(0, 1).toUpperCase()); if (word.length() > 1) sb.append(word.substring(1)); } } while (!word.equals("")); sb.append("."); List<RuleMatch> check = language.check(sb.toString()); if (check.isEmpty()) { System.out.println(sb); } } }
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);//from w w w . ja v a2 s. com 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:twitterswingclient.TwitterClient.java
private void updateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateActionPerformed // TODO add your handling code here: String consKey = "Your key"; String consSecret = "Your secret"; String accToken = "Your key"; String accSecret = "Your secret"; try {// w ww . j a v a 2s. com TwitterFactory twitterFactory = new TwitterFactory(); Twitter twitter = twitterFactory.getInstance(); twitter.setOAuthConsumer(consKey, consSecret); twitter.setOAuthAccessToken(new AccessToken(accToken, accSecret)); StatusUpdate statusUpdate = new StatusUpdate(status.getText()); statusUpdate.setMedia("Feeling great", new URL("http://media3.giphy.com/media/el1tH0BzEWm4w/giphy.gif").openStream()); Status stat = twitter.updateStatus(statusUpdate); textArea.append("status.toString() = " + stat.toString()); textArea.append("status.getInReplyToScreenName() = " + stat.getInReplyToScreenName()); textArea.append("status.getSource() = " + stat.getSource()); textArea.append("status.getText() = " + stat.getText()); textArea.append("status.getContributors() = " + Arrays.toString(stat.getContributors())); textArea.append("status.getCreatedAt() = " + stat.getCreatedAt()); textArea.append("status.getCurrentUserRetweetId() = " + stat.getCurrentUserRetweetId()); textArea.append("status.getGeoLocation() = " + stat.getGeoLocation()); textArea.append("status.getId() = " + stat.getId()); textArea.append("status.getInReplyToStatusId() = " + stat.getInReplyToStatusId()); textArea.append("status.getInReplyToUserId() = " + stat.getInReplyToUserId()); textArea.append("status.getPlace() = " + stat.getPlace()); textArea.append("status.getRetweetCount() = " + stat.getRetweetCount()); textArea.append("status.getRetweetedStatus() = " + stat.getRetweetedStatus()); textArea.append("status.getUser() = " + stat.getUser()); textArea.append("status.getAccessLevel() = " + stat.getAccessLevel()); textArea.append("status.getHashtagEntities() = " + Arrays.toString(stat.getHashtagEntities())); textArea.append("status.getMediaEntities() = " + Arrays.toString(stat.getMediaEntities())); if (stat.getRateLimitStatus() != null) { textArea.append("status.getRateLimitStatus().getLimit() = " + stat.getRateLimitStatus().getLimit()); textArea.append( "status.getRateLimitStatus().getRemaining() = " + stat.getRateLimitStatus().getRemaining()); textArea.append("status.getRateLimitStatus().getResetTimeInSeconds() = " + stat.getRateLimitStatus().getResetTimeInSeconds()); textArea.append("status.getRateLimitStatus().getSecondsUntilReset() = " + stat.getRateLimitStatus().getSecondsUntilReset()); textArea.append("status.getRateLimitStatus().getRemainingHits() = " + stat.getRateLimitStatus().getRemaining()); } textArea.append("status.getURLEntities() = " + Arrays.toString(stat.getURLEntities())); textArea.append("status.getUserMentionEntities() = " + Arrays.toString(stat.getUserMentionEntities())); } catch (IOException ex) { textArea.append("IO Exception"); } catch (TwitterException tw) { textArea.append("Twitter Exception"); } }
From source file:uk.ac.susx.tag.method51.twitter.Tweet.java
License:Apache License
public Tweet(Status status) { this();/*from w ww .ja v a2 s. com*/ created = status.getCreatedAt(); id = status.getId(); text = status.getText(); inReplyToStatusId = status.getInReplyToStatusId(); inReplyToUserId = status.getInReplyToUserId(); originalText = null; retweetId = -1; isTruncated = status.isTruncated(); isRetweet = status.isRetweet(); Status entities = status; if (isRetweet) { Status origTweet = status.getRetweetedStatus(); entities = origTweet; retweetId = origTweet.getId(); originalText = text; text = origTweet.getText(); } StringBuilder sb = new StringBuilder(); for (HashtagEntity e : entities.getHashtagEntities()) { sb.append(e.getText()); sb.append(" "); } hashtags = sb.toString(); sb = new StringBuilder(); for (UserMentionEntity e : entities.getUserMentionEntities()) { sb.append(e.getScreenName()); sb.append(" "); } mentions = sb.toString(); sb = new StringBuilder(); for (URLEntity e : entities.getURLEntities()) { //String url = e.getURL(); String url = e.getExpandedURL(); if (url == null) { url = e.getURL(); if (url != null) { sb.append(url); } } else { sb.append(url); } sb.append(" "); } urls = sb.toString(); sb = new StringBuilder(); //seems to be null if no entries MediaEntity[] mediaEntities = entities.getMediaEntities(); if (mediaEntities != null) { for (MediaEntity e : mediaEntities) { String url = e.getMediaURL(); sb.append(url); sb.append(" "); } mediaUrls = sb.toString(); } else { mediaUrls = ""; } received = new Date(); source = status.getSource(); GeoLocation geoLoc = status.getGeoLocation(); Place place = status.getPlace(); if (geoLoc != null) { geoLong = geoLoc.getLongitude(); geoLat = geoLoc.getLatitude(); } else if (place != null && place.getBoundingBoxCoordinates() != null && place.getBoundingBoxCoordinates().length > 0) { GeoLocation[] locs = place.getBoundingBoxCoordinates()[0]; double avgLat = 0; double avgLon = 0; for (GeoLocation loc : locs) { avgLat += loc.getLatitude(); avgLon += loc.getLongitude(); } avgLat /= locs.length; avgLon /= locs.length; geoLat = avgLat; geoLong = avgLon; } else { geoLong = null; geoLat = null; } twitter4j.User user = status.getUser(); if (user != null) { userId = user.getId(); location = user.getLocation(); screenName = user.getScreenName(); following = user.getFriendsCount(); name = user.getName(); lang = user.getLang(); timezone = user.getTimeZone(); userCreated = user.getCreatedAt(); followers = user.getFollowersCount(); statusCount = user.getStatusesCount(); description = user.getDescription(); url = user.getURL(); utcOffset = user.getUtcOffset(); favouritesCount = user.getFavouritesCount(); this.user = new User(user); } }
From source file:uk.co.cathtanconsulting.twitter.TwitterSource.java
License:Apache License
/** * @param status/*www. j a v a2 s . c o m*/ * * Generate a TweetRecord object and submit to * */ private void extractRecord(Status status) { TweetRecord record = new TweetRecord(); //Basic attributes record.setId(status.getId()); //Using SimpleDateFormat "yyyy-MM-dd'T'HH:mm:ss'Z'" record.setCreatedAtStr(formatterTo.format(status.getCreatedAt())); //Use millis since epoch since Avro doesn't do dates record.setCreatedAtLong(status.getCreatedAt().getTime()); record.setTweet(status.getText()); //User based attributes - denormalized to keep the Source stateless //but also so that we can see user attributes changing over time. //N.B. we could of course fork this off as a separate stream of user info User user = status.getUser(); record.setUserId(user.getId()); record.setUserScreenName(user.getScreenName()); record.setUserFollowersCount(user.getFollowersCount()); record.setUserFriendsCount(user.getFriendsCount()); record.setUserLocation(user.getLocation()); //If it is zero then leave the value null if (status.getInReplyToStatusId() != 0) { record.setInReplyToStatusId(status.getInReplyToStatusId()); } //If it is zero then leave the value null if (status.getInReplyToUserId() != 0) { record.setInReplyToUserId(status.getInReplyToUserId()); } //Do geo. N.B. Twitter4J doesn't give use the geo type GeoLocation geo = status.getGeoLocation(); if (geo != null) { record.setGeoLat(geo.getLatitude()); record.setGeoLong(geo.getLongitude()); } //If a status is a retweet then the original tweet gets bundled in //Because we can't guarantee that we'll have the original we can //extract the original tweet and process it as we have done this time //using recursion. Note: we will end up with dupes. Status retweetedStatus = status.getRetweetedStatus(); if (retweetedStatus != null) { record.setRetweetedStatusId(retweetedStatus.getId()); record.setRetweetedUserId(retweetedStatus.getUser().getId()); extractRecord(retweetedStatus); } //Submit the populated record onto the channel processRecord(record); }