List of usage examples for twitter4j Status getGeoLocation
GeoLocation getGeoLocation();
From source file:TwitterDownload.TwitterExel.java
public static String writeTweets(long ID, List<Status> tweets, String path) { try {// www. j ava2s .c om 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:twitterrest.GeoSearch.java
License:Apache License
public static void main(String[] args) throws TwitterException { // ?/*from w ww. j a v a 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(); // ?????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.UserSearch.java
License:Apache License
public static void main(String[] args) throws TwitterException { //?/* ww w . ja v a 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(); // 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 Tweet getTweetObject(Status status) { Tweet tweet = new Tweet(); int sentimentScore = StanfordCoreNLPTool.findSentiment(status.getText()); if (sentimentScore != -1) { tweet.setDateTime(status.getCreatedAt()); tweet.setTweetText(status.getText()); tweet.setUsername(status.getUser().getScreenName()); tweet.setSentimentScore(sentimentScore); GeoLocation geoLocation = status.getGeoLocation(); if (geoLocation != null) { tweet.setLongitude(geoLocation.getLongitude() + ""); tweet.setLatitude(geoLocation.getLatitude() + ""); } else {/*from w w w . ja v a 2s. c om*/ tweet.setLongitude(null);// tweet.setLatitude(null);// } Place place = status.getPlace(); if (place != null) { tweet.setCountry(place.getCountry()); tweet.setPlace(place.getFullName()); } else { tweet.setCountry(null);// tweet.setPlace(null);// } } else tweet = null; return tweet; }
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 {/*from www . ja v a 2s .c om*/ 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();// w w w .j ava 2 s . c om 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/* w ww . ja v a 2s . c om*/ * * 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); }
From source file:wap.twitter.model.TwitterUtility.java
public List<Tweet> getTweets(String news) { TwitterFactory tf = config();//www . ja va2 s .co m Twitter twitter = tf.getInstance(); try { List<Tweet> tws = new ArrayList<Tweet>(); int i = 0; Query query = new Query("#" + news); QueryResult result; do { result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { Tweet tw = new Tweet(); if (i == 8) { break; } else { tw.setTitle(news); tw.setUser(tweet.getUser().getScreenName()); tw.setUrl(tweet.getSource()); tw.setImage(tweet.getUser().getProfileImageURL()); tw.setBody(tweet.getText()); tw.setSource(tweet.getSource()); tw.setId(tweet.getId() + ""); i++; } System.out.println("******************* " + tweet.getGeoLocation()); tws.add(tw); } } while ((query = result.nextQuery()) != null); return tws; } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to search tweets: " + te.getMessage()); System.exit(-1); } return null; }
From source file:webServices.RestServiceImpl.java
@GET @Path("/findTwittsRest") @Produces({ MediaType.TEXT_PLAIN })//w ww . j a va2 s . c om public String twitterSearchRest(@QueryParam("keys") String searchKeys, @QueryParam("sinceId") long sinceId, @QueryParam("maxId") long maxId, @QueryParam("update") boolean update, @QueryParam("location") String location) { final Vector<String> results = new Vector<String>(); String output = ""; long higherStatusId = Long.MIN_VALUE; long lowerStatusId = Long.MAX_VALUE; Query searchQuery = new Query(searchKeys); searchQuery.setCount(50); searchQuery.setResultType(Query.ResultType.recent); if (sinceId != 0) { if (update) { searchQuery.setSinceId(sinceId); } higherStatusId = sinceId; } if (maxId != 0) { if (!update) { searchQuery.setMaxId(maxId); } lowerStatusId = maxId; } if (location != null) { double lat = Double.parseDouble(location.substring(0, location.indexOf(","))); double lon = Double.parseDouble(location.substring(location.indexOf(",") + 1, location.length())); searchQuery.setGeoCode(new GeoLocation(lat, lon), 10, Query.KILOMETERS); } try { QueryResult qResult = twitter.search(searchQuery); for (Status status : qResult.getTweets()) { //System.out.println(Long.toString(status.getId())+" *** "+Long.toString(status.getUser().getId())+" *** "+status.isRetweet()+" *** "+status.isRetweeted()); higherStatusId = Math.max(status.getId(), higherStatusId); lowerStatusId = Math.min(status.getId(), lowerStatusId); if (!status.isRetweet()) { if (status.getGeoLocation() != null) { System.out.println(Long.toString(status.getId()) + "@" + Double.toString(status.getGeoLocation().getLatitude()) + "," + Double.toString(status.getGeoLocation().getLongitude())); results.add(Long.toString(status.getId()) + "@" + Double.toString(status.getGeoLocation().getLatitude()) + "," + Double.toString(status.getGeoLocation().getLongitude())); } else { results.add(Long.toString(status.getId()) + "@null"); } } } } catch (TwitterException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } TwitterResults resultsObj = new TwitterResults(results.toString(), higherStatusId, lowerStatusId); ObjectMapper mapper = new ObjectMapper(); try { output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultsObj); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return output; }
From source file:wise.TwitterUtils.java
public ArrayList<CheckinObject> dataList(String cityCode, String selectedDate, String maxTweetParam, String topTweetParam) throws IOException, JSONException, ParseException { ArrayList<CheckinObject> checkinList = new ArrayList<>(); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(Constants.CONSUMER_KEY) .setOAuthConsumerSecret(Constants.CONSUMER_SECRET).setOAuthAccessToken(Constants.TOKEN) .setOAuthAccessTokenSecret(Constants.TOKEN_SECRET); Integer maxTweet = Integer.parseInt(maxTweetParam); Integer topTweet = Integer.parseInt(topTweetParam); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance();/*from w w w .ja v a 2s .co m*/ DateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH); Date startDate = format.parse(selectedDate); Calendar c = Calendar.getInstance(); c.setTime(startDate); c.add(Calendar.DATE, 1); Date endDate = c.getTime(); Query query = SetQueryString(cityCode, startDate, endDate); QueryResult result = null; try { while (query != null && checkinList.size() <= maxTweet) { result = twitter.search(query); if (result != null) { for (Status status : result.getTweets()) { for (URLEntity urlEntity : status.getURLEntities()) { String urlCheckinId = urlEntity.getExpandedURL() .substring(urlEntity.getExpandedURL().lastIndexOf("/") + 1); GeoLocation geo = status.getGeoLocation(); CheckinObject checkin = new CheckinObject(); checkin.CheckinId = urlCheckinId; checkin.Count = 1;//status.getRetweetCount() + status.getFavoriteCount() + 1; checkin.Latitude = geo.getLatitude(); checkin.Longitude = geo.getLongitude(); if (!checkin.containsSameCoordinates(checkinList, checkin.Latitude, checkin.Longitude)) { checkinList.add(checkin); } else { int indexOfCheckinId = checkin.getIndexByCoordinates(checkinList, checkin.Latitude, checkin.Longitude); checkinList.get(indexOfCheckinId).setCheckinCount(checkin.Count); checkinList.get(indexOfCheckinId).setReplacementCheckinId(checkin.CheckinId); } } } query = result.nextQuery(); } else { query = null; } } } catch (TwitterException e) { } Collections.sort(checkinList, new CountComparator()); if (checkinList.size() > topTweet) { checkinList.subList(topTweet, checkinList.size()).clear(); // get top x } FourSquareCheckin fsq = new FourSquareCheckin(); for (CheckinObject checkin : checkinList) { fsq = getVenueInfo(checkin); checkin.LocationName = fsq.VenueName; checkin.Image = fsq.VenueImage; } return checkinList; }