Example usage for twitter4j Status getLang

List of usage examples for twitter4j Status getLang

Introduction

In this page you can find the example usage for twitter4j Status getLang.

Prototype

String getLang();

Source Link

Document

Returns the lang of the status text if available.

Usage

From source file:org.graylog2.inputs.twitter.TwitterCodec.java

License:Open Source License

private Message createMessageFromStatus(final Status status) {
    final Message message = new Message(status.getText(), "twitter.com", new DateTime(status.getCreatedAt()));

    message.addField("facility", "Tweets");
    message.addField("level", 6);
    message.addField("tweet_id", status.getId());
    message.addField("tweet_is_retweet", Boolean.toString(status.isRetweet()));
    message.addField("tweet_favorite_count", status.getFavoriteCount());
    message.addField("tweet_retweet_count", status.getRetweetCount());
    message.addField("tweet_language", status.getLang());

    final GeoLocation geoLocation = status.getGeoLocation();
    if (geoLocation != null) {
        message.addField("tweet_geo_long", geoLocation.getLongitude());
        message.addField("tweet_geo_lat", geoLocation.getLatitude());
    }/*from   w ww  .  ja  va 2s.  c om*/

    final User user = status.getUser();
    if (user != null) {
        message.addField("tweet_url",
                "https://twitter.com/" + user.getScreenName() + "/status/" + status.getId());
        message.addField("user_id", user.getId());
        message.addField("user_name", user.getScreenName());
        message.addField("user_description", user.getDescription());
        message.addField("user_timezone", user.getTimeZone());
        message.addField("user_utc_offset", user.getUtcOffset());
        message.addField("user_location", user.getLocation());
        message.addField("user_language", user.getLang());
        message.addField("user_url", user.getURL());
        message.addField("user_followers", user.getFollowersCount());
        message.addField("user_tweets", user.getStatusesCount());
        message.addField("user_favorites", user.getFavouritesCount());
    }
    return message;
}

From source file:org.rtsa.storm.TwitterSpout.java

License:Apache License

public void open(Map conf, TopologyContext context, SpoutOutputCollector collector) {
    queue = new LinkedBlockingQueue<Status>(1000);
    _collector = collector;// w ww .  j a v a2 s .c  o m

    StatusListener listener = new StatusListener() {

        public void onStatus(Status status) {

            if (status.getText().length() != 0 && status.getLang().equals("en")) {
                queue.offer(status);

            }
        }

        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        public void onTrackLimitationNotice(int i) {
        }

        public void onScrubGeo(long l, long l1) {
        }

        public void onException(Exception ex) {
        }

        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }

    };

    TwitterStream twitterStream = new TwitterStreamFactory(
            new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance();

    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(consumerKey, consumerSecret);
    AccessToken token = new AccessToken(accessToken, accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    if (keyWords.length == 0) {

        twitterStream.sample();
    }

    else {

        FilterQuery query = new FilterQuery().track(keyWords);
        twitterStream.filter(query);
    }

}

From source file:ru.mail.sphere.java_hw5_vasilyev.twitteraccessor.Accessor.java

private static Tweet buildTweetFromStatus(final Status status) {
    return new Tweet(status.getText(), status.getCreatedAt(), status.getFavoriteCount(),
            status.getRetweetCount(), status.getLang());
}

From source file:sentimentanalysis.Twitter.GetTweets.java

public static void main(String args[]) {

    Twitter4JConfig t4jConfig = new Twitter4JConfig();
    ConfigurationBuilder cb = t4jConfig.getConfigurationBuilder();

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();//from  w  ww. jav  a  2s  .co  m
    String keyword = "Trump";

    ArrayList<Post> TweetResultList = new ArrayList<Post>();
    int count = 0;
    try {

        Query query = new Query(keyword + "+exclude:retweets+lang:en").until("2016-11-19");
        QueryResult result;

        do {
            result = twitter.search(query);
            ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();

            for (Status tweet : tweets) {
                count++;

                String user = tweet.getUser().getScreenName();
                String content = tweet.getText();
                Date time = tweet.getCreatedAt();
                System.out.println(time.getTime());
                String tweet_url = "https://twitter.com/" + tweet.getUser().getScreenName() + "/status/"
                        + tweet.getId();
                System.out.println(tweet.getLang());
                Post tr = new Post(user, content, tweet_url, new java.sql.Date(time.getTime()));
                TweetResultList.add(tr);

                //                    System.out.println("[user]@" + tweet.getUser().getScreenName() 
                //                        + "[/user][tweet]" + tweet.getText()+"[/tweet][link]"+tweet_url+"[/link]");
            }

        } while (((query = result.nextQuery()) != null) && (count < 500));

        try {
            SaveToDB.savePosts(TweetResultList);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(GetTweets.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (TwitterException te) {
        te.printStackTrace();
    }

}

From source file:storm.starter.spout.Q2FetchTweetSpout.java

License:Apache License

@Override
public void nextTuple() {
    //Utils.sleep(interval);
    Status ret = queue.poll();
    if (ret == null) {
        Utils.sleep(10);// ww  w .  j  a  v  a2  s  . c  o  m
    } else {
        System.out.println("DEBUG\tFetchTweetSpout\t" + ret.getText());
        if (ret.getLang().equals("en")) {
            Date date = new Date();
            long currTime = date.getTime();
            ArrayList<String> hss = new ArrayList<String>();
            for (HashtagEntity htentity : ret.getHashtagEntities()) {
                hss.add(htentity.getText());
            }
            tweetInfoList.add(new TweetInfo(ret.getUser().getFriendsCount(), hss, ret.getText()));

            if ((currTime - timestamp) > interval) {
                timestamp = currTime;
                sequenceNumber++;
                _collector.emit(new Values(sequenceNumber, tweetInfoList));
                tweetInfoList.clear();
            }
        }
    }
}

From source file:ws.project.languagebasedlexiconanalisys.TwitterStreamAnalizer.java

void parseStream() throws IOException {
    //Inizializza file JSON
    FileWriter file = new FileWriter("data.json");
    JSONObject obj = new JSONObject();
    final JSONArray data = new JSONArray();
    obj.put("data", data);
    file.write(obj.toJSONString());/*from  ww  w .  j  a  v a  2s .  c o m*/
    file.flush();
    file.close();

    SimpleDateFormat currentDate = new SimpleDateFormat();
    currentDate.applyPattern("dd-MM-yyyy");
    final String currentDateStr = currentDate.format(new Date());

    ConfigurationBuilder cfg = new ConfigurationBuilder();
    cfg.setOAuthAccessToken("3065669171-9Hp3VZbz7f0BCsvWWFfgywgqimSIp1AlT98745S");
    cfg.setOAuthAccessTokenSecret("AUmg0AdhHzMXisnP1WV7Wnsw5amWFQPyIojI5aBG5qV4A");
    cfg.setOAuthConsumerKey("arieQRhL2WwgRFfXFLAJp5Hkw");
    cfg.setOAuthConsumerSecret("NvmWqgN1UKKPUWoh9d9Z2PuQobOah8IR5faqX2WjDGBL053sWE");

    StatusListener listener;
    listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            SimpleDateFormat tweetDate = new SimpleDateFormat();
            tweetDate.applyPattern("dd-MM-yyyy");
            String tweetDateStr = tweetDate.format(status.getCreatedAt());

            try {
                indexer.openWriter(currentDateStr);
            } catch (IOException ex) {
                Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
            }

            //CHIUDO se cambio giorno ma non ho raggiunto l'1%
            if (!tweetDateStr.equals(currentDateStr)) {
                try {
                    indexer.closeWriter();
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }
                writeOnJson(currentDateStr);
                System.out.println("Giorno successivo, completato senza aver raggiunto 1%");
                System.exit(0);
            }
            tot_count++;

            if (status.getLang().equals("it")) {
                it_count++;
                try {
                    indexer.addTweet(id, status.getText());
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
            try {
                indexer.closeWriter();
            } catch (IOException ex) {
                Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
        }

        @Override
        public void onTrackLimitationNotice(int i) {
        }

        @Override
        public void onScrubGeo(long l, long l1) {
        }

        @Override
        public void onStallWarning(StallWarning sw) {
        }

        @Override
        public void onException(Exception excptn) {
            TwitterException exc = (TwitterException) excptn;
            if (exc.exceededRateLimitation()) {
                try {
                    indexer.closeWriter();
                } catch (IOException ex) {
                    Logger.getLogger(TwitterStreamAnalizer.class.getName()).log(Level.SEVERE, null, ex);
                }
                writeOnJson(currentDateStr);
                System.out.println("1% raccolto, dati raccolti. Amen");
            }
        }

    };

    TwitterStream twitterStream = new TwitterStreamFactory(cfg.build()).getInstance();
    twitterStream.addListener(listener);

    indexer.addIndex(currentDateStr);
    indexer.openWriter(currentDateStr);
    twitterStream.sample();

}