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:onl.area51.a51li.twitter.TwitterAuth.java

License:Apache License

public static void main(String args[]) throws Exception {
    final String consumerKey = args[0];
    final String consumerSecret = args[1];

    // The factory instance is re-useable and thread safe.
    Twitter twitter = TwitterFactory.getSingleton();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    RequestToken requestToken = twitter.getOAuthRequestToken();
    AccessToken accessToken = null;/* w w  w .j  a  va2  s. c om*/
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    while (null == accessToken) {
        System.out.println("Open the following URL and grant access to your account:");
        System.out.println(requestToken.getAuthorizationURL());
        System.out.print("Enter the PIN(if aviailable) or just hit enter.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
    }
    //persist to the accessToken for future reference.
    storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
    Status status = twitter.updateStatus(args[0]);
    System.out.println("Successfully updated the status to [" + status.getText() + "].");
    System.exit(0);
}

From source file:onl.area51.a51li.twitter.TwitterConsumer.java

License:Apache License

private void tweet(String userName, String hash, String tweetAs, String tweet) {

    User user = LinkManager.INSTANCE.getUser(userName, hash);
    if (user == null) {
        return;//from  ww w  .java 2 s .  com
    }

    Twitter twitter = twits.computeIfAbsent(tweetAs, h -> TwitterManager.INSTANCE.getTwitter(user, tweetAs));
    if (twitter == null) {
        return;
    }

    // Now rate limit ourselves here as we have a twitter API available to us
    TwitterManager.INSTANCE.rateLimit();

    // Try to tweet
    try {
        LOG.log(Level.INFO, () -> "Tweeting @" + tweetAs + ": " + tweet);
        Status s = twitter.updateStatus(tweet);
        LOG.log(Level.INFO, () -> "Tweeted @" + tweetAs + ": " + s.getText());
    } catch (TwitterException ex) {
        LOG.log(Level.SEVERE, ex, () -> "Failed to tweet " + tweetAs + ": " + tweet);
    }

}

From source file:ontoSentiment.Busca.java

public void buscarPorAssunto(String busca, String lang) throws TwitterException {
    int totalTweets = 0;
    long maxID = -1;
    Query q = new Query(busca + " -filter:retweets -filter:links -filter:replies -filter:images");
    q.setCount(Util.TWEETS_PER_QUERY); // How many tweets, max, to retrieve 
    q.resultType(Query.ResultType.recent); // Get all tweets 
    q.setLang(lang);/* ww w  .j  a  va  2s .  co  m*/
    QueryResult r = Util.getTwitter().search(q);
    do {
        for (Status s : r.getTweets()) {
            totalTweets++;
            if (maxID == -1 || s.getId() < maxID) {
                maxID = s.getId();
            }

            //System.out.printf("O tweet de id %s disse as %s, @%-20s disse: %s\n", new Long(s.getId()).toString(), s.getCreatedAt().toString(), s.getUser().getScreenName(), Util.cleanText(s.getText()));
            System.out.println(Util.cleanText(s.getText()));
        }
        q = r.nextQuery();
        if (q != null) {
            q.setMaxId(maxID);
            r = Util.getTwitter().search(q);
            System.out.println("Total tweets: " + totalTweets);
            System.out.println("Maximo ID: " + maxID);
            Util.imprimirRateLimit(Util.RATE_LIMIT_OPTION_SEARCH_TWEETS);
        }
    } while (q != null);
}

From source file:org.anc.lapps.datasource.twitter.TwitterDatasource.java

/**
 * Entry point for a Lappsgrid service.//w  w  w  .j a  va  2s .c  om
 * <p>
 * Each service on the Lappsgrid will accept {@code org.lappsgrid.serialization.Data} object
 * and return a {@code Data} object with a {@code org.lappsgrid.serialization.lif.Container}
 * payload.
 * <p>
 * Errors and exceptions that occur during processing should be wrapped in a {@code Data}
 * object with the discriminator set to http://vocab.lappsgrid.org/ns/error
 * <p>
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/Data.html>org.lappsgrid.serialization.Data</a><br />
 * See <a href="https://lapp.github.io/org.lappsgrid.serialization/index.html?org/lappsgrid/serialization/lif/Container.html>org.lappsgrid.serialization.lif.Container</a><br />
 *
 * @param input A JSON string representing a Data object
 * @return A JSON string containing a Data object with a Container payload.
 */
@Override
public String execute(String input) {
    Data<String> data = Serializer.parse(input, Data.class);
    String discriminator = data.getDiscriminator();

    // Return ERRORS back
    if (Discriminators.Uri.ERROR.equals(discriminator)) {
        return input;
    }

    // Generate an error if the used discriminator is wrong
    if (!Discriminators.Uri.GET.equals(discriminator)) {
        return generateError(
                "Invalid discriminator.\nExpected " + Discriminators.Uri.GET + "\nFound " + discriminator);
    }

    Configuration config = new ConfigurationBuilder().setApplicationOnlyAuthEnabled(true).setDebugEnabled(false)
            .build();

    // Authentication using saved keys
    Twitter twitter = new TwitterFactory(config).getInstance();
    String key = readProperty(KEY_PROPERTY);
    if (key == null) {
        return generateError("The Twitter Consumer Key property has not been set.");
    }

    String secret = readProperty(SECRET_PROPERTY);
    if (secret == null) {
        return generateError("The Twitter Consumer Secret property has not been set.");
    }

    twitter.setOAuthConsumer(key, secret);

    try {
        twitter.getOAuth2Token();
    } catch (TwitterException te) {
        String errorData = generateError(te.getMessage());
        logger.error(errorData);
        return errorData;
    }

    // Get query String from data payload
    Query query = new Query(data.getPayload());

    // Set the type to Popular or Recent if specified
    // Results will be Mixed by default.
    if (data.getParameter("type") == "Popular")
        query.setResultType(Query.POPULAR);
    if (data.getParameter("type") == "Recent")
        query.setResultType(Query.RECENT);

    // Get lang string
    String langCode = (String) data.getParameter("lang");

    // Verify the validity of the language code and add it to the query if it's valid
    if (validateLangCode(langCode))
        query.setLang(langCode);

    // Get date strings
    String sinceString = (String) data.getParameter("since");
    String untilString = (String) data.getParameter("until");

    // Verify the format of the date strings and set the parameters to query if correctly given
    if (validateDateFormat(untilString))
        query.setUntil(untilString);
    if (validateDateFormat(sinceString))
        query.setSince(sinceString);

    // Get GeoLocation
    if (data.getParameter("address") != null) {
        String address = (String) data.getParameter("address");
        double radius = (double) data.getParameter("radius");
        if (radius <= 0)
            radius = 10;
        Query.Unit unit = Query.MILES;
        if (data.getParameter("unit") == "km")
            unit = Query.KILOMETERS;
        GeoLocation geoLocation;
        try {
            double[] coordinates = getGeocode(address);
            geoLocation = new GeoLocation(coordinates[0], coordinates[1]);
        } catch (Exception e) {
            String errorData = generateError(e.getMessage());
            logger.error(errorData);
            return errorData;
        }

        query.geoCode(geoLocation, radius, String.valueOf(unit));

    }

    // Get the number of tweets from count parameter, and set it to default = 15 if not specified
    int numberOfTweets;
    try {
        numberOfTweets = (int) data.getParameter("count");
    } catch (NullPointerException e) {
        numberOfTweets = 15;
    }

    // Generate an ArrayList of the wanted number of tweets, and handle possible errors.
    // This is meant to avoid the 100 tweet limit set by twitter4j and extract as many tweets as needed
    ArrayList<Status> allTweets;
    Data tweetsData = getTweetsByCount(numberOfTweets, query, twitter);
    String tweetsDataDisc = tweetsData.getDiscriminator();
    if (Discriminators.Uri.ERROR.equals(tweetsDataDisc))
        return tweetsData.asPrettyJson();

    else {
        allTweets = (ArrayList<Status>) tweetsData.getPayload();
    }

    // Initialize StringBuilder to hold the final string
    StringBuilder builder = new StringBuilder();

    // Append each Status (each tweet) to the initialized builder
    for (Status status : allTweets) {
        String single = status.getCreatedAt() + " : " + status.getUser().getScreenName() + " : "
                + status.getText() + "\n";
        builder.append(single);
    }

    // Output results
    Container container = new Container();
    container.setText(builder.toString());
    Data<Container> output = new Data<>(Discriminators.Uri.LAPPS, container);
    return output.asPrettyJson();
}

From source file:org.anhonesteffort.ads.twitter.TweetListener.java

License:Open Source License

public void onTweet(Status status) {
    if (status.getText().toLowerCase().contains(trackTerm)) {
        onTrackedTweet(status);
    }
}

From source file:org.anhonesteffort.ads.twitter.TweetModel.java

License:Open Source License

public TweetModel(Status status) {
    id = status.getId();/*from  w ww.  jav a  2  s .com*/
    timeMs = status.getCreatedAt().getTime();
    handle = status.getUser().getScreenName();
    accountPic = status.getUser().getProfileImageURLHttps();
    text = status.getText();
}

From source file:org.anhonesteffort.ads.zodiac.ZodiacTweetListener.java

License:Open Source License

@Override
protected void onTrackedTweet(Status status) {
    VersionedEntry<Status> entry = tweetQueue.add(status);
    log.debug("received tweet for term: " + trackTerm + ", version: " + entry.getVersion() + ", text: "
            + status.getText());
}

From source file:org.apache.asterix.external.parser.TweetParser.java

License:Apache License

@Override
public void parse(IRawRecord<? extends Status> record, DataOutput out) throws HyracksDataException {
    Status tweet = record.get();
    User user = tweet.getUser();/*from   www .ja  v  a2s.c om*/
    // Tweet user data
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.SCREEN_NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getScreenName()));
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.LANGUAGE)])
            .setValue(JObjectUtil.getNormalizedString(user.getLang()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FRIENDS_COUNT)])
            .setValue(user.getFriendsCount());
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.STATUS_COUNT)])
            .setValue(user.getStatusesCount());
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getName()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FOLLOWERS_COUNT)])
            .setValue(user.getFollowersCount());

    // Tweet data
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.ID)])
            .setValue(String.valueOf(tweet.getId()));

    int userPos = tweetFieldNameMap.get(Tweet.USER);
    for (int i = 0; i < mutableUserFields.length; i++) {
        ((AMutableRecord) mutableTweetFields[userPos]).setValueAtPos(i, mutableUserFields[i]);
    }
    if (tweet.getGeoLocation() != null) {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)])
                .setValue(tweet.getGeoLocation().getLatitude());
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)])
                .setValue(tweet.getGeoLocation().getLongitude());
    } else {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)]).setValue(0);
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)]).setValue(0);
    }
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.CREATED_AT)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getCreatedAt().toString()));
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.MESSAGE)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getText()));

    for (int i = 0; i < mutableTweetFields.length; i++) {
        mutableRecord.setValueAtPos(i, mutableTweetFields[i]);
    }
    recordBuilder.reset(mutableRecord.getType());
    recordBuilder.init();
    IDataParser.writeRecord(mutableRecord, out, recordBuilder);
}

From source file:org.apache.asterix.external.util.TweetProcessor.java

License:Apache License

public AMutableRecord processNextTweet(Status tweet) {
    User user = tweet.getUser();//w w  w .j  av  a 2  s  . com

    // Tweet user data
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.SCREEN_NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getScreenName()));
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.LANGUAGE)])
            .setValue(JObjectUtil.getNormalizedString(user.getLang()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FRIENDS_COUNT)])
            .setValue(user.getFriendsCount());
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.STATUS_COUNT)])
            .setValue(user.getStatusesCount());
    ((AMutableString) mutableUserFields[userFieldNameMap.get(Tweet.NAME)])
            .setValue(JObjectUtil.getNormalizedString(user.getName()));
    ((AMutableInt32) mutableUserFields[userFieldNameMap.get(Tweet.FOLLOWERS_COUNT)])
            .setValue(user.getFollowersCount());

    // Tweet data
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.ID)])
            .setValue(String.valueOf(tweet.getId()));

    int userPos = tweetFieldNameMap.get(Tweet.USER);
    for (int i = 0; i < mutableUserFields.length; i++) {
        ((AMutableRecord) mutableTweetFields[userPos]).setValueAtPos(i, mutableUserFields[i]);
    }
    if (tweet.getGeoLocation() != null) {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)])
                .setValue(tweet.getGeoLocation().getLatitude());
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)])
                .setValue(tweet.getGeoLocation().getLongitude());
    } else {
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LATITUDE)]).setValue(0);
        ((AMutableDouble) mutableTweetFields[tweetFieldNameMap.get(Tweet.LONGITUDE)]).setValue(0);
    }
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.CREATED_AT)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getCreatedAt().toString()));
    ((AMutableString) mutableTweetFields[tweetFieldNameMap.get(Tweet.MESSAGE)])
            .setValue(JObjectUtil.getNormalizedString(tweet.getText()));

    for (int i = 0; i < mutableTweetFields.length; i++) {
        mutableRecord.setValueAtPos(i, mutableTweetFields[i]);
    }

    return mutableRecord;

}

From source file:org.apache.blur.demo.twitter.TwitterSearchQueueReader.java

License:Apache License

private RowMutation toRowMutation(Status tweet) {
    RowMutation rowMutation = new RowMutation();
    rowMutation.setRowId(tweet.getUser().getScreenName());
    rowMutation.setTable(tableName);/*ww  w. j  a va2 s. c  o  m*/
    rowMutation.setRowMutationType(RowMutationType.UPDATE_ROW);
    Record record = new Record();
    record.setFamily("tweets");
    record.setRecordId(tweet.getUser().getScreenName() + "-" + tweet.getId());

    record.addToColumns(new Column("message", tweet.getText()));

    for (UserMentionEntity mention : tweet.getUserMentionEntities()) {
        record.addToColumns(new Column("mentions", mention.getScreenName()));
    }

    for (HashtagEntity tag : tweet.getHashtagEntities()) {
        record.addToColumns(new Column("hashtags", tag.getText()));
    }
    rowMutation.addToRecordMutations(new RecordMutation(RecordMutationType.REPLACE_ENTIRE_RECORD, record));

    log.trace(rowMutation);

    return rowMutation;
}