List of usage examples for twitter4j Status getId
long getId();
From source file:TwitterDownload.TwitterHandler.java
public List<Status> getUserTimeline(String searchPhrase, int pageSize) throws TwitterException { String userName = searchPhrase; if (!userName.contains(" ")) { if (!userName.startsWith("@")) return getSearchTweets(userName, pageSize); long lastID = Long.MAX_VALUE; ArrayList<Status> tweets = new ArrayList<Status>(); int count = 200; try {//from w w w . j av a 2 s .c o m int i = 0; while (tweets.size() < pageSize) { i++; if (pageSize - tweets.size() > 200) count = 200; else count = pageSize - tweets.size(); Paging page = new Paging(i, count); //page.maxId(lastID); List<Status> l = twitter.getUserTimeline(userName, page); tweets.addAll(l); if (l.size() < 200) { break; } for (Status t : tweets) { if (t.getId() < lastID) lastID = t.getId(); else if (t.getId() == lastID) break; } } return (List<Status>) tweets; } catch (TwitterException ex) { String s = ex.toString(); //TODO: needs to be refined to only include user not found exception if (ex.resourceNotFound()) return getSearchTweets(searchPhrase, pageSize); } catch (Exception ex) { String s = ex.toString(); return null; } } //else return getSearchTweets(userName, pageSize); }
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 ww w. j a v a 2 s .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:twittertestingagain.TwitterTesting.java
/** * @param args the command line arguments * @throws twitter4j.TwitterException//from ww w . j a v a2 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:TwitterUserTimelineTweets.timeliner.java
public static void main(String[] args) throws JSONException, ParseException, InterruptedException { Postgresql.DBBaglan();//from w w w. j a v a 2s. c o m Postgresql.DBSelect(); Twitter twitter = new TwitterFactory().getInstance(); int pageno = 1; //String user = "gasanyasan"; List statuses = new ArrayList(); for (int i = 0; i < 5; i++) { System.out.println("ARANAN KULLANICI : " + sonuc[i]); while (true) { try { int size = statuses.size(); Paging page = new Paging(pageno++, 100); statuses.addAll(twitter.getUserTimeline(sonuc[i], page)); if (statuses.size() == size) break; } catch (TwitterException e) { if (e.getErrorCode() == 88) { System.out.println("SORGU LMT AILDI.....UYKUYA GRYOR..."); Thread.sleep(900000); } //e.printStackTrace(); } } } for (Object statuse : statuses) { Status a = (Status) statuse; System.out.println(a.getText()); System.out.println(a.getCreatedAt()); System.out.println(a.getUser().getScreenName()); System.out.println(a.getId()); } System.out.println("Total: " + statuses.size()); // System.out.println(stats.get(0).getText()); }
From source file:twittynumnum.FutureListener.java
public void listen(String[] keywords) { StatusListener listener = new StatusListener() { @Override//from w w w . j av a 2 s.c o m public void onException(Exception arg0) { } @Override public void onDeletionNotice(StatusDeletionNotice arg0) { } @Override public void onScrubGeo(long arg0, long arg1) { } @Override public void onStatus(Status status) { User user = status.getUser(); String username = user.getScreenName(); String profileLocation = user.getLocation(); long tweetId = status.getId(); String content = status.getText(); Date tweetDate = status.getCreatedAt(); out.print(tweetId + "\t" + tweetDate + "\t" + username + "\t" + profileLocation + "\t" + content.replaceAll("\n", "/n") + "\n"); } @Override public void onTrackLimitationNotice(int arg0) { } @Override public void onStallWarning(StallWarning sw) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }; FilterQuery filter = new FilterQuery(); filter.track(keywords); twitterStream.addListener(listener); twitterStream.filter(filter); }
From source file:uk.ac.susx.tag.method51.twitter.Tweet.java
License:Apache License
public Tweet(Status status) { this();//from w ww. jav a 2 s . c o m 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//from ww w .j a va2 s .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:uk.co.flax.ukmp.twitter.TweetUpdateThread.java
License:Apache License
private Tweet buildTweetFromStatus(Status status) { String text = status.getText(); Tweet tweet = new Tweet(); tweet.setId("" + status.getId()); tweet.setText(text);/* ww w .j av a 2s . co m*/ tweet.setUserScreenName(status.getUser().getScreenName()); tweet.setUserName(status.getUser().getName()); tweet.setCreated(status.getCreatedAt()); if (status.getPlace() != null) { tweet.setPlaceName(status.getPlace().getFullName()); tweet.setCountry(status.getPlace().getCountry()); } tweet.setRetweetCount(status.getRetweetCount()); tweet.setFavouriteCount(status.getFavoriteCount()); tweet.setParty(partyListIds.get(status.getUser().getId())); if (status.getUserMentionEntities() != null) { List<String> screenNames = new ArrayList<>(status.getUserMentionEntities().length); List<String> fullNames = new ArrayList<>(status.getUserMentionEntities().length); for (UserMentionEntity ent : status.getUserMentionEntities()) { screenNames.add(ent.getScreenName()); if (StringUtils.isNotBlank(ent.getName())) { fullNames.add(ent.getName()); } } tweet.setMentionScreenNames(screenNames); tweet.setMentionFullNames(fullNames); } if (status.getHashtagEntities().length > 0) { List<String> hashtags = new ArrayList<>(status.getHashtagEntities().length); for (HashtagEntity ht : status.getHashtagEntities()) { hashtags.add(ht.getText()); } tweet.setHashtags(hashtags); } // Call the entity extraction service Map<String, List<String>> entities = entityExtraction.getEntities(text); if (entities != null && !entities.isEmpty()) { Map<String, Object> tweetEntities = new HashMap<String, Object>(); entities.keySet().forEach(type -> tweetEntities.put(type, entities.get(type))); tweet.setEntities(tweetEntities); } return tweet; }
From source file:wap.twitter.model.TwitterUtility.java
public List<Tweet> getTweets(String news) { TwitterFactory tf = config();// ww w . j a va2 s . c o 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 va 2s .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; }