List of usage examples for twitter4j Status getCreatedAt
Date getCreatedAt();
From source file:sentinets.ParseTweet.java
License:Open Source License
public ParseTweet(Status tweet) { this(tweet.getText()); this.tweet = tweet; this.url = "http://twitter.com/" + tweet.getUser().getScreenName() + "/status/" + tweet.getId(); this.user = tweet.getUser().getScreenName(); this.published_date = tweet.getCreatedAt().toString(); }
From source file:Situational_Awareness.TwitterSearch.java
public ArrayList<Information> twitterFeed(String twitterURL) { ArrayList<Information> informationList = new ArrayList<>(); try {/*from w w w . j a v a 2 s . com*/ Query query = new Query(twitterURL); QueryResult result; result = twitter.search(query); List<Status> tweets = result.getTweets(); for (Status tweet : tweets) { System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText()); Date tweeted = tweet.getCreatedAt(); if (tweeted.getTime() >= java.lang.System.currentTimeMillis() - 36000000) { Information newInfo = new Information(tweet.getId(), tweet.getUser().getScreenName(), tweet.getText(), tweet.getUser().getLocation(), tweet.getUser().getProfileImageURL()); informationList.add(newInfo); } else { System.out.println("information not relevant"); } } } catch (Exception te) { System.out.println("Failed to search tweets: " + te.getMessage()); } return informationList; }
From source file:socialImport.twitter.TweetToDatabaseImportListener.java
License:Open Source License
@Override public void onStatus(Status status) { Date dateOfCreation = status.getCreatedAt(); String authorName = status.getUser().getName(); Gender gender = Gender.unknown;/*from w ww . jav a2 s. com*/ int yearOfBirth = -1; Author author = new Author(authorName, gender, yearOfBirth); GeoTag geoTag = null; Place place = status.getPlace(); GeoLocation[][] geoLocation = null; if (place != null) { geoLocation = place.getBoundingBoxCoordinates(); } if (geoLocation != null) { float latitude = 0; float longitude = 0; int noOfCoordinates = geoLocation[0].length; for (int i = 0; i < noOfCoordinates; i++) { latitude += geoLocation[0][i].getLatitude(); longitude += geoLocation[0][i].getLongitude(); } latitude = latitude / noOfCoordinates; longitude = longitude / noOfCoordinates; geoTag = new GeoTag(latitude, longitude); } String postText = status.getText(); long retweetCount = status.getRetweetCount(); TweetPost tweet = new TweetPost(streamDescriptor, dateOfCreation, author, geoTag, postText, retweetCount); System.out.println(author); System.out.println(geoTag); System.out.println(status.getText()); dataModule.savePost(tweet); }
From source file:source.TwitterSource.java
License:Apache License
/** * Start processing events. This uses the Twitter Streaming API to sample * Twitter, and process tweets.//w ww . ja va2s .c o m */ @Override public void start() { // The channel is the piece of Flume that sits between the Source and // Sink, and is used to process events final ChannelProcessor channel = getChannelProcessor(); final Map<String, String> headers = new HashMap<String, String>(); // The StatusListener is a twitter4j API, which can be added to a // Twitter stream, and will execute methods every time a message comes // in through the stream StatusListener listener = new StatusListener() { // The onStatus method is executed every time a new tweet comes in public void onStatus(Status status) { // The EventBuilder is used to build an event using the headers // and the raw JSON of a tweet logger.debug(status.getUser().getScreenName() + ": " + status.getText()); headers.put("timestamp", String.valueOf(status.getCreatedAt().getTime())); Event event = EventBuilder.withBody(DataObjectFactory.getRawJSON(status).getBytes(), headers); channel.processEvent(event); } // This listener will ignore everything except for new tweets public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) { } public void onTrackLimitationNotice(int numberOfLimitedStatuses) { } public void onScrubGeo(long userId, long upToStatusId) { } public void onException(Exception ex) { } public void onStallWarning(StallWarning warning) { } }; logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}", new String[] { consumerKey, accessToken }); // Set up the stream's listener (defined above), and set any necessary // security information twitterStream.addListener(listener); // Set up a filter to pull out industry-relevant tweets logger.debug("Starting up Twitter filtering..."); FilterQuery query = new FilterQuery().count(0); if (locations == null) { logger.debug("No locations specified"); } else { String debugString = "Locations specified: "; debugString += "SW={" + locations[0][0] + ", " + locations[0][1] + "}, "; debugString += "NE={" + locations[1][0] + ", " + locations[1][1] + "}"; logger.debug(debugString); query.locations(locations); } if (keywords == null) { logger.debug("No keywords specified"); } else { String debugString = keywords.length + " keywords specified: "; for (int i = 0; i < keywords.length; i++) { debugString += keywords[i]; if (i != keywords.length - 1) { debugString += ", "; } } logger.debug(debugString); query.track(keywords); } twitterStream.filter(query); super.start(); }
From source file:t.twitter.TTwitterModule.java
License:Open Source License
@Kroll.method public void connect(HashMap args) { KrollDict arg = new KrollDict(args); ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey(arg.optString("apikey", "")) .setOAuthConsumerSecret(arg.optString("apisecret", "")) .setOAuthAccessToken(arg.optString("accesstoken", "")) .setOAuthAccessTokenSecret(arg.optString("accesssecret", "")); AsyncTwitterFactory tf = new AsyncTwitterFactory(cb.build()); twitter = tf.getInstance();/*from w w w . ja v a2 s .co m*/ twitter.addListener(new TwitterAdapter() { @Override public void updatedStatus(Status status) { Log.d("Twitter", "text: " + status.getText()); } @Override public void searched(QueryResult result) { HashMap<String, KrollDict[]> event = new HashMap<String, KrollDict[]>(); List<Status> tweets = result.getTweets(); KrollDict[] dList = new KrollDict[tweets.size()]; // sort tweets Collections.sort(tweets, new Comparator<Status>() { public int compare(Status o1, Status o2) { if (desc) { if (o2.getId() < o1.getId()) { return 1; } else { return -1; } } else { if (o2.getId() > o1.getId()) { return 1; } else { return -1; } } } }); // return tweets to titanium int i = 0; for (Status tweet : tweets) { if (lastID == -1 || lastID < tweet.getId()) { KrollDict d = new KrollDict(); d.put("username", tweet.getUser().getScreenName()); d.put("userimage", tweet.getUser().getProfileImageURL()); d.put("text", tweet.getText()); d.put("date", tweet.getCreatedAt()); d.put("id", Long.toString(tweet.getId())); dList[i] = d; lastID = tweet.getId(); i++; } } KrollDict[] dList2 = new KrollDict[i]; // shorten array System.arraycopy(dList, 0, dList2, 0, i); event.put("tweets", dList2); success.call(getKrollObject(), event); synchronized (LOCK) { LOCK.notify(); } } @Override public void verifiedCredentials(User user) { HashMap<String, KrollDict> event = new HashMap<String, KrollDict>(); KrollDict d = new KrollDict(); d.put("user_name", user.getName()); d.put("screen_name", user.getScreenName()); d.put("image_path", user.getProfileImageURL()); event.put("user_info", d); success.call(getKrollObject(), event); synchronized (LOCK) { LOCK.notify(); } } @Override public void onException(TwitterException e, TwitterMethod method) { synchronized (LOCK) { LOCK.notify(); } Log.e("twitter", "error: " + e.getErrorMessage()); } }); Log.d("Twitter", "connected"); }
From source file:teambootje.TwitterAPI.java
public static void timeline() throws TwitterException, SQLException { Twitter twitter = TwitterFactory.getSingleton(); Query query = new Query("ssrotterdam"); query.setCount(100);/*from w ww . j av a2 s.com*/ /** ** setSince kan alleen tot 7 dagen terug worden gebruikt*** */ QueryResult result = twitter.search(query); for (Status status : result.getTweets()) { if (status.getPlace() != null) { cityVar = status.getPlace().getName(); countryVar = status.getPlace().getCountry(); } else { countryVar = null; cityVar = null; } java.util.Date utilDate = status.getCreatedAt(); java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime()); date = sqlDate; post = status.getText(); screenName = status.getUser().getScreenName(); try { ImportIntoSQL.TwitterImport(); } catch (SQLException e) { e.printStackTrace(); } } }
From source file:testtweet.TweetUsingTwitter4jExample.java
/** * @param args the command line arguments *///from w ww .j a va2 s .c o m public static void main(String[] args) throws IOException, TwitterException { //Instantiate a re-usable and thread-safe factory TwitterFactory twitterFactory = new TwitterFactory(Data.getConf().build()); //Instantiate a new Twitter instance Twitter twitter = twitterFactory.getInstance(); /* //setup OAuth Consumer Credentials twitter.setOAuthConsumer(consumerKey, consumerSecret); //setup OAuth Access Token twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret)); */ //Instantiate and initialize a new twitter status update StatusUpdate statusUpdate = new StatusUpdate( //your tweet or status message "Twitter API #Hacked"); //attach any media, if you want to /* statusUpdate.setMedia( //title of media "http://h1b-work-visa-usa.blogspot.com" , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream()); */ //tweet or update status Status status = twitter.updateStatus(statusUpdate); //response from twitter server 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.getRateLimitStatus().getRemainingHits() = " + status.getRateLimitStatus().getRemaining()); } System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities())); System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities())); }
From source file:toninbot.ToninStatusListener.java
@Override public void onStatus(Status tweetRecibido) { if (tweetRecibido.getUser().getId() != 184742273L && tweetRecibido.getUser().getId() != 2841338087L) { return;/*w w w .j a va2 s . co m*/ } System.out.println(tweetRecibido.getUser().getName() + " " + tweetRecibido.getText()); Calendar cal = Calendar.getInstance(); cal.setTime(tweetRecibido.getCreatedAt()); long hora = cal.get(Calendar.HOUR_OF_DAY); System.out.println("Hora: " + cal.get(Calendar.HOUR_OF_DAY)); //comprobar la hora if (hora > 7 || hora < 1) { return; } //comprobar que no sea una respuesta a alguien if (tweetRecibido.getText().contains("@")) { return; } StatusUpdate stat = new StatusUpdate( "@" + tweetRecibido.getUser().getScreenName() + " " + respuestaRandom()); System.out.println("Fora de horario!"); stat.inReplyToStatusId(tweetRecibido.getId()); try { twitter.updateStatus(stat); System.out.println("Twitteado: " + stat.toString()); } catch (TwitterException ex) { System.out.println("Error"); } }
From source file:traffickarmasent.newgetpage.java
public static void main(String[] args) throws IOException { // gets Twitter instance with default credentials Twitter twitter = new TwitterFactory().getInstance(); try {/*from w w w . jav a2 s . c om*/ ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true); cb.setOAuthConsumerKey("GPtsu5cjC08KTOEojEoaHw"); cb.setOAuthConsumerSecret("SsgeXn73bN4CXUYtJfEdKOwBxVTmAEPvmFo3q2CX45w"); cb.setOAuthAccessToken("154196958-J1Gqy86jmQ6YSoFVVq69bmbJB0acGxiDEocxtvre"); cb.setOAuthAccessTokenSecret("DpTJr3huuDy2qMwsCMgsTn5yNbi0oQzSDGhDDWQsLog"); TwitterFactory tf = new TwitterFactory(cb.build()); Twitter twitter1 = tf.getInstance(); List<Status> statuses; String user; String[] users = { "livetrafficsyd", "trafficnsw", "sydtraffic_cs", "WazeTrafficSYD", "livetrafficnsw" }; Date[] d_users = { new Date(99, 2, 12), new Date(99, 2, 12), new Date(99, 2, 12), new Date(99, 2, 12), new Date(99, 2, 12) }; while (true) { for (int i = 0; i < users.length; i++) { statuses = twitter1.getUserTimeline(users[i]); for (int j = statuses.size() - 1; j >= 0; j--) { Status st = statuses.get(j); if (d_users[i].before(st.getCreatedAt())) { String message = removeUrl(st.getText()); File file = new File("out_sydney_new.txt"); //if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } //true = append file FileWriter fileWritter = new FileWriter(file.getName(), true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(message + "\n"); bufferWritter.close(); System.out.println("Done"); System.out.println("@" + st.getUser().getScreenName() + " - " + st.getText()); d_users[i] = st.getCreatedAt(); } } } try { Thread.sleep(300000); //1000 milliseconds is one second. } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } System.out.println("firse"); } } catch (TwitterException te) { te.printStackTrace(); System.out.println("Failed to get timeline: " + te.getMessage()); System.exit(-1); } }
From source file:trendulo.ingest.twitter.TwitterFileStringSequenceSource.java
License:Apache License
public TemporalStringSequence nextStringSequence() { TemporalStringSequence temporalStringSequence = null; String line = null;//from w w w . j a v a 2 s .co m Status status = null; boolean statusAccepted = false; // Read a line from the file and serialize the JSON string into a Status object try { do { line = bufferedReader.readLine(); if (line != null) { status = DataObjectFactory.createStatus(line); // if the user has specified a StatusFilter, check to see if the Status object // is accepted. If not, we will continue around the loop if (statusFilter != null) { if (statusFilter.accept(status)) { statusAccepted = true; } } // Every status is accepted if there is no filter else { statusAccepted = true; } } } while (line != null && statusAccepted == false); } catch (IOException e) { log.error("Error reading from file: " + twitterFilePath, e); } catch (TwitterException e) { log.error("Error parsing JSON status string: " + line, e); } if (status != null && statusAccepted == true) { temporalStringSequence = new TemporalStringSequence(status.getText(), status.getCreatedAt().getTime()); } return temporalStringSequence; }