Example usage for twitter4j Status getText

List of usage examples for twitter4j Status getText

Introduction

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

Prototype

String getText();

Source Link

Document

Returns the text of the status

Usage

From source file:com.sparkexample.TwitterStream.java

License:Apache License

public static void main(String[] args) throws Exception {

    // twitter stuff

    HashMap<String, String> configs = new HashMap<String, String>();
    configs.put("apiKey", "BRPqNoG7WV6ONMWG9C8brmvtl");
    configs.put("apiSecret", "OZ3I4on0JiDQc7HYRsKBeevQC7lG8MBSDSi1yiserj6yTwXFAp");
    configs.put("accessToken", "722309419413991424-IBbz3hhBlroK96qkKexJaFJa3yrcKad");
    configs.put("accessTokenSecret", "UH2H02LP3wV2xw5BOPKfr3lb1rIsKFkmhN1gEqLceuoJX");

    Object[] keys = configs.keySet().toArray();
    for (int k = 0; k < keys.length; k++) {
        String key = keys[k].toString();
        String value = configs.get(key).trim();
        if (value.isEmpty()) {
            throw new Exception("Error setting authentication - value for " + key + " not set");
        }/*from  w w  w  .  j  a  v a2  s .c  o  m*/
        String fullKey = "twitter4j.oauth." + key.replace("api", "consumer");
        System.setProperty(fullKey, value);
    }

    // StreamingExamples.setStreamingLogLevels();
    SparkConf sparkConf = new SparkConf().setAppName("JavaQueueStream").setSparkHome("/root/spark/");
    sparkConf.setMaster("local[4]");
    // Create the context
    JavaStreamingContext ssc = new JavaStreamingContext(sparkConf, new Duration(10000));

    JavaDStream<Status> tweets = TwitterUtils.createStream(ssc);

    JavaDStream<String> statuses = tweets.map(new Function<Status, String>() {
        public String call(Status status) {
            return status.getText();
        }
    });
    statuses.print();
    ssc.start();
}

From source file:com.sstrato.flume.source.TwitterSource.java

License:Apache License

/**
 * Start processing events. This uses the Twitter Streaming API to sample
 * Twitter, and process tweets.//from   w w  w. j  av a2 s .  c o  m
 */
@Override
public void start() {

    // ? ?
    final ChannelProcessor channel = getChannelProcessor();

    final Map<String, String> headers = new HashMap<String, String>();

    // ?  twitter4j? StatusListener   ?   ?. 

    StatusListener listener = new StatusListener() {
        // The onStatus method is executed every time a new tweet comes in.
        public void onStatus(Status status) {
            // header raw json ?  ? .

            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) {
        }

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

        }
    };

    logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}",
            new String[] { this.consumerKey, this.accessToken });
    // Set up the stream's listener (defined above), and set any necessary
    // security information.
    twitterStream.addListener(listener);
    twitterStream.setOAuthConsumer(this.consumerKey, this.consumerSecret);
    AccessToken token = new AccessToken(this.accessToken, this.accessTokenSecret);
    twitterStream.setOAuthAccessToken(token);

    // Set up a filter to pull out industry-relevant tweets
    if (keywords.length == 0) {
        logger.debug("Starting up Twitter sampling...");
        twitterStream.sample();
    } else {
        logger.debug("Starting up Twitter filtering...");

        // ? . 
        FilterQuery query = new FilterQuery().track(keywords);
        twitterStream.filter(query);
    }
    super.start();
}

From source file:com.temenos.interaction.example.mashup.twitter.Twitter4JConsumer.java

License:Open Source License

/**
 * @param otherUser//  w w  w.  j  av a  2s . c om
 * @return
 */
public Collection<Tweet> requestTweetsByUser(String otherUser) {
    List<Tweet> tweets = new ArrayList<Tweet>();
    try {
        // The factory instance is re-useable and thread safe.
        Twitter twitter = new TwitterFactory().getInstance();
        AccessToken accessToken = loadAccessToken(1);
        twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
        twitter.setOAuthAccessToken(accessToken);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Fetching latest 100 tweets for [" + otherUser + "]");
        }
        // First param of Paging() is the page number, second is the number per page (this is capped around 200 I think.
        Paging paging = new Paging(1, 100);
        List<Status> statuses = twitter.getUserTimeline(otherUser, paging);
        for (Status status : statuses) {
            tweets.add(new Tweet(otherUser, status.getText(),
                    (status.getGeoLocation() != null
                            ? status.getGeoLocation().getLatitude() + ","
                                    + status.getGeoLocation().getLongitude()
                            : "")));
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info(
                        status.getUser().getName() + "(" + status.getGeoLocation() + "):" + status.getText());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Error on requestTweetsByUser", e);
        throw new TwitterMashupException(e);
    }
    return tweets;
}

From source file:com.thesmartweb.swebrank.TwitterAnalysis.java

License:Apache License

/**
 * Method to get tweets regarding a string 
 * @param query_string the string to search for
 * @param config_path the directory with the twitter api key
 * @return the tweets in a string//w w w  . j  av a 2 s  .c o  m
 */
public String perform(String query_string, String config_path) {
    try {
        List<String> twitterkeys = GetKeys(config_path);
        //configuration builder in order to set the keys of twitter
        ConfigurationBuilder cb = new ConfigurationBuilder();
        String consumerkey = twitterkeys.get(0);
        String consumersecret = twitterkeys.get(1);
        String accesstoken = twitterkeys.get(2);
        String accesstokensecret = twitterkeys.get(3);
        cb.setDebugEnabled(true).setOAuthConsumerKey(consumerkey).setOAuthConsumerSecret(consumersecret)
                .setOAuthAccessToken(accesstoken).setOAuthAccessTokenSecret(accesstokensecret);
        TwitterFactory tf = new TwitterFactory(cb.build());
        AccessToken acc = new AccessToken(accesstoken, accesstokensecret);

        Twitter twitter = tf.getInstance(acc);

        //query the twitter
        Query query = new Query(query_string);
        int rpp = 100;
        query.count(rpp);
        query.setQuery(query_string);

        //----------get the tweets------------
        QueryResult result = twitter.search(query);
        List<Status> tweets = result.getTweets();

        RateLimitStatus rls = result.getRateLimitStatus();

        String tweet_txt = "";
        for (Status tweet : tweets) {
            tweet_txt = tweet_txt + " " + tweet.getText();
        }
        DataManipulation txtpro = new DataManipulation();
        Stopwords st = new Stopwords();
        tweet_txt = txtpro.removeChars(tweet_txt);
        tweet_txt = st.stop(tweet_txt);
        tweet_txt = txtpro.removeChars(tweet_txt);
        return tweet_txt;
    } catch (TwitterException ex) {
        String tweet_txt = "";
        Logger.getLogger(TwitterAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        return tweet_txt = "fail";
    }
}

From source file:com.tuncaysenturk.jira.plugins.jtp.twitter.JiraTwitterUserStreamListener.java

@Override
public void onStatus(Status status) {
    PropertySet propSet = ComponentManager.getComponent(PropertiesManager.class).getPropertySet();
    if (!licenseValidator.isValid()) {
        logger.error(JTPConstants.LOG_PRE + "License problem, see configuration page");
        ExceptionMessagesUtil.addLicenseExceptionMessage();
    } else {/*  ww  w. j  av  a2 s  .  c  o  m*/
        logger.info(JTPConstants.LOG_PRE + "onStatus @" + status.getUser().getScreenName() + " - "
                + status.getText());

        ExceptionMessagesUtil.cleanAllExceptionMessages();

        checkAndSetScreenName();
        if (StringUtils.isEmpty(screenName)) {
            ExceptionMessagesUtil
                    .addExceptionMessage("No Screen name found, please authorize Twitter account!");
            return;
        }
        if (status.getUser().getScreenName().equals(screenName)) {
            // tweet is mine, do not respond it
            return;
        }
        String text = StringUtils.trim(status.getText().replace("@" + screenName, ""));

        if (propSet.getBoolean("onlyFollowers") && !isFollower(status.getUser().getId())) {
            logger.warn(JTPConstants.LOG_PRE + status.getUser().getScreenName()
                    + " is not a follower but mentioned to create issue");
            return;
        }
        String userName = propSet.getString("userId");
        String issueTypeId = propSet.getString("issueTypeId");
        if (status.getInReplyToStatusId() == -1) {
            // -1 means that this is not reply, it's main tweet
            String projectId = propSet.getString("projectId");
            issueService.createIssue(userName, status.getUser().getScreenName(), text,
                    Long.parseLong(projectId), issueTypeId);
        } else if (status.getInReplyToStatusId() > 0) {
            // this is a reply tweet, so add comment to main issue
            long statusId = status.getInReplyToStatusId();
            TweetIssueRel rel = tweetIssueRelService.findTweetIssueRelByTweetStatusId(statusId);
            Long issueId = null;
            if (null != rel)
                issueId = rel.getIssueId();
            if (null != issueId) {
                issueService.addComment(userName, status.getUser().getScreenName(), issueId, text);
                // assosiate this tweet with issue,
                // so that replies to this tweet will be comments to the issue
                tweetIssueRelService.persistRelation(issueId, status.getId());
            }
        }
    }
}

From source file:com.tuncaysenturk.jira.plugins.jtp.twitter.JiraTwitterUserStreamListener.java

public void onRetweet(User source, User target, Status retweetedStatus) {
    logger.info(JTPConstants.LOG_PRE + "just logging, onRetweet @" + retweetedStatus.getUser().getScreenName()
            + " - " + retweetedStatus.getText());
}

From source file:com.twasyl.slideshowfx.server.service.TwitterService.java

License:Apache License

private StatusListener buildTwitterStreamListener() {
    final StatusListener listener = new StatusListener() {
        @Override// w w w.j ava 2s .  c  om
        public void onStatus(Status status) {
            final ChatMessage chatMessage = new ChatMessage();
            chatMessage.setId(System.currentTimeMillis() + "");
            chatMessage.setSource(ChatMessageSource.TWITTER);
            chatMessage.setStatus(ChatMessageStatus.NEW);
            chatMessage.setAuthor("@" + status.getUser().getScreenName());
            chatMessage.setContent(status.getText());

            final JsonObject jsonTweet = chatMessage.toJSON();

            TwitterService.this.vertx.eventBus().publish("slideshowfx.chat.attendee.message.add", jsonTweet);
            TwitterService.this.vertx.eventBus().publish("slideshowfx.chat.presenter.message.add", jsonTweet);
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

        }

        @Override
        public void onTrackLimitationNotice(int i) {

        }

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

        }

        @Override
        public void onStallWarning(StallWarning stallWarning) {

        }

        @Override
        public void onException(Exception e) {
            e.printStackTrace();
        }
    };

    return listener;
}

From source file:com.tweet.analysis.SearchTweets.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param args search query//w ww.  j  av  a  2 s  .  c  om
 */
public static void main(String[] args) {
    if (args.length < 1) {
        //System.out.println("java twitter4j.examples.search.SearchTweets [query]");
        //System.exit(-1);
    }
    Twitter twitter = new TwitterFactory().getInstance();
    //twitter.getFollowersList("Kuldeep.loveiit");
    try {
        Query query = new Query("Modi");
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.TweetExtractor.java

/**
 * */*w  w  w  . j  av a2 s  .  c  o m*/
 *
 */
public ArrayList<Tweet> retrieveTweets(String searchWord) {

    Paging paging;

    // set the lowest value of the tweet ID initially to one less than Long.MAX_VALUE
    long min_id = Long.MAX_VALUE - 1;
    int count = 0;
    int index = 0;
    boolean maxValueReached = false;
    userToSearch = searchWord;

    while (true) {
        try {

            //count = tweetList.size();
            // paging tweets at a rate of 100 per page
            paging = new Paging(1, 100);

            // if this is not the first iteration set the new min_id value for the page
            if (count != 0) {

                paging.setMaxId(min_id - 1);
            }

            // get a page of the tweet timeline with tweets with ids less than the min_id value
            List<Status> tweetTempList = twitterApp.getUserTimeline(userToSearch, paging);

            // iterate the results and add to tweetList
            for (Status s : tweetTempList) {
                if (count == maxTweets) {
                    maxValueReached = true;
                    break;
                }
                count++;
                Tweet tweet = new Tweet(s.getId(), s.getCreatedAt(), s.getText());
                tweetList.add(tweet);

                // set the value for the min value for the next iteration
                if (s.getId() < min_id) {
                    min_id = s.getId();
                }
            }

            // if the results for this iteration is zero, means we have reached the API limit or we have extracted the maximum
            // possible, so break
            if (tweetTempList.size() == 0 || maxValueReached) {
                return tweetList;
                // break;
            }

        } catch (TwitterException e) {
            e.printStackTrace();
            break;
        } catch (Exception e) {
            e.printStackTrace();
            break;
        }
    }
    return tweetList;

}

From source file:com.tweetmyhome.TweetMyHome.java

/**
 * funcion se dispara cuando te mencionan sin ser amigo
 * funcion se dipara cuando alguien que sigues habla cualquier wea
 * funcion se dispara cuando la propia casa twittea
 * @param status /*from   ww  w.j a  v  a2s  .co m*/
 */
@Override
public void onStatus(Status status) {
    User user = status.getUser();
    debug("onStatus @" + status.getUser().getScreenName() + " : " + status.getText());
    if (TwitterUserUtil.equals(status.getUser().getScreenName(), p.getValueByKey(Key.twitterSuperUser))) {
        debug("Own tweet detected... EXITING function");
        return;
    }
    TweetStringAnalizer tsa;
    try {
        tsa = new TweetStringAnalizer(status.getText(), tweetDictionary);
    } catch (TweetStringException ex) {
        error(ex.toString(), ex);
        return;
    }
    Map<Integer, String> mencionedUsers = tsa.getMencionedUsers();
    if (mencionedUsers != null) {
        boolean isHomeMencioned = false;
        for (Map.Entry<Integer, String> entry : mencionedUsers.entrySet()) {
            if (TwitterUserUtil.equals(entry.getValue(), p.getValueByKey(Key.twitterSuperUser))) {
                isHomeMencioned = true;
                break;
            }
        }
        if (isHomeMencioned) {
            if (!tsa.isErrorFounded()) {
                try {
                    db.add(new SimpleMention(this, status.getId(), status.getUser().getId(), null,
                            status.getText(), Calendar.getInstance().getTimeInMillis()));
                    analyzeAndRespond(user, tsa, false);
                } catch (TwitterException | TweetMyHomeException ex) {
                    error(ex.toString(), ex);
                }
            } else {
                error(tsa.getErrorString().toString());
            }
        } else {
            debug("Users were mencioned, but not this home...");
        }
    } else {
        debug("None user Mencioned...");
    }
}