List of usage examples for twitter4j Status getCreatedAt
Date getCreatedAt();
From source file:monitoring.tools.TwitterAPI.java
License:Apache License
private void generateData(String searchTimeStamp) { List<MonitoringData> data = new ArrayList<>(); for (Status s : tweetInfo) { String id = String.valueOf(s.getId()); String timeStamp = String.valueOf(s.getCreatedAt()); String message = s.getText(); String author = "@" + s.getUser().getScreenName(); String link = "https://twitter.com/" + s.getUser().getName().replace(" ", "") + "/status/" + s.getId(); MonitoringData dataObj = new MonitoringData(id, timeStamp, message, author, link); data.add(dataObj);//from w w w . j a v a 2 s . c o m } tweetInfo = new ArrayList<>(); //kafka.generateResponseKafka(data, searchTimeStamp, id, configurationId, this.confParams.getKafkaTopic); kafka.generateResponseIF(data, searchTimeStamp, id, configurationId, this.confParams.getKafkaTopic()); logger.debug("Data successfully sent to Kafka endpoint"); ++id; }
From source file:my.twittergui.TwitterUI.java
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed String text;/*from w w w. ja v a2 s. c o m*/ text = jTextField1.getText(); //jTextArea1.append(text+"\n"); jTextArea1.append("Searching for: "); String[] strarray = text.split(" "); for (int i = 0; i < strarray.length; i++) { jTextArea1.append(strarray[i] + "\n"); } File filed = null; filed = new File("C:\\Results"); if (!filed.exists()) { filed.mkdir(); } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("").setOAuthConsumerSecret("").setOAuthAccessToken("") .setOAuthAccessTokenSecret(""); StatusListener listener = new StatusListener() { public void onStatus(Status status) { try { int fileno = 0; String strI = Integer.toString(fileno); String fname = "C:\\results\\DataCol" + strI + ".csv"; File file = new File(fname); FileWriter bw = new FileWriter(file, true); if (file.length() == 0) { bw.write("\"Screen Name\", text, \"created at\", geolocation, Retweet? \r\n"); bw.flush(); } while (file.length() > 10485760) { fileno += 1; strI = Integer.toString(fileno); fname = "DataCol" + strI + ".txt"; file = new File(fname); bw = new FileWriter(file, true); bw.write("\"Screen Name\", \"text\", \"created_at\", \"geolocation\" \r\n"); bw.flush(); } // if(!status.isRetweet()){ bw.write("\r\n"); bw.write("\"" + status.getUser().getScreenName() + "\","); String tweettxt = status.getText(); tweettxt = tweettxt.replace("\n", ""); tweettxt = tweettxt.replace(",", ""); tweettxt = tweettxt.replace("\"", ""); bw.write("\"" + tweettxt + "\","); bw.write("\"" + status.getCreatedAt() + "\","); if (status.getGeoLocation() != null) { bw.write("\"" + status.getGeoLocation() + "\""); } else bw.write("N/A,"); if (status.isRetweet()) bw.write("Yes"); else bw.write("No"); bw.flush(); bw.close(); //System.out.print("\n"); String str = "@" + status.getUser().getScreenName() + " " + status.getText() + " " + status.getCreatedAt() + " "; if (status.getGeoLocation() != null) str += status.getGeoLocation(); //System.out.print(str); jTextArea1.append(str + "\n"); // } bw.close(); } catch (IOException e) { //System.out.print("EXCEPTION"); e.printStackTrace(); } } public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onStallWarning(StallWarning stall) { } public void onScrubGeo(long a, long b) { } public void onException(Exception ex) { ex.printStackTrace(); } }; TwitterStreamFactory tf = new TwitterStreamFactory(cb.build()); TwitterStream twitterStream = tf.getInstance(); twitterStream.addListener(listener); // Filter FilterQuery filtre = new FilterQuery(); Scanner in = new Scanner(System.in); filtre.track(strarray); twitterStream.filter(filtre); }
From source file:net.lacolaco.smileessence.viewmodel.StatusViewModel.java
License:Open Source License
public StatusViewModel(Status status, Account account) { if (status.isRetweet()) { retweetedStatus = new StatusViewModel(status.getRetweetedStatus(), account); }/*from ww w .j av a2 s . c o m*/ id = status.getId(); text = TwitterUtils.replaceURLEntities(status.getText(), status.getURLEntities(), false); createdAt = status.getCreatedAt(); source = status.getSource(); mentions = status.getUserMentionEntities(); hashtags = status.getHashtagEntities(); media = status.getMediaEntities(); urls = status.getURLEntities(); symbols = status.getSymbolEntities(); User user = status.getUser(); UserCache.getInstance().put(user); userID = user.getId(); screenName = user.getScreenName(); name = user.getName(); iconURL = user.getProfileImageURLHttps(); isProtected = user.isProtected(); setMention(isMention(account.screenName)); setMyStatus(isMyStatus(account.userID)); setRetweetOfMe(isRetweetOfMe(account.userID)); }
From source file:nl.isaac.dotcms.twitter.pojo.CustomStatus.java
License:Creative Commons License
public CustomStatus(Status status) { this.createdAt = status.getCreatedAt(); this.id = status.getId(); this.id_str = String.valueOf(status.getId()); this.text = status.getText(); this.source = status.getSource(); this.isTruncated = status.isTruncated(); this.inReplyToStatusId = status.getInReplyToStatusId(); this.inReplyToUserId = status.getInReplyToUserId(); this.isFavorited = status.isFavorited(); this.inReplyToScreenName = status.getInReplyToScreenName(); this.geoLocation = status.getGeoLocation(); this.place = status.getPlace(); this.retweetCount = status.getRetweetCount(); this.isPossiblySensitive = status.isPossiblySensitive(); this.contributorsIDs = status.getContributors(); this.retweetedStatus = status.getRetweetedStatus(); this.userMentionEntities = status.getUserMentionEntities(); this.urlEntities = status.getURLEntities(); this.hashtagEntities = status.getHashtagEntities(); this.mediaEntities = status.getMediaEntities(); this.currentUserRetweetId = status.getCurrentUserRetweetId(); this.isRetweet = status.isRetweet(); this.isRetweetedByMe = status.isRetweetedByMe(); this.rateLimitStatus = status.getRateLimitStatus(); this.accessLevel = status.getAccessLevel(); this.user = status.getUser(); }
From source file:nl.utwente.bigdata.bolts.FileOutputBolt.java
License:Apache License
@Override public void execute(Tuple tuple, BasicOutputCollector collector) { Status tweet = (Status) tuple.getValueByField("tweet"); this.pw.println(String.format("%s;%s;%s;%s;%s;%s", tweet.getLang(), tweet.getCreatedAt().toGMTString(), tuple.getStringByField("normalized_text"), tuple.getIntegerByField("sentiment"), tuple.getStringByField("home"), tuple.getStringByField("away"))); // logger.info("Wrote to " + this.f.getAbsolutePath()); try {/*from www. j av a 2 s.co m*/ this.writer.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:nl.utwente.bigdata.bolts.PrinterSentiment.java
License:Apache License
@Override public void execute(Tuple tuple, BasicOutputCollector collector) { String icon;//from w w w . j a v a 2 s . c om if ((Integer) tuple.getValueByField("sentiment") > 0) { icon = ":-D"; } else if ((Integer) tuple.getValueByField("sentiment") < 0) { icon = ">:["; } else { icon = ":-)"; } Status tweet = (Status) tuple.getValueByField("tweet"); String tweetText = tweet.getText(); System.out.println(Emoji.replaceFlagInText(this.language) + " " + Emoji.replaceInText(icon) + " " + "DATE: " + tweet.getCreatedAt().toGMTString() + " " + "MATCH: " + tuple.getValueByField("home") + "-" + tuple.getValueByField("away") + " - " + tweetText + " " + tuple.getValueByField("sentiment")); collector.emit(new Values(this.language, tuple.getStringByField("normalized_text"), tweet.getCreatedAt().toGMTString(), tuple.getStringByField("home"), tuple.getValueByField("away"), tuple.getValueByField("sentiment"))); }
From source file:nyu.twitter.lg.FentchTwitter.java
License:Open Source License
public static void invoke() throws Exception { init();/*ww w . j av a 2s .c om*/ // Create table if it does not exist yet if (Tables.doesTableExist(dynamoDB, tableName)) { System.out.println("Table " + tableName + " is already ACTIVE"); } else { // Create a table with a primary hash key named 'name', which holds // a string CreateTableRequest createTableRequest = new CreateTableRequest().withTableName(tableName) .withKeySchema(new KeySchemaElement().withAttributeName("id").withKeyType(KeyType.HASH)) .withAttributeDefinitions(new AttributeDefinition().withAttributeName("id") .withAttributeType(ScalarAttributeType.S)) .withProvisionedThroughput( new ProvisionedThroughput().withReadCapacityUnits(1L).withWriteCapacityUnits(1L)); TableDescription createdTableDescription = dynamoDB.createTable(createTableRequest) .getTableDescription(); System.out.println("Created Table: " + createdTableDescription); // Wait for it to become active System.out.println("Waiting for " + tableName + " to become ACTIVE..."); Tables.waitForTableToBecomeActive(dynamoDB, tableName); } ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("Emwo2pG").setOAuthConsumerSecret("RM9B7fske5T") .setOAuthAccessToken("19ubQOirq").setOAuthAccessTokenSecret("Lbg3C"); final TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance(); StatusListener listener = new StatusListener() { @Override public void onStatus(Status status) { if (status.getGeoLocation() != null && status.getPlace() != null) { // if (count == 0) { // count++; // } // latitude = status.getGeoLocation().getLatitude(); longtitude = status.getGeoLocation().getLongitude(); place = status.getPlace().getCountry() + "," + status.getPlace().getFullName(); date = status.getCreatedAt().toString(); id = Integer.toString(count); name = status.getUser().getScreenName(); message = status.getText(); System.out.println("---------------------------"); System.out.println("ID:" + count); System.out.println("latitude:" + latitude); System.out.println("longtitude:" + longtitude); System.out.println("place:" + place); System.out.println("name:" + name); System.out.println("message:" + message); System.out.println("data:" + date); System.out.println("-------------8-------------"); insertDB(id, count, name, longtitude, latitude, place, message, date); if (++count > 100) { twitterStream.shutdown(); System.out.println("Information Collection Completed"); } // count = (count+1) % 101; } } @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:nz.net.speakman.android.dreamintweets.twitterstream.TwitterStreamAdapter.java
License:Apache License
private Spanned getTweetTimestamp(Status tweet) { Date tweetTime = tweet.getCreatedAt(); Date now = new Date(); Date difference = new Date(now.getTime() - tweetTime.getTime()); long diff = difference.getTime() / 1000; String timestamp;/* w w w .ja v a 2s. c o m*/ if (diff <= 0) { timestamp = mDream.getString(R.string.tweet_timestamp_just_now); } else if (diff / (24 * 60 * 60) > 0) { diff = diff / (24 * 60 * 60); if (diff > 1) timestamp = mDream.getString(R.string.tweet_timestamp_x_days_ago, diff); else timestamp = mDream.getString(R.string.tweet_timestamp_1_day_ago); } else if (diff / (60 * 60) > 0) { diff = diff / (60 * 60); if (diff > 1) timestamp = mDream.getString(R.string.tweet_timestamp_x_hours_ago, diff); else timestamp = mDream.getString(R.string.tweet_timestamp_1_hour_ago); } else if (diff / 60 > 0) { diff = diff / 60; if (diff > 1) timestamp = mDream.getString(R.string.tweet_timestamp_x_minutes_ago, diff); else timestamp = mDream.getString(R.string.tweet_timestamp_1_minute_ago); } else { if (diff > 1) timestamp = mDream.getString(R.string.tweet_timestamp_x_seconds_ago, diff); else timestamp = mDream.getString(R.string.tweet_timestamp_1_second_ago); } return Html.fromHtml(getClickableUrl(getTweetUrl(tweet), timestamp)); }
From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java
/** * Entry point for a Lappsgrid service./*from www . ja v a 2s. co m*/ * <p> * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container} * payload. * <p> * Errors and exceptions that occur during processing should be wrapped in a {@code Data} * object with the discriminator set to http://vocab.lappsgrid.org/ns/error * <p> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br /> * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br /> * * @param input A JSON string representing a Data object * @return A JSON string containing a Data object with a Container payload. */ @Override public String execute(String input) { Data<String> data = Serializer.parse(input, Data.class); String discriminator = data.getDiscriminator(); // Return ERRORS back if (Discriminators.Uri.ERROR.equals(discriminator)) { return input; } // Generate an error if the used discriminator is wrong if (!Discriminators.Uri.GET.equals(discriminator)) { return generateError( "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator); } Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false) .build(); // Authentication using saved keys Twitter twitter = new TwitterFactory(config).getInstance(); String key = readProperty(KEY_PROPERTY); if (key == null) { return generateError("The Twitter Consumer Key property has not been set."); } String secret = readProperty(SECRET_PROPERTY); if (secret == null) { return generateError("The Twitter Consumer Secret property has not been set."); } twitter.setOAuthConsumer(key, secret); try { twitter.getOAuth2Token(); } catch (TwitterException te) { String errorData = generateError(te.getMessage()); logger.error(errorData); return errorData; } // Get query String from data payload Query query = new Query(data.getPayload()); // Set the type to Popular or Recent if specified // Results will be Mixed by default. if (data.getParameter("type") == "Popular") query.setResultType(Query.POPULAR); if (data.getParameter("type") == "Recent") query.setResultType(Query.RECENT); // Get lang string String langCode = (String) data.getParameter("lang"); // Verify the validity of the language code and add it to the query if it's valid if (validateLangCode(langCode)) query.setLang(langCode); // Get date strings String sinceString = (String) data.getParameter("since"); String untilString = (String) data.getParameter("until"); // Verify the format of the date strings and set the parameters to query if correctly given if (validateDateFormat(untilString)) query.setUntil(untilString); if (validateDateFormat(sinceString)) query.setSince(sinceString); // Get GeoLocation if (data.getParameter("address") != null) { String address = (String) data.getParameter("address"); double radius = (double) data.getParameter("radius"); if (radius <= 0) radius = 10; Query.Unit unit = Query.MILES; if (data.getParameter("unit") == "km") unit = Query.KILOMETERS; GeoLocation geoLocation; try { double[] coordinates = getGeocode(address); geoLocation = new GeoLocation(coordinates[0], coordinates[1]); } catch (Exception e) { String errorData = generateError(e.getMessage()); logger.error(errorData); return errorData; } query.geoCode(geoLocation, radius, String.valueOf(unit)); } // Get the number of tweets from count parameter, and set it to default = 15 if not specified int numberOfTweets; try { numberOfTweets = (int) data.getParameter("count"); } catch (NullPointerException e) { numberOfTweets = 15; } // Generate an ArrayList of the wanted number of tweets, and handle possible errors. // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed ArrayList<Status> allTweets; Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter); String tweetsDataDisc = tweetsData.getDiscriminator(); if (Discriminators.Uri.ERROR.equals(tweetsDataDisc)) return tweetsData.asPrettyJson(); else { allTweets = (ArrayList<Status>) tweetsData.getPayload(); } // Initialize StringBuilder to hold the final string StringBuilder builder = new StringBuilder(); // Append each Status (each tweet) to the initialized builder for (Status status : allTweets) { String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : " + status.getText() + "\n"; builder.append(single); } // Output results Container container = new Container(); container.setText(builder.toString()); Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container); return output.asPrettyJson(); }
From source file:org.anhonesteffort.ads.twitter.TweetModel.java
License:Open Source License
public TweetModel(Status status) { id = status.getId();//from w w w . j ava 2s . c o m timeMs = status.getCreatedAt().getTime(); handle = status.getUser().getScreenName(); accountPic = status.getUser().getProfileImageURLHttps(); text = status.getText(); }