List of usage examples for twitter4j Status getCreatedAt
Date getCreatedAt();
From source file:TimeLine.java
private void btTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTwitActionPerformed // Tombol update status, show setelah update txtStatus.setText(""); TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();/* www. j av a2 s .c o m*/ try { Status status = twitter.updateStatus(txStatus.getText()); JOptionPane.showMessageDialog(rootPane, "Twit \n [ " + status.getText() + " ]\nTerkirim!"); } catch (TwitterException ex) { JOptionPane.showMessageDialog(rootPane, "Tidak bisa mengirim : " + ex.getMessage()); Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex); } List<Status> statuses = null; try { statuses = twitter.getUserTimeline(); statuses.stream().forEach((status) -> { txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - " + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n"); }); txStatus.setText(""); //reload field } catch (TwitterException te) { JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage()); } }
From source file:MapDemo.java
public static void main(String[] args) throws TwitterException, IOException, Exception { TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();/* w w w . j a v a 2s . c o m*/ boolean flag = true; // Ask the user for a search string. String searchStr = "ParkandGoUNL"; // Create a Query object. Query query = new Query(searchStr); // Send API request to execute a search with the given query. QueryResult result = twitter.search(query); // Display search results. result.getTweets().stream().forEach((Status status) -> { System.out.println("\n" + status.getText() + status.getCreatedAt()); }); if (flag) { GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y"); List<Marker> markers = new ArrayList<>(); Marker e = new Marker(GeocodingApi.geocode(context, "616 North 16th Street, Lincoln, Nebraska, USA") .await()[0].geometry.location, "marker1", "KKG", new Date()); markers.add(e); StreetExtractor se = new StreetExtractor(); List<Address> address = se.find("Park and Go 601 North 16th Street"); address.forEach(((Address a) -> { try { Marker m = new Marker( GeocodingApi.geocode(context, a.getAddress()).await()[0].geometry.location, "marker0", "A Tweet", new Date()); markers.add(m); } catch (Exception ex) { Logger.getLogger(MapDemo.class.getName()).log(Level.SEVERE, null, ex); } })); Map map = new Map(markers); map.create(); } }
From source file:TweetMapManager.java
public static void main(String[] args) { TwitterFactory tf = new TwitterFactory(); Twitter twitter = tf.getInstance();// w ww. j a v a 2s .com String searchStr = "#ParkandGoUNL"; Query query = new Query(searchStr); GeoApiContext context = new GeoApiContext().setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y"); List<Marker> markers = new LinkedList<>(); StreetExtractor se = new StreetExtractor(); LocalTime now = LocalTime.now(); while (true) { DayOfWeek today = LocalDate.now().getDayOfWeek(); if (today.getValue() < WEEKEND) { if (now.isAfter(STARTTIME) && now.isBefore(ENDTIME)) { // Send API request to execute a search with the given query. QueryResult results = null; try { results = twitter.search(query); } catch (TwitterException ex) { LOGGER.warn(ex.getMessage()); } // Display search results. if (results != null) { results.getTweets().stream().forEach((Status status) -> { try { Date created = status.getCreatedAt(); String text = status.getText(); LOGGER.info(status.getText()); LatLng location; if (status.getGeoLocation() != null) { location = new LatLng(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()); } else { String modified = text.replace("#ParkAndGoUNL", ""); List<Address> address = se.find(modified); location = GeocodingApi.geocode(context, address.get(0).getAddress()) .await()[0].geometry.location; } String id = UUID.randomUUID().toString().substring(0, 8); Marker m = new Marker(location, "m" + id, text, created); markers.add(m); } catch (Exception ex) { LOGGER.warn(ex.getMessage()); } }); } if (!markers.isEmpty()) { Marker m = markers.get(markers.size() - 1); if (m.getTimestamp().getTime() < Time.valueOf(now.minusMinutes(30)).getTime()) { DailyLogs.addMarkerToLog(m, today); markers.remove(m); } } Map map = new Map(markers); map.create(); } else { //wait 5 hours try { LOGGER.info("Sleeping 5 hours"); Thread.sleep((long) 1.8e+7); } catch (InterruptedException ex) { LOGGER.warn(ex.getMessage()); } } now = LocalTime.now(); } else { try { //Wait a day LOGGER.info("Sleeping 1 day"); Thread.sleep((long) 8.64e+7); } catch (InterruptedException ex) { LOGGER.warn(ex.getMessage()); } } try { LOGGER.info("Successful Loop, Resting"); Thread.sleep(1000); } catch (InterruptedException ex) { LOGGER.warn(ex.getMessage()); } } }
From source file:GetLiveMedia.java
License:Open Source License
public void TweetCollect(String searchString) throws TwitterException { tXCoord = 0;//from w ww .ja v a 2 s. co m tYCoord = 0; ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setDebugEnabled(true).setOAuthConsumerKey("0c1v1wqqNATaVcWpINaHoW3o5") .setOAuthConsumerSecret("a6sEAJ1NLY3cXhkMTrMZF62bIfww6qLvlEetDAU9O09Mp04lyh") .setOAuthAccessToken("330427831-RJig6B6YycJL3xQVoEjjyRaujwnr1xHEQGtSHOOc") .setOAuthAccessTokenSecret("Da71qk4SN6Nu88mLkugDDR6CftVcgOcz3QB8dHNw4hVbD"); TwitterFactory tf = new TwitterFactory(cb.build()); twitter = tf.getInstance(); query = new Query("#" + searchString); result = twitter.search(query); for (Status status : result.getTweets()) { try { System.out.println(status.getGeoLocation()); System.out.println(status.getCreatedAt()); tXCoord = status.getGeoLocation().getLatitude(); tYCoord = status.getGeoLocation().getLongitude(); twitterString = ("@" + status.getUser().getScreenName() + ": " + status.getText() + " : " + "(" + tXCoord + ", " + tYCoord + ")"); twitterURL = "https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId(); } catch (Exception e) { } } }
From source file:MyUpdateTweetTimeToDB.java
public void GetTweetTime() { Twitter twitter = new TwitterFactory().getInstance(); String CONSUMER_KEY = "4enxNevEGWMqBuKzcJoQ"; String CONSUMER_SECRET = "UUDCNSvkFoZRaRUV4b8eHBcgR2N1LSrHXX7IELxdIk"; String TWITTER_TOKEN = "470084145-qwjAlIxq7GFB1I62TO5ebyoO10tXgUuZJfgTLu7G"; String TWITTER_TOKEN_SECRET = "9y47ww1xk0Nc5DhL9ZW0HOC6Qoig2wP101tOjsERnqNNv"; twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET); AccessToken accesstoken = new AccessToken(TWITTER_TOKEN, TWITTER_TOKEN_SECRET); twitter.setOAuthAccessToken(accesstoken); Iterator iterator = tweet_id_to_time.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry pair = (Map.Entry) iterator.next(); try {// w ww .j a v a 2 s . c o m Status status = twitter.showStatus((long) pair.getKey()); if (status == null) { System.out.println("Doesnot exist twitter with tweet id : " + pair.getKey()); } else { tweet_id_to_time.put((Long) pair.getKey(), status.getCreatedAt().getTime()); } } catch (TwitterException e) { tweet_id_to_time.put((Long) pair.getKey(), 1L); e.printStackTrace(); } System.out.println("Id : " + pair.getKey() + "value " + pair.getValue()); } }
From source file:CollectAndPredict.java
public static void main(String[] args) { //StreamingExamples.setStreamingLogLevels(); // Set logging level if log4j not configured (override by adding log4j.properties to classpath) if (!Logger.getRootLogger().getAllAppenders().hasMoreElements()) { Logger.getRootLogger().setLevel(Level.WARN); }/* w w w . ja v a 2 s. c o m*/ String OAuthConsumerKey = "QxeynbXmN93DuNiZKkYfZcS2o"; String OAuthConsumerSecret = "2rAzjerHeW6sIgeDim0A77iGaRn9O683m0DrTbBhaoIuRRq7oU"; String OAuthAccessToken = "825094416935297025-jCegwA25yj3QxF2rHeJ5hRoVu86AfaY"; String OAuthAccessTokenSecret = "CwfNmGcWHoL8qvr5dWDdknYM4k4KvAZc7XlGZuYl2DcR8"; String[] filters = Arrays.copyOfRange(args, 0, args.length); // Set the system properties so that Twitter4j library used by Twitter stream // can use them to generate OAuth credentials System.setProperty("twitter4j.oauth.consumerKey", OAuthConsumerKey); System.setProperty("twitter4j.oauth.consumerSecret", OAuthConsumerSecret); System.setProperty("twitter4j.oauth.accessToken", OAuthAccessToken); System.setProperty("twitter4j.oauth.accessTokenSecret", OAuthAccessTokenSecret); SparkConf sparkConf = new SparkConf().setAppName("JavaTwitterHashTagJoinSentiments"); // check Spark configuration for master URL, set it to local if not configured if (!sparkConf.contains("spark.master")) { sparkConf.setMaster("local[2]"); } SparkSession spark = SparkSession.builder().appName("teste2").config(sparkConf).getOrCreate(); JavaStreamingContext jssc = new JavaStreamingContext(new JavaSparkContext(spark.sparkContext()), Seconds.apply(30)); TokenizerFactory tokFactory = TwitterTokenizerFactory.getTokFactory(); NaiveBayesModel model = NaiveBayesModel.load(spark.sparkContext(), "Docker/myNaiveBayesModel"); HashingTF hashingTF = new HashingTF(1000); JavaReceiverInputDStream<Status> stream = TwitterUtils.createStream(jssc, filters); JavaDStream<Tweet> statuses = stream.map((Status status) -> new Tweet() .addUser(new TwitterUser().addID(status.getUser().getId()).addName(status.getUser().getName()) .addLocation(status.getUser().getLocation()).addDateSignin(status.getUser().getCreatedAt()) .addCountTweets(status.getUser().getStatusesCount()) .addCountFavorites(status.getUser().getFavouritesCount()) .addCountFriends(status.getUser().getFriendsCount()) .addCountFollowers(status.getUser().getFollowersCount())) .addText(status.getText()).addID(status.getId()).addDate(status.getCreatedAt()) .addLatitude( status.getGeoLocation() != null ? status.getGeoLocation().getLatitude() : Double.MAX_VALUE) .addLongitude(status.getGeoLocation() != null ? status.getGeoLocation().getLongitude() : Double.MAX_VALUE)); statuses.foreachRDD(new VoidFunction2<JavaRDD<Tweet>, Time>() { long numTweetsCollected = 0; long numTweetsToCollect = 200; @Override public void call(JavaRDD<Tweet> t1, Time t2) throws Exception { List<Tweet> collect = t1.collect(); long count = collect.size(); if (count > 0) { for (Tweet tweet : collect) { String textoSemUrl = URLRemove.remove(tweet.getText()); Vector v = hashingTF.transform(Arrays.asList(tokFactory .tokenizer(textoSemUrl.toCharArray(), 0, textoSemUrl.length()).tokenize())); double predict = model.predict(v); if (predict == 1) { tweet.setClassifier("POSITIVE"); } else { tweet.setClassifier("NEGATIVE"); } } ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter(); try { ow.writeValue( new FileOutputStream(new File("Docker/Twitter" + t2.milliseconds() + ".json")), collect); } catch (Exception ex) { spark.log().error(ex.getMessage(), ex); } numTweetsCollected += count; spark.log().info("coletou :" + numTweetsCollected + " tweets"); if (numTweetsCollected > numTweetsToCollect) { System.exit(0); } } } }); // statuses.foreachRDD(new VoidFunction2<JavaRDD<String>, Time>() { // long numTweetsCollected = 0; // long numTweetsToCollect = 200; // // @Override // public void call(JavaRDD<String> rdd, Time time) throws Exception { // long count = rdd.count(); // if (count > 0) { // JavaRDD<String> outputRDD = rdd.repartition(10); // outputRDD.saveAsTextFile("/Docker/tweets_" + time.milliseconds()); // numTweetsCollected += count; // if (numTweetsCollected > numTweetsToCollect) { // System.exit(0); // } // } // } // }); // JavaDStream<String> words = stream.flatMap(new FlatMapFunction<Status, String>() { // // @Override // public Iterable<String> call(Status t) throws Exception { // return Arrays.asList(t.getText().split(" ")); // } // }); // // JavaDStream<String> hashTags = words.filter(new Function<String, Boolean>() { // @Override // public Boolean call(String word) { // return word.startsWith("#"); // } // }); // // // Read in the word-sentiment list and create a static RDD from it // String wordSentimentFilePath = "streaming-twitter/examples/data/AFINN-111.txt"; // final JavaPairRDD<String, Double> wordSentiments = jssc.sparkContext() // .textFile(wordSentimentFilePath) // .mapToPair(new PairFunction<String, String, Double>() { // @Override // public Tuple2<String, Double> call(String line) { // String[] columns = line.split("\t"); // return new Tuple2<>(columns[0], Double.parseDouble(columns[1])); // } // }); // // JavaPairDStream<String, Integer> hashTagCount = hashTags.mapToPair( // new PairFunction<String, String, Integer>() { // @Override // public Tuple2<String, Integer> call(String s) { // // leave out the # character // return new Tuple2<>(s.substring(1), 1); // } // }); // // JavaPairDStream<String, Integer> hashTagTotals = hashTagCount.reduceByKeyAndWindow( // new Function2<Integer, Integer, Integer>() { // @Override // public Integer call(Integer a, Integer b) { // return a + b; // } // }, new Duration(10000)); // // // Determine the hash tags with the highest sentiment values by joining the streaming RDD // // with the static RDD inside the transform() method and then multiplying // // the frequency of the hash tag by its sentiment value // JavaPairDStream<String, Tuple2<Double, Integer>> joinedTuples // = hashTagTotals.transformToPair(new Function<JavaPairRDD<String, Integer>, JavaPairRDD<String, Tuple2<Double, Integer>>>() { // @Override // public JavaPairRDD<String, Tuple2<Double, Integer>> call( // JavaPairRDD<String, Integer> topicCount) { // return wordSentiments.join(topicCount); // } // }); // // JavaPairDStream<String, Double> topicHappiness = joinedTuples.mapToPair( // new PairFunction<Tuple2<String, Tuple2<Double, Integer>>, String, Double>() { // @Override // public Tuple2<String, Double> call(Tuple2<String, Tuple2<Double, Integer>> topicAndTuplePair) { // Tuple2<Double, Integer> happinessAndCount = topicAndTuplePair._2(); // return new Tuple2<>(topicAndTuplePair._1(), // happinessAndCount._1() * happinessAndCount._2()); // } // }); // // JavaPairDStream<Double, String> happinessTopicPairs = topicHappiness.mapToPair( // new PairFunction<Tuple2<String, Double>, Double, String>() { // @Override // public Tuple2<Double, String> call(Tuple2<String, Double> topicHappiness) { // return new Tuple2<>(topicHappiness._2(), // topicHappiness._1()); // } // }); // // JavaPairDStream<Double, String> happiest10 = happinessTopicPairs.transformToPair( // new Function<JavaPairRDD<Double, String>, JavaPairRDD<Double, String>>() { // @Override // public JavaPairRDD<Double, String> call( // JavaPairRDD<Double, String> happinessAndTopics) { // return happinessAndTopics.sortByKey(false); // } // } // ); // // // Print hash tags with the most positive sentiment values // happiest10.foreachRDD(new VoidFunction<JavaPairRDD<Double, String>>() { // @Override // public void call(JavaPairRDD<Double, String> happinessTopicPairs) { // List<Tuple2<Double, String>> topList = happinessTopicPairs.take(10); // System.out.println( // String.format("\nHappiest topics in last 10 seconds (%s total):", // happinessTopicPairs.count())); // for (Tuple2<Double, String> pair : topList) { // System.out.println( // String.format("%s (%s happiness)", pair._2(), pair._1())); // } // } // }); jssc.start(); try { jssc.awaitTermination(); } catch (InterruptedException e) { e.printStackTrace(); } }
From source file:ac.simons.tweetarchive.tweets.TweetStorageService.java
License:Apache License
@Transactional public TweetEntity store(final Status status, final String rawContent) { final Optional<TweetEntity> existingTweet = this.tweetRepository.findOne(status.getId()); if (existingTweet.isPresent()) { final TweetEntity rv = existingTweet.get(); log.warn("Tweet with status {} already existed...", rv.getId()); return rv; }/* ww w .ja v a 2 s . c o m*/ final TweetEntity tweet = new TweetEntity(status.getId(), status.getUser().getId(), status.getUser().getScreenName(), status.getCreatedAt().toInstant().atZone(ZoneId.of("UTC")), extractContent(status), extractSource(status), rawContent); tweet.setCountryCode(Optional.ofNullable(status.getPlace()).map(Place::getCountryCode).orElse(null)); if (status.getInReplyToStatusId() != -1L && status.getInReplyToUserId() != -1L && status.getInReplyToScreenName() != null) { tweet.setInReplyTo(new InReplyTo(status.getInReplyToStatusId(), status.getInReplyToScreenName(), status.getInReplyToUserId())); } tweet.setLang(status.getLang()); tweet.setLocation(Optional.ofNullable(status.getGeoLocation()) .map(g -> new TweetEntity.Location(g.getLatitude(), g.getLongitude())).orElse(null)); // TODO Handle quoted tweets return this.tweetRepository.save(tweet); }
From source file:adapter.TwitterAllAdapter.java
License:Apache License
@Override public void run() { while (true) { try {/* w ww . j ava 2s . com*/ Status status = this.messageQueue.take(); Event event = new Event(); int rtCount = 0; int fvCount = 0; if (status.isRetweet()) { rtCount = status.getRetweetedStatus().getRetweetCount(); fvCount = status.getRetweetedStatus().getFavoriteCount(); } Tweet tweet = new Tweet(status.getId(), status.getText(), status.getCreatedAt(), status.getPlace(), status.getUser().getScreenName(), status.getUser().getLang(), status.getUser().getFollowersCount(), status.getUser().getFriendsCount(), status.getHashtagEntities(), fvCount, rtCount, status.getGeoLocation()); //status.getRetweetedStatus().getRetweetCount(), status.getGeoLocation()); eventCount++; // cantReplicas: Cantidad de PEs que se quieren generar para el proximo operador // Nota: recuerden que la topologa no necesariamente deba ser de este estilo // tambin poda ser por un hash int cantReplicas = 10; event.put("levelTweet", Integer.class, eventCount % cantReplicas); event.put("id", Integer.class, eventCount); event.put("tweet", Tweet.class, tweet); getRemoteStream().put(event); } catch (Exception e) { logger.error("Error: " + e); logger.error("Error al crear evento"); } } }
From source file:adapter.TwitterKeywordsAdapter.java
License:Apache License
@Override public void run() { while (true) { try {/*from w w w. jav a 2s.com*/ Status status = this.messageQueue.take(); Event event = new Event(); Tweet tweet = new Tweet(status.getId(), status.getText(), status.getCreatedAt(), status.getPlace(), status.getUser().getScreenName(), status.getUser().getLang(), status.getUser().getFollowersCount(), status.getUser().getFriendsCount(), status.getHashtagEntities(), status.getFavoriteCount(), status.getRetweetCount(), status.getGeoLocation()); eventCount++; // cantReplicas: Cantidad de PEs que se quieren generar para el proximo operador // Nota: recuerden que la topologa no necesariamente deba ser de este estilo // tambin poda ser por un hash int cantReplicas = 10; event.put("levelTweet", Integer.class, eventCount % cantReplicas); event.put("id", Integer.class, eventCount); event.put("tweet", Tweet.class, tweet); getRemoteStream().put(event); } catch (Exception e) { logger.error("Error: " + e); logger.error("Error al crear evento"); } } }
From source file:adapter.TwitterLanguageAdapter.java
License:Apache License
@Override public void run() { while (true) { try {/*from w w w . j ava 2s . c o m*/ Status status = this.messageQueue.take(); Event event = new Event(); Tweet tweet = new Tweet(status.getId(), status.getText(), status.getCreatedAt(), status.getPlace(), status.getUser().getScreenName(), status.getUser().getLang(), status.getUser().getFollowersCount(), status.getUser().getFriendsCount(), status.getHashtagEntities(), status.getFavoriteCount(), status.getRetweetCount(), status.getGeoLocation()); eventCount++; // cantReplicas: Cantidad de PEs que se quieren generar para el proximo operador // Nota: recuerden que la topologa no necesariamente deba ser de este estilo // tambin poda ser por un hash int cantReplicas = 10; event.put("levelTweet", Integer.class, eventCount % cantReplicas); event.put("id", Integer.class, eventCount); event.put("tweet", Tweet.class, tweet); getRemoteStream().put(event); } catch (Exception e) { logger.error("Error: " + e); logger.error("Error al crear evento"); } } }