List of usage examples for twitter4j Status getCreatedAt
Date getCreatedAt();
From source file:collector.TwitterCollector.java
public LinkedHashSet<Tweet> userSearchData(String userName, int maxResults) { LinkedHashSet<Tweet> out = new LinkedHashSet<>(); Paging paging = new Paging(1, 180); int numberOfTweets = maxResults;//512; long lastID = Long.MAX_VALUE; ArrayList<Status> status = new ArrayList<>(); while (status.size() < numberOfTweets) { if (numberOfTweets - status.size() > 180) {//100) { paging.setCount(180);//100); } else {//from ww w. j a v a 2 s .c o m paging.setCount(numberOfTweets - status.size()); } try { List<Status> timeLine = twitter.getUserTimeline(userName, paging); status.addAll(timeLine); for (Status t : status) { if (t.getId() < lastID) { lastID = t.getId(); } } } catch (TwitterException ex) { System.err.println(ex.getMessage()); } paging.setMaxId(lastID - 1); } //armazenar os atributos interessantes a analise dos tweets int qtdretweet = 0; for (Status sta : status) { String text = sta.getText(); if (!sta.isRetweet() && !sta.isRetweeted() && !text.startsWith("RT")) { //&& !TweetMediaDetect.detect(text)) { TwitterUser user; user = new TwitterUser().addID(sta.getUser().getId()).addName(sta.getUser().getName()) .addLocation(sta.getUser().getLocation()).addDateSignin(sta.getUser().getCreatedAt()) .addCountTweets(sta.getUser().getStatusesCount()) .addCountFavorites(sta.getUser().getFavouritesCount()) .addCountFriends(sta.getUser().getFriendsCount()) .addCountFollowers(sta.getUser().getFollowersCount()); Tweet tweet = new Tweet().addUser(user).addText(sta.getText()).addID(sta.getId()) .addDate(sta.getCreatedAt()) .addLatitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLatitude() : Double.MAX_VALUE) .addLongitude(sta.getGeoLocation() != null ? sta.getGeoLocation().getLongitude() : Double.MAX_VALUE); out.add(tweet); } else { qtdretweet++; } } return out; }
From source file:com.ahuralab.mozaic.db.Message.java
License:Open Source License
public static Message create(Status status) { User user = status.getUser();//w ww . ja v a2 s . c o m return new Message(status.getText(), status.getCreatedAt(), status.getRetweetCount(), user.getId(), user.getName(), user.getScreenName(), user.getLocation(), user.getDescription(), user.getProfileImageURL(), status.getId(), 0, 0, user.getFollowersCount(), user.getStatusesCount()); }
From source file:com.alainesp.fan.sanderson.SummaryFragment.java
License:Open Source License
protected int doWork() { int state = DownloadParseSaveTask.STATE_SUCCESS; try {/*from www . j av a 2s . c o m*/ List<twitter4j.Status> tweets; // Twitter client configuration ConfigurationBuilder builder = new ConfigurationBuilder(); builder.setOAuthConsumerKey(TwitterAPISecrets.CONSUMER_KEY) .setOAuthConsumerSecret(TwitterAPISecrets.CONSUMER_SECRET); // TODO: Use guest authentication instead of application builder.setApplicationOnlyAuthEnabled(true).setDebugEnabled(false).setGZIPEnabled(true); Twitter twitter = new TwitterFactory(builder.build()).getInstance(); twitter.getOAuth2Token(); // Get the tweets long lastTweetID = DB.Tweet.getLastTweetID(); if (lastTweetID <= 0) tweets = twitter.getUserTimeline("BrandSanderson"); else tweets = twitter.getUserTimeline("BrandSanderson", new Paging(lastTweetID)); if (tweets != null) { long brandonID = 28187205; Hashtable<Long, DB.Tweet> findTweet = new Hashtable<>(tweets.size() * 16, 0.25f); List<DB.Tweet> dbTweets = new ArrayList<>(tweets.size()); for (twitter4j.Status tweet : tweets) { // Create the tweet if (tweet.isRetweet()) tweet = tweet.getRetweetedStatus(); long tweetID = tweet.getId(); // TODO: Include the tweets in the DB if (findTweet.get(tweetID) == null)// This eliminate tweets already in the replies tree { DB.Tweet dbTweet = new DB.Tweet(tweetID, getTweetText(tweet), tweet.getCreatedAt(), false, tweet.getUser().getName(), tweet.getUser().getBiggerProfileImageURLHttps()); InternetHelper.getRemoteFile(tweet.getUser().getBiggerProfileImageURLHttps()); dbTweets.add(dbTweet); findTweet.put(tweetID, dbTweet); // Traverse the tree of the replies tweets twitter4j.Status treeTweet = tweet; while (treeTweet != null && treeTweet.getInReplyToStatusId() >= 0) { try { long id = treeTweet.getInReplyToStatusId(); long userID = treeTweet.getUser().getId(); treeTweet = null; if (findTweet.get(id) == null || brandonID == userID) treeTweet = twitter.showStatus(id); else// Remove duplicates. Not sure why they appear, but the difference of the text is a dot at the end. dbTweets.remove(dbTweets.size() - 1); } catch (Exception ignore) { } if (treeTweet != null) { findTweet.put(treeTweet.getId(), dbTweet); StringBuilder replyBuilder = new StringBuilder(); replyBuilder.append("<blockquote>"); // Profile image replyBuilder.append("<img src=\""); InternetHelper.getRemoteFile(treeTweet.getUser().getBiggerProfileImageURLHttps()); replyBuilder.append(treeTweet.getUser().getBiggerProfileImageURLHttps()); replyBuilder.append("\"/> <b>"); // Username - date replyBuilder.append(treeTweet.getUser().getName()); replyBuilder.append("</b> @"); replyBuilder.append(treeTweet.getUser().getScreenName()); replyBuilder.append(" - "); replyBuilder .append(TwitterFragment.showDateFormat.format(treeTweet.getCreatedAt())); // Tweet text replyBuilder.append("<br/>"); replyBuilder.append(getTweetText(treeTweet)); // Remaining replyBuilder.append(dbTweet.htmlReply); replyBuilder.append("</blockquote>"); dbTweet.htmlReply = replyBuilder.toString(); } } } } DB.Tweet.updateTwitter(dbTweets); } } catch (Exception e) { Logger.reportError(e.toString()); state = DownloadParseSaveTask.STATE_ERROR_PARSING; } return state; }
From source file:com.alta189.cyborg.commandkit.twitter.TwitterCommands.java
License:Open Source License
@Command(name = "twitter", desc = "displays the last tweet of a twitter user", aliases = { "twit" }) @Usage(".twitter <user>") public CommandResult twitter(CommandSource source, CommandContext context) { if (source.getSource() == CommandSource.Source.USER && (context.getPrefix() == null || !context.getPrefix().equals("."))) { return null; }/*from ww w. j a v a 2 s . co m*/ if (context.getArgs() == null || context.getArgs().length < 1) { return get(ReturnType.NOTICE, "Correct usage is .twitter <user>", source, context); } try { List<Status> statusList = twitter.getUserTimeline(context.getArgs()[0]); if (statusList == null || statusList.size() < 1) { return get(ReturnType.MESSAGE, "User has no tweets!", source, context); } Status status = statusList.get(0); status.getUser(); StringBuilder builder = new StringBuilder(); builder.append(status.getUser().getScreenName()).append(Colors.BLUE).append(": ").append(Colors.NORMAL) .append(status.getText()).append(" ("); Period period = new Period(new DateTime(status.getCreatedAt()), new DateTime()); if (period.getWeeks() > 2 || period.getMonths() > 1 || period.getYears() > 1) { builder.append(longTimeFormatter.print(period)); } else { builder.append(timeFormatter.print(period)); } builder.append(" ago)"); return get(ReturnType.MESSAGE, builder.toString().replace(lineBreak, " "), source, context); } catch (TwitterException e) { if (e.getStatusCode() == 404) { return get(ReturnType.MESSAGE, "User not found!", source, context); } else if (e.getStatusCode() == 401) { return get(ReturnType.MESSAGE, "Access denied by Twitter!", source, context); } else { e.printStackTrace(); return get(ReturnType.MESSAGE, "There was an internal error!", source, context); } } }
From source file:com.appspot.bitlyminous.handler.twitter.SaveUrlHandler.java
License:Apache License
@Override public StatusUpdate execute(Status tweet) { try {//from w ww . j a v a 2 s .c om List<String> shortUrls = extractBitlyUrls(tweet.getText()); if (!shortUrls.isEmpty()) { Set<Url> longUrls = getBitlyClient() .call(Bitly.expand(shortUrls.toArray(new String[shortUrls.size()]))); List<com.appspot.bitlyminous.entity.Url> entities = new ArrayList<com.appspot.bitlyminous.entity.Url>(); for (Url url : longUrls) { if (!isEmpty(url.getLongUrl())) { com.appspot.bitlyminous.entity.Url entity = new com.appspot.bitlyminous.entity.Url(); entity.setDescription(tweet.getText()); entity.setUrl(url.getLongUrl()); entity.setShortUrl(url.getShortUrl()); entity.setDateSubmitted(tweet.getCreatedAt()); List<String> suggestedTags = new ArrayList<String>(); DeliciousGateway deliciousGateway = getDeliciousGateway(context.getVersion()); try { suggestedTags = deliciousGateway.getSuggestedTags(url.getLongUrl()); } catch (GatewayException e) { logger.log(Level.WARNING, "Seems like Delicious token expired again.", e); if (e.getErrorCode() == HttpURLConnection.HTTP_UNAUTHORIZED) { deliciousGateway .refreshToken(context.getVersion().getDeliciousSessionHandle().getValue()); context.getVersion().setDeliciousToken( new Text(deliciousGateway.getOAuthAuthentication().getAccessToken())); context.getVersion().setDeliciousSecret( new Text(deliciousGateway.getOAuthAuthentication().getAccessTokenSecret())); context.getVersion().setDeliciousSessionHandle(new Text( deliciousGateway.getOAuthAuthentication().getOauthSessionHandle())); suggestedTags = deliciousGateway.getSuggestedTags(url.getLongUrl()); } else { throw e; } } entity.setTags(suggestedTags); entity.setUser(context.getUser()); updateUserTags(context.getUser(), suggestedTags); entities.add(entity); } } context.setUrls(entities); updateUserUrls(context.getUser(), entities); } } catch (Exception e) { logger.log(Level.SEVERE, "Error while persisting urls.", e); } return null; }
From source file:com.appspot.socialinquirer.server.service.impl.UserServiceImpl.java
License:Apache License
@Override public void aggregateQuotes() { EntityManager entityManager = createEntityManager(); try {/*w ww. ja v a2s . co m*/ DataAccessObject dao = getDao(entityManager); Version version = getCurrentVersion(); Twitter twitter = getTwitterClient(); List<Status> homeTimeline = twitter.getUserTimeline(ApplicationConstants.TWITTER_SCREEN_NAME, new Paging(version.getLastHomeTweetId())); long lastTweetId = 0L; for (Status status : homeTimeline) { if (status.getId() > lastTweetId) { lastTweetId = status.getId(); } if (!status.isRetweet() && status.getInReplyToStatusId() == -1) { Quote quote = new Quote(); quote.setPublishedDate(status.getCreatedAt()); quote.setText(new Text(status.getText())); quote.setTweetId(status.getId()); dao.saveOrUpdate(quote); } } if (lastTweetId > version.getLastHomeTweetId()) { version.setLastHomeTweetId(lastTweetId); dao.saveOrUpdate(version); } } catch (Exception e) { throw new ServiceException(e); } finally { closeEntityManager(entityManager); } }
From source file:com.aremaitch.codestock2010.repository.TweetObj.java
License:Apache License
public static TweetObj createInstance(Status status) { TweetObj to = new TweetObj(); to.setId(status.getId());/* www. ja v a 2s . co m*/ to.setText(status.getText()); to.setToUserId(status.getInReplyToUserId()); to.setToUser(status.getInReplyToScreenName()); if (status.getUser() != null) { to.setFromUser(status.getUser().getScreenName()); to.setFromUserId(status.getUser().getId()); to.setIsoLanguageCode(status.getUser().getLang()); to.setProfileImageUrl(status.getUser().getProfileBackgroundImageUrl()); } to.setSource(status.getSource()); to.setCreatedAt(status.getCreatedAt()); if (status.getGeoLocation() != null) { to.setLatitude(status.getGeoLocation().getLatitude()); to.setLongitude(status.getGeoLocation().getLongitude()); } return to; }
From source file:com.bordengrammar.bordengrammarapp.TwitterActivity.java
License:Open Source License
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_twitter); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true);//ww w .j av a2s .c om } SystemBarTintManager tintManager = new SystemBarTintManager(this); tintManager.setStatusBarTintEnabled(true); tintManager.setStatusBarTintResource(R.color.bordenpurple); FeedbackSettings feedbackSettings = new FeedbackSettings(); feedbackSettings.setCancelButtonText("Cancel"); feedbackSettings.setSendButtonText("Send"); feedbackSettings.setText("Send feedback to improve the app"); feedbackSettings.setTitle("Feedback"); feedbackSettings.setToast("We value your feedback"); feedBack = new FeedbackDialog(this, "AF-186C1F794D93-1A", feedbackSettings); ActionBar actionBar = getActionBar(); assert actionBar != null; actionBar.setDisplayHomeAsUpEnabled(true); PACKAGE_NAME = getApplicationContext().getPackageName(); //Now lets get down into the twitter ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("Toqp03fcUErG5P8e9nhfsw") .setOAuthConsumerSecret("SEqktstO9h7SqSm7zmcuWlH3bOtElJm1Ds2TFSwFBc") .setOAuthAccessToken("2245935685-U5LMfl4oEcOv6Khw58JZqRdcH2PlABEeUP2JeXj") .setOAuthAccessTokenSecret("uFcGRpCx8aGXdv3AiAkfVImnoLrlNNCUnZ2UtE76Zbnpa"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter = tf.getInstance(); List<Status> statuses = null; String user; user = "bordengrammar"; try { statuses = twitter.getUserTimeline(user); } catch (TwitterException e) { e.printStackTrace(); } assert statuses != null; twitter4j.Status status1 = statuses.get(0); Format formatter = new SimpleDateFormat("MMM d, K:mm"); savePrefs("twitter", status1.getText()); savePrefs("twittertime", formatter.format(status1.getCreatedAt())); twitter4j.Status status2 = statuses.get(1); twitter4j.Status status3 = statuses.get(2); twitter4j.Status status4 = statuses.get(3); twitter4j.Status status5 = statuses.get(4); twitter4j.Status status6 = statuses.get(5); twitter4j.Status status7 = statuses.get(6); twitter4j.Status status8 = statuses.get(7); twitter4j.Status status9 = statuses.get(8); twitter4j.Status status10 = statuses.get(9); TextView time1 = (TextView) findViewById(R.id.time1); TextView time2 = (TextView) findViewById(R.id.time2); TextView time3 = (TextView) findViewById(R.id.time3); TextView time4 = (TextView) findViewById(R.id.time4); TextView time5 = (TextView) findViewById(R.id.time5); TextView time6 = (TextView) findViewById(R.id.time6); TextView time7 = (TextView) findViewById(R.id.time7); TextView time8 = (TextView) findViewById(R.id.time8); TextView time9 = (TextView) findViewById(R.id.time9); TextView time10 = (TextView) findViewById(R.id.time10); time1.setText(formatter.format(status1.getCreatedAt())); time2.setText(formatter.format(status2.getCreatedAt())); time3.setText(formatter.format(status3.getCreatedAt())); time4.setText(formatter.format(status4.getCreatedAt())); time5.setText(formatter.format(status5.getCreatedAt())); time6.setText(formatter.format(status6.getCreatedAt())); time7.setText(formatter.format(status7.getCreatedAt())); time8.setText(formatter.format(status8.getCreatedAt())); time9.setText(formatter.format(status9.getCreatedAt())); time10.setText(formatter.format(status10.getCreatedAt())); TextView text1 = (TextView) findViewById(R.id.text1); TextView text2 = (TextView) findViewById(R.id.text2); TextView text3 = (TextView) findViewById(R.id.text3); TextView text4 = (TextView) findViewById(R.id.text4); TextView text5 = (TextView) findViewById(R.id.text5); TextView text6 = (TextView) findViewById(R.id.text6); TextView text7 = (TextView) findViewById(R.id.text7); TextView text8 = (TextView) findViewById(R.id.text8); TextView text9 = (TextView) findViewById(R.id.text9); TextView text10 = (TextView) findViewById(R.id.text10); text1.setText(readPrefs("twitter")); text2.setText(status2.getText()); text3.setText(status3.getText()); text4.setText(status4.getText()); text5.setText(status5.getText()); text6.setText(status6.getText()); text7.setText(status7.getText()); text8.setText(status8.getText()); text9.setText(status9.getText()); text10.setText(status10.getText()); /* i think i could have used a for loop... oh well i typed it all already. */ }
From source file:com.cafeform.iumfs.twitterfs.files.AbstractTimelineFile.java
License:Apache License
/** * Convert Status to formated text./*from w ww .java 2 s. com*/ * * @param status Status * @return formatted text */ public static String statusToFormattedString(Status status) { // Add user name time.. StringBuilder sb = new StringBuilder(); Date createdDate = status.getCreatedAt(); SimpleDateFormat simpleFormat = new SimpleDateFormat("MM/dd HH:mm:ss"); sb.append(simpleFormat.format(createdDate)); sb.append(" "); sb.append(status.getUser().getScreenName()); sb.append("["); sb.append(status.getUser().getName()); sb.append("] \n"); sb.append(status.getText()); sb.append("\n\n"); return sb.toString(); }
From source file:com.chimpler.example.TwitterStatusProducer.java
License:Apache License
public synchronized void startSample(String username, String password) { if (twitterStream != null) { return;/* w w w .j a v a2 s .c om*/ } TwitterStreamFactory factory = new TwitterStreamFactory( new ConfigurationBuilder().setUser(username).setPassword(password).build()); twitterStream = factory.getInstance(); twitterStream.addListener(new StatusAdapter() { public void onStatus(Status status) { Map<String, Object> map = new HashMap<String, Object>(); map.put("status", "OK"); map.put("createdAt", status.getCreatedAt().toString()); map.put("username", status.getUser().getName()); map.put("profileImageUrl", status.getUser().getMiniProfileImageURL()); map.put("text", status.getText()); cometTwitterService.publishMessage(map, Long.toString(status.getId())); } @Override public void onException(Exception ex) { Map<String, Object> map = new HashMap<String, Object>(); map.put("status", "ERR"); map.put("text", ex.getMessage()); cometTwitterService.publishMessage(map, "-1"); stopSample(); } }); logger.log(Level.INFO, "Starting listening to twitter sample"); twitterStream.sample(); }