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.vti.managers.TwitterManager.java

License:Apache License

/**
 * Get timeline of  a specified user/*from   w ww .j  a v a 2s  .  c  o m*/
 * 
 * @return List<Twits>
 */
public List<Twit> getUserTimeline(String userName) {
    List<Twit> twits = null;
    try {
        // User user = twitter.verifyCredentials();
        final List<Status> statues = twitter.getUserTimeline(userName);
        twits = new ArrayList<Twit>(statues.size());
        for (Status status : statues) {
            Log.e(TAG, status.getText());
            twits.add(new Twit(status.getId(), status.getCreatedAt().getTime(), status.getUser().getName(),
                    status.getUser().getProfileImageURL().toString(), status.getText()));
        }
    } catch (Exception e) {
        Log.d(TAG, Log.stack2string(e));
    }
    return twits;
}

From source file:com.vuze.client.plugins.twitter.TwitterPlugin.java

License:Open Source License

private TwitterResult sendTweet(String status) {
    TwitterResult twitter_result;//  w  w w.  j  a va  2  s  . c  o m

    log.log("Updating status: " + status);

    try {
        ConfigurationBuilder cb = new ConfigurationBuilder();

        //cb.setSource( "Vuze" );

        // Twitter twitter = new TwitterFactory( cb.build()).getInstance( twitter_user.getValue(), new String( twitter_password.getValue()));

        Status result;

        Twitter twitter = null;

        try {
            if (access_token == null) {

                throw (new Exception("Please configure your account settings in the plugin options"));
            }

            cb.setOAuthAccessToken(access_token.getToken())
                    .setOAuthAccessTokenSecret(access_token.getTokenSecret()).setOAuthConsumerKey(CONSUMER_KEY)
                    .setOAuthConsumerSecret(CONSUMER_SECRET);

            twitter = new TwitterFactory(cb.build()).getInstance();

            result = twitter.updateStatus(status);

        } catch (Throwable e) {

            // hack for old clients that don't have correct trust store

            if (twitter != null && (e instanceof TwitterException)
                    && ((TwitterException) e).getStatusCode() == -1) {

                String truststore_name = FileUtil.getUserFile(SESecurityManager.SSL_CERTS).getAbsolutePath();

                File target = new File(truststore_name);

                if (!target.exists() || target.length() < 2 * 1024) {

                    File cacerts = new File(
                            new File(new File(System.getProperty("java.home"), "lib"), "security"), "cacerts");

                    if (cacerts.exists()) {

                        FileUtil.copyFile(cacerts, target);
                    }
                }

                // this merely acts to trigger a load of the keystore

                plugin_interface.getUtilities().getSecurityManager()
                        .installServerCertificate(new URL("https://twitter.com/"));

                result = twitter.updateStatus(status);

            } else {

                throw (e);
            }
        }

        log.log("Status updated to '" + result.getText() + "'");

        twitter_result = new TwitterResult();

    } catch (TwitterException e) {

        int status_code = e.getStatusCode();

        if (status_code == 401) {

            log.logAlert(LoggerChannel.LT_ERROR, "Twitter status update failed: id or password incorrect");

            twitter_result = new TwitterResult("Authentication failed: ID or password incorrect", false);

        } else if (status_code == 403) {

            log.logAlert(LoggerChannel.LT_ERROR,
                    "Twitter status update failed: duplicate tweet rejected by the server");

            twitter_result = new TwitterResult("Tweet has already been sent!", false);

        } else if (status_code >= 500 && status_code < 600) {

            log.logAlert(LoggerChannel.LT_ERROR,
                    "Twitter status update failed: Twitter is down or being upgraded");

            twitter_result = new TwitterResult("Tweet servers unavailable - try again later", true);

        } else {

            log.logAlert("Twitter status update failed", e);

            twitter_result = new TwitterResult(Debug.getNestedExceptionMessage(e), false);
        }
    } catch (Throwable e) {

        log.logAlert("Twitter status update failed", e);

        twitter_result = new TwitterResult(Debug.getNestedExceptionMessage(e), false);
    }

    return (twitter_result);
}

From source file:com.wso2.stream.connector.protocol.TweetContent.java

License:Open Source License

public OMElement createBodyContent(OMFactory omFactory, Status status) {
    OMElement tweet = omFactory.createOMElement(qTweet);

    OMElement text = omFactory.createOMElement(qText);
    tweet.addChild(text);/*from w ww  . j a  v a 2  s .  c  om*/
    text.addChild(omFactory.createOMText(status.getText()));

    OMElement createdAt = omFactory.createOMElement(qCreatedAt);
    tweet.addChild(createdAt);
    createdAt.addChild(omFactory.createOMText(status.getCreatedAt().toString()));

    OMElement latitude = omFactory.createOMElement(qLatitude);
    tweet.addChild(latitude);
    OMElement longitude = omFactory.createOMElement(qLongitude);
    tweet.addChild(longitude);
    if (status.getGeoLocation() != null) {
        latitude.addChild(omFactory.createOMText(String.valueOf(status.getGeoLocation().getLatitude())));
        longitude.addChild(omFactory.createOMText(String.valueOf(status.getGeoLocation().getLongitude())));
    }

    OMElement country = omFactory.createOMElement(qCountry);
    tweet.addChild(country);
    OMElement countryCode = omFactory.createOMElement(qCountryCode);
    tweet.addChild(countryCode);

    if (status.getPlace() != null) {
        country.addChild(omFactory.createOMText(status.getPlace().getCountry()));
        countryCode.addChild(omFactory.createOMText(status.getPlace().getCountryCode()));
    }

    OMElement location = omFactory.createOMElement(qLocation);
    tweet.addChild(location);
    if (status.getUser() != null) {
        location.addChild(omFactory.createOMText(status.getUser().getLocation()));
    }

    OMElement hashTags = omFactory.createOMElement(qHasTags);
    tweet.addChild(hashTags);

    if (status.getHashtagEntities().length > 0) {
        String tags = "";
        for (HashtagEntity h : status.getHashtagEntities()) {
            tags += h.getText() + ";";
        }
        tags = tags.substring(0, tags.length() - 1);
        hashTags.addChild(omFactory.createOMText(tags));
    }

    return tweet;

}

From source file:com.yahoo.labs.samoa.sentinel.model.TwitterStreamAPIReader.java

License:Apache License

public void addToList(Status status) {
    Tweet tweet = soap.processTweets(status.getText(), language);
    String tweetMessage = tweet.getCleanedMessage();

    //if (tweet.getLanguage().equals(language)) {
    if (tweetMessage != null && !tweetMessage.equals("") && !tweetMessage.equals(" ")) {
        synchronized (listOfTweets) {
            listOfTweets.add(tweet);/*  w w w . j  a  v  a  2  s  .c  om*/
            sizeTweetList++;
        }
    }
}

From source file:com.yoshio3.javaee7.sampleapp.TwitterStreamImpl.java

@Override
public void onStatus(Status status) {
    try {/*w w  w .  ja v  a2  s .  co  m*/
        //Twitter ????????
        User user = status.getUser();
        String resStr = "@" + user.getScreenName() + " : " + status.getText();
        String encodedString = encode(resStr);
        session.getBasicRemote().sendText(encodedString);
        System.out.println(encodedString);
    } catch (IOException ex) {
        Logger.getLogger(TwitterStreamImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:controllers.modules.CorpusModule.java

License:Open Source License

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;//from w ww  . j  a v a2s  .  c  o  m
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}

From source file:cp.Demo.java

private void MoviesListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_MoviesListValueChanged

    // Obtain the movie object
    Movie mov;/*www  .  j a  v a2  s.  c  o m*/
    try {
        mov = (Movie) MoviesList.getSelectedValue();
        System.out.println(mov.getApiQuery());
    } catch (Exception ex) {
        PosterLabel.setIcon(null);
        PosterLabel.setText("Movie not found");
        return;
    }

    // Display the movie poster
    try {
        // Load the movie poster
        URL url = new URL(mov.getPosterLink());
        ImageIcon img = new ImageIcon(url);

        // Rescale the movie poster
        int w = img.getIconWidth();
        int h = img.getIconHeight();
        int labelH = MovieTabs.getHeight() - 36;
        img.setImage(img.getImage().getScaledInstance(labelH * w / h, labelH, Image.SCALE_SMOOTH));

        // Put the movie poster into the label, and change the text
        PosterLabel.setIcon(img);
        PosterLabel.setText("");
    } catch (Exception ex) {
        // If for some reason the poster isn't available, indicate this
        PosterLabel.setIcon(null);
        PosterLabel.setText("Poster could not be displayed");
    }

    // Display tweets about the movie
    try {
        // clear out the tweets
        TweetsArea.setText("");

        // The factory instance is re-useable and thread safe.
        Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(mov.getTitle());
        QueryResult result = twitter.search(query);
        String tweet;
        for (Status status : result.getTweets()) {
            tweet = String.format("[%s] @%s tweeted %s\n", status.getCreatedAt(),
                    status.getUser().getScreenName(), status.getText());
            TweetsArea.append(tweet);
        }
    } catch (TwitterException ex) {
        TweetsArea.setText(ex.toString());
    }

    // Display reviews of the movie
    try {
        ReviewsArea.setText("");
        for (Review rev : (new ReviewRequest(mov.getMovie())).getReviews()) {
            String review = String.format("[%s] (by %s, %s)\n%s\n%s\n\n", rev.getDateOfReview(),
                    rev.getCritic(), rev.getPublication(), rev.getQuote(), rev.getReviewLinkUrl());
            ReviewsArea.append(review);
        }
    } catch (IOException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ReviewRequest.ReviewRequestException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:crawler.DataSearch.java

License:Apache License

public void collectNewTweets() {

    while (keywords.size() > 0) {
        String hash = keywords.get(0);
        Query query = new Query(hash);
        query.setCount(Settings.searchTweetNo);
        QueryResult result;/*w  w  w .  ja  v  a  2 s.com*/

        try {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            if (tweets.size() == 0)
                TwitterCrawler.TFFreq.remove(hash);
            for (Status status : tweets) {
                //System.out.println("{"+hash+"}["+status.getCreatedAt().toString()+"]- [USER: " + status.getUser().getScreenName() + "] - " + status.getText());
                String temp;
                if (trash(status.getText())) {
                    if (Settings.limitTime) {
                        long currentTime = System.currentTimeMillis();
                        long tweetTime = status.getCreatedAt().getTime();

                        if (currentTime - tweetTime > Settings.timeLimit)
                            continue;
                    }
                    if (hashtext.containsKey(hash))
                        temp = hashtext.get(hash) + status.getText();
                    else
                        temp = status.getText();
                    hashtext.put(hash, temp);
                }
            }
            //System.out.println("{"+hash+"} with "+tweets.size()+"tweets");
            keywords.remove(0);
        } catch (TwitterException e) {
            if (e.getErrorCode() == 88) {
                System.out.println("Using other keys???");

                String ConsumerKey_temp = Settings.ConsumerKey.get(0);
                String ConsumerSecret_temp = Settings.ConsumerSecret.get(0);
                String AccessToken_temp = Settings.AccessToken.get(0);
                String AccessSecret_temp = Settings.AccessSecret.get(0);

                Settings.ConsumerKey.remove(ConsumerKey_temp);
                Settings.ConsumerSecret.remove(ConsumerSecret_temp);
                Settings.AccessToken.remove(AccessToken_temp);
                Settings.AccessSecret.remove(AccessSecret_temp);

                twitter = new TwitterFactory(
                        OA.build(Settings.ConsumerKey.get(0), Settings.ConsumerSecret.get(0),
                                Settings.AccessToken.get(0), Settings.AccessSecret.get(0))).getInstance();

                Settings.ConsumerKey.add(Settings.ConsumerKey.size(), ConsumerKey_temp);
                Settings.ConsumerSecret.add(Settings.ConsumerSecret.size(), ConsumerSecret_temp);
                Settings.AccessToken.add(Settings.AccessToken.size(), AccessToken_temp);
                Settings.AccessSecret.add(Settings.AccessSecret.size(), AccessSecret_temp);

                System.out.println("**************************************************************");
                System.out.println("[" + ConsumerKey_temp + "] to [" + Settings.ConsumerKey.get(0) + "]");
                System.out.println("[" + ConsumerSecret_temp + "] to [" + Settings.ConsumerSecret.get(0) + "]");
                System.out.println("[" + AccessToken_temp + "] to [" + Settings.AccessToken.get(0) + "]");
                System.out.println("[" + AccessSecret_temp + "] to [" + Settings.AccessSecret.get(0) + "]");
                System.out.println("**************************************************************");

                continue;
            }
            e.printStackTrace();
        }
    }

}

From source file:crawler.DataStorage.java

License:Apache License

private static void sqlStore(Status status) throws SQLException {
    long sql_pid = Settings.pid;
    Settings.pid++;/*w  ww.  ja va  2s .co m*/

    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss, z");
    String sqlCreateAt = tempDate.format(new java.util.Date(status.getCreatedAt().getTime()));

    double sqlGeoLocationLat = 0;
    double sqlGeoLocationLong = 0;

    if (status.getGeoLocation() != null) {
        sqlGeoLocationLat = status.getGeoLocation().getLatitude();
        sqlGeoLocationLong = status.getGeoLocation().getLongitude();
    }

    String sqlPlace = (status.getPlace() != null ? status.getPlace().getFullName() : "");
    long sqlId = status.getId();
    String sqlTweet = status.getText().replace("'", "''");
    String sqlSource = status.getSource().replace("'", "''");
    sqlSource = sqlSource.replace("\\", "\\\\");
    String sqlLang = status.getUser().getLang();
    String sqlScreenName = status.getUser().getScreenName();
    String sqlReplyTo = status.getInReplyToScreenName();
    long sqlRtCount = status.getRetweetCount();

    HashtagEntity[] hashs = status.getHashtagEntities();
    String sqlHashtags = "";
    for (HashtagEntity hash : hashs)
        sqlHashtags += hash.getText() + " ";

    pstm.setLong(1, sql_pid);
    pstm.setString(2, sqlCreateAt);
    pstm.setDouble(3, sqlGeoLocationLat);
    pstm.setDouble(4, sqlGeoLocationLong);
    pstm.setString(5, sqlPlace);
    pstm.setLong(6, sqlId);
    pstm.setString(7, sqlTweet);
    pstm.setString(8, sqlSource);
    pstm.setString(9, sqlLang);
    pstm.setString(10, sqlScreenName);
    pstm.setString(11, sqlReplyTo);
    pstm.setLong(12, sqlRtCount);
    pstm.setString(13, sqlHashtags);

    pstm.addBatch();
}

From source file:crawler.DataStream.java

License:Apache License

public void onStatus(Status status) {
    if (!trash(status.getText())) {
        statusRepo.add(status);//from   w  w w. j  ava2 s. c o  m
        freqUpdate(status);
    }
    /*HashtagEntity[] tags = status.getHashtagEntities();
    String hashtags = "";
    for (HashtagEntity t: tags) hashtags+=t.getText()+",";
    System.out.println(status.getCreatedAt()+", [" + hashtags + "] - " + status.getText());*/
}