List of usage examples for twitter4j Status getGeoLocation
GeoLocation getGeoLocation();
From source file:tweetcrawling.TweetCrawler.java
public ArrayList<String> getValueToWrite(Status status) { // Getting the value to be written Long tid = status.getId();/*from w w w .ja v a 2 s . c o m*/ String tweetid = tid.toString(); ArrayList<String> valueToWrite = new ArrayList<String>(); User user = status.getUser(); String screenname = user.getScreenName(); String name = user.getName(); String url = getTweetUrl(screenname, tweetid); String body = status.getText().replace("\n", " "); valueToWrite.add(body.replace(",", " ")); // element: body valueToWrite.add(url); // element: id valueToWrite.add(screenname); // element: userid valueToWrite.add(name); // element: user // element: gender if (name != null && !name.isEmpty()) { valueToWrite.add(getUserGender(name)); } else if (screenname != null && !screenname.isEmpty()) { valueToWrite.add(getUserGender(screenname)); } else { valueToWrite.add(""); } valueToWrite.add(user.getLocation()); // element: location valueToWrite.add("" + user.getFollowersCount()); // element: followercount valueToWrite.add("" + user.getFriendsCount()); // element: friendscount valueToWrite.add("" + user.getStatusesCount()); // element: statuscount try { List<String> coor = new ArrayList<String>(); String latitude = "" + status.getGeoLocation().getLatitude(); String longitude = "" + status.getGeoLocation().getLongitude(); coor.add(latitude); coor.add(longitude); if (coor != null && !coor.isEmpty() && coor.size() > 0) { valueToWrite.add(coor.get(0)); // element: latitude valueToWrite.add(coor.get(1)); // element: longitude valueToWrite.add(coor.get(0) + "," + coor.get(1)); } else { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } try { String geoname = status.getPlace().getName(); String country = status.getPlace().getCountry(); if (geoname != null) { valueToWrite.add(geoname); } else { valueToWrite.add(null); } if (country != null) { valueToWrite.add(country); } else { valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date date = status.getCreatedAt(); valueToWrite.add(dateFormat.format(date)); // element: date valueToWrite.add(getDateCrawler()); // element: datecrawler valueToWrite.add(status.getInReplyToScreenName()); // element: replyto String tooltip = ""; try { String geoname = status.getPlace().getName(); if (geoname != null) { tooltip = "user = " + name + ", geoname = " + geoname; } } catch (Exception e) { tooltip = ""; } valueToWrite.add(tooltip.trim()); // element: tooltip valueToWrite.add(SOURCE); // element: source return valueToWrite; }
From source file:tweetcrawling.TweetCrawler.java
public void printTweets(String csvOut) throws IOException, TwitterException { for (Status status : getStatuses()) { // Getting the value to be written Long tid = status.getId(); String tweetid = tid.toString(); ArrayList<String> valueToWrite = new ArrayList<String>(); User user = status.getUser();/* w w w . ja va2 s . co m*/ String screenname = user.getScreenName(); String name = user.getName(); String url = getTweetUrl(screenname, tweetid); valueToWrite.add(url); // element: id valueToWrite.add(screenname); // element: userid valueToWrite.add(name); // element: user // element: gender if (name != null && !name.isEmpty()) { valueToWrite.add(getUserGender(name)); } else if (screenname != null && !screenname.isEmpty()) { valueToWrite.add(getUserGender(screenname)); } else { valueToWrite.add(""); } valueToWrite.add(user.getLocation()); // element: location valueToWrite.add("" + user.getFollowersCount()); // element: followercount valueToWrite.add("" + user.getFriendsCount()); // element: friendscount valueToWrite.add("" + user.getStatusesCount()); // element: statuscount try { List<String> coor = new ArrayList<String>(); String latitude = "" + status.getGeoLocation().getLatitude(); String longitude = "" + status.getGeoLocation().getLongitude(); coor.add(latitude); coor.add(longitude); if (coor != null && !coor.isEmpty() && coor.size() > 0) { valueToWrite.add(coor.get(0)); // element: latitude valueToWrite.add(coor.get(1)); // element: longitude valueToWrite.add(coor.get(0) + "," + coor.get(1)); } else { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); valueToWrite.add(null); } try { String geoname = status.getPlace().getName(); String country = status.getPlace().getCountry(); if (geoname != null) { valueToWrite.add(geoname); } else { valueToWrite.add(null); } if (country != null) { valueToWrite.add(country); } else { valueToWrite.add(null); } } catch (Exception e) { valueToWrite.add(null); valueToWrite.add(null); } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); Date date = status.getCreatedAt(); valueToWrite.add(dateFormat.format(date)); // element: date valueToWrite.add(getDateCrawler()); // element: datecrawler valueToWrite.add(status.getText()); // element: body valueToWrite.add(status.getInReplyToScreenName()); // element: replyto String tooltip = ""; try { String geoname = status.getPlace().getName(); if (geoname != null) { tooltip = "user = " + name + ", geoname = " + geoname; } } catch (Exception e) { tooltip = ""; } valueToWrite.add(tooltip.trim()); // element: tooltip valueToWrite.add(SOURCE); // element: source // Write valueToWrite to csv external file FileWriter fw = new FileWriter(csvOut, true); PrintWriter pw = new PrintWriter(fw); String content = "'"; for (int i = 0; i < valueToWrite.size() - 1; i++) { content += valueToWrite.get(i) + "','"; } content += valueToWrite.get(valueToWrite.size()) + "'"; pw.print(content); pw.flush(); pw.close(); fw.close(); } }
From source file:tweetdownloader.cnr_stable.version.TweetDownload.java
/** * this method return an ArrayList of dataOfTweets * @param allMyTweets//from w w w .j ava2s . com * @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; }
From source file:tweetmining.MiningFunctions.java
/** * This method creates an instance of Miningfunctions based on your TwitterApss credentials. * You should as well check filepaths to put yours. * //from w w w .j a v a 2 s . c om * @throws FileNotFoundException */ public MiningFunctions() throws FileNotFoundException, IOException { ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey) .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken) .setOAuthAccessTokenSecret(AccessTokenSecret); tf = new TwitterFactory(configurationBuilder.build()); twitter = tf.getInstance(); File f = new File(fichero1); File f2 = new File(fichero2); File f3 = new File(fichero3); if (!f.exists()) f.createNewFile(); if (!f2.exists()) f2.createNewFile(); if (!f3.exists()) f3.createNewFile(); pw = new PrintWriter(new FileOutputStream(f, true)); pw2 = new PrintWriter(new FileOutputStream(f2, true)); pw3 = new PrintWriter(new FileOutputStream(f3, true)); listener = new StatusListener() { public void onStatus(Status status) { if (status.getGeoLocation() != null) { cont++; System.out.println("Loc not null----" + cont); GeoLocation loc = status.getGeoLocation(); pw.println(String.valueOf(loc.getLatitude()) + ";" + String.valueOf(loc.getLongitude()) + ";" + status.getUser().getName()); System.out.println( loc.getLatitude() + " " + loc.getLongitude() + " " + status.getUser().getName()); } pw2.println(status.getUser().getName() + "--->" + status.getText()); try { CloseWriteAndOpen(); } catch (FileNotFoundException ex) { java.util.logging.Logger.getLogger(MiningFunctions.class.getName()).log(Level.SEVERE, null, ex); } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onException(Exception ex) { ex.printStackTrace(); } @Override public void onScrubGeo(long l, long l1) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; configurationBuilder = new ConfigurationBuilder(); configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey) .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken) .setOAuthAccessTokenSecret(AccessTokenSecret); twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance(); }
From source file:tweetmining.MiningFunctions.java
/** * This method mines data from a particular twitter user. * @param user String which has the name of a Twitter user without @ *//*from www. ja v a 2 s . c o m*/ public void MineFromUser(String user) { int pageno = 1; List<Status> statuses = new ArrayList(); while (true) { try { int size = statuses.size(); Paging page = new Paging(pageno++, 100); statuses.addAll(twitter.getUserTimeline(user, page)); if (statuses.size() == size) break; } catch (TwitterException e) { e.printStackTrace(); } } System.out.println(statuses.size()); for (Status st : statuses) { GeoLocation loc = st.getGeoLocation(); if (loc != null) { System.out.println("Loc not null"); Double lat = loc.getLatitude(); Double lon = loc.getLongitude(); pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName()); } pw2.println(st.getUser().getName() + "-----" + st.getText()); } pw.close(); pw2.close(); }
From source file:tweetmining.MiningFunctions.java
/** * This method mines data from youw twitter account based on the query string that you pass by * parameters.//from w w w. ja va2 s.com * @param query Query you want to place. * @throws FileNotFoundException * @throws TwitterException */ public void MineFromQuery(String query) throws FileNotFoundException, TwitterException { Query q = new Query(query); QueryResult r; q.count(100); do { r = twitter.search(q); List<Status> statuses = r.getTweets(); for (Status st : statuses) { GeoLocation loc = st.getGeoLocation(); if (loc != null) { System.out.println("Loc not null"); Double lat = loc.getLatitude(); Double lon = loc.getLongitude(); pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName()); } } q = r.nextQuery(); } while (r.hasNext()); }
From source file:tweets.Tweets.java
/** * @param args the command line arguments *//*from w w w . j a va2 s .c o m*/ public static void main(String[] args) throws Exception { ConfigurationBuilder configurtacion = new ConfigurationBuilder(); configurtacion.setDebugEnabled(true).setOAuthConsumerKey("KdVOb7h8mqcjWIfkXXED2G6sJ") .setOAuthConsumerSecret("EXImfgfGCYIbWZIOSEeYVvaDE5oxwJZY7UIuwUusbyRWf2ds7l") .setOAuthAccessToken("785481406654722049-aRARaHgZujPZIdpYla4mVZIMMlvzJRb") .setOAuthAccessTokenSecret("YWWQwbFw8K7rxsnivwpBRZVoQlUhMYy7gOs7KUWOb8Rvy"); Twitter twitter = new TwitterFactory(configurtacion.build()).getInstance(); twitter.getUserTimeline(); String hashtag = "#ElectionNight"; Query busqueda = new Query(hashtag); int numeroTweets = 1500; long ultimo = Long.MAX_VALUE; ArrayList<Status> tweets = new ArrayList<Status>(); while (tweets.size() < numeroTweets) { if (numeroTweets - tweets.size() > 255) { busqueda.setCount(255); } else { busqueda.setCount(numeroTweets - tweets.size()); } try { QueryResult result = twitter.search(busqueda); tweets.addAll(result.getTweets()); System.out.println("Generados " + tweets.size() + " tweets" + "\n"); for (Status t : tweets) { if (t.getId() < ultimo) { ultimo = t.getId(); } System.out.println("Generados " + tweets.size() + " tweets" + "\n"); } } catch (TwitterException excepcion) { System.out.println("Sin conexin " + excepcion); } ; busqueda.setMaxId(ultimo - 1); } // guardamos los datos java.util.Date fecha = new Date(); int hora = fecha.getHours(); int minuto = fecha.getMinutes(); System.out.println(); String nombre = "Datos_" + hashtag + " " + hora + " " + minuto + ".txt"; File f = new File(nombre); FileWriter fw = new FileWriter(f); BufferedWriter bw = new BufferedWriter(fw); System.out.println("identificador\tUsuario\ttweet\n"); for (int i = 0; i < tweets.size(); i++) { Status estadoTweet = (Status) tweets.get(i); GeoLocation loc = estadoTweet.getGeoLocation(); String user = estadoTweet.getUser().getScreenName(); String msg = estadoTweet.getText(); Boolean sensitive = estadoTweet.isPossiblySensitive(); int fav = estadoTweet.getFavoriteCount(); System.out.println("Id: " + i + "| User: " + user + "| Texto: " + msg + "| SentimientoPositivo: " + sensitive + "$\n"); int id = i + 1; bw.append(msg + " | " + sensitive + ";"); bw.newLine(); } bw.close(); }
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;/*w w w .jav a2 s . c o m*/ }
From source file:twitter.stream.PrintSampleStream.java
License:Apache License
/** * Main entry of this application.// w w w. jav a 2 s. c om * * @param args * arguments doesn't take effect with this example * @throws TwitterException * when Twitter service or network is unavailable */ public static void main(String[] args) throws TwitterException { TwitterStream twitterStream = new TwitterStreamFactory().getInstance(); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { if (status.getGeoLocation() != null) System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + "Lat:" + status.getGeoLocation().getLatitude() + "Long" + status.getGeoLocation().getLongitude()); } @Override public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { // System.out.println("Got a status deletion notice id:" + // statusDeletionNotice.getStatusId()); } @Override public void onTrackLimitationNotice(int numberOfLimitedStatuses) { // System.out.println("Got track limitation notice:" + // numberOfLimitedStatuses); } @Override public void onScrubGeo(long userId, long upToStatusId) { // System.out.println("Got scrub_geo event userId:" + userId + " // upToStatusId:" + upToStatusId); } @Override public void onStallWarning(StallWarning warning) { System.out.println("Got stall warning:" + warning); } @Override public void onException(Exception ex) { ex.printStackTrace(); } }; twitterStream.addListener(listener); twitterStream.sample(); }
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 w w w .j av a 2s . 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"); } }