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.aremaitch.codestock2010.repository.TweetObj.java

License:Apache License

public static TweetObj createInstance(Status status) {
    TweetObj to = new TweetObj();
    to.setId(status.getId());/*  w  w  w.j  av  a2  s  . c o m*/
    to.setText(status.getText());
    to.setToUserId(status.getInReplyToUserId());
    to.setToUser(status.getInReplyToScreenName());
    if (status.getUser() != null) {
        to.setFromUser(status.getUser().getScreenName());
        to.setFromUserId(status.getUser().getId());
        to.setIsoLanguageCode(status.getUser().getLang());
        to.setProfileImageUrl(status.getUser().getProfileBackgroundImageUrl());
    }
    to.setSource(status.getSource());
    to.setCreatedAt(status.getCreatedAt());
    if (status.getGeoLocation() != null) {
        to.setLatitude(status.getGeoLocation().getLatitude());
        to.setLongitude(status.getGeoLocation().getLongitude());
    }
    return to;

}

From source file:com.arihant15.ActionServlet.java

@RequestMapping("/getTimeline.arihant15")
public void doTimeline(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {// www  .  j a  v  a 2s .  co m
        Twitter twitter = (Twitter) req.getSession().getAttribute("t");
        List<Status> statuses = twitter.getHomeTimeline();
        for (Status status : statuses) {
            (res.getWriter()).println(status.getUser().getScreenName() + ":" + status.getText() + "\n");
        }
    } catch (Exception e) {
        (res.getWriter()).println(e);
    }
}

From source file:com.babatunde.twittergoogle.Utility.java

public void postToGoogle(PlusDomains s, String id, String hashtag) {
    try {//from   w  w  w.  jav  a 2  s .  c  om
        final PlusDomains serve = s;
        final String circleID = id;
        listener = new StatusListener() {
            @Override
            public void onStatus(Status status) {
                String msg = status.getUser().getName() + " - " + "@" + status.getUser().getScreenName() + " - "
                        + status.getText();
                System.out.println(msg);
                //Create a list of ACL entries
                if (serve != null && (!circleID.isEmpty() || (circleID != null))) {
                    PlusDomainsAclentryResource resource = new PlusDomainsAclentryResource();
                    resource.setType("domain").setType("circle").setId(circleID);

                    //Get Emails of people in the circle.
                    List<PlusDomainsAclentryResource> aclEntries = new ArrayList<PlusDomainsAclentryResource>();
                    aclEntries.add(resource);

                    Acl acl = new Acl();

                    acl.setItems(aclEntries);
                    acl.setDomainRestricted(true); // Required, this does the domain restriction

                    // Create a new activity object
                    Activity activity = new Activity()
                            .setObject(new Activity.PlusDomainsObject().setOriginalContent(msg)).setAccess(acl);
                    try {
                        // Execute the API request, which calls `activities.insert` for the logged in user
                        activity = serve.activities().insert("me", activity).execute();
                    } catch (IOException ex) {
                        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
                    }

                }

            }

            @Override
            public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
                System.out.println("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
            }

            @Override
            public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
                System.out.println("Got track limitation notice:" + numberOfLimitedStatuses);
            }

            @Override
            public void onScrubGeo(long userId, long upToStatusId) {
                System.out.println("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
            }

            @Override
            public void onStallWarning(StallWarning warning) {
                System.out.println("Got stall warning:" + warning);
            }

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

        };
    } catch (Exception e) {
    }

    TwitterStream twitterStream = new TwitterStreamFactory(configuration).getInstance();

    twitterStream.addListener(listener);
    String str[] = { hashtag };
    twitterStream.shutdown();
    try {
        Thread.sleep(1000);
    } catch (InterruptedException ex) {
        Logger.getLogger(Utility.class.getName()).log(Level.SEVERE, null, ex);
    }
    twitterStream.filter(new FilterQuery().track(str));

}

From source file:com.bordengrammar.bordengrammarapp.TwitterActivity.java

License:Open Source License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_twitter);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        setTranslucentStatus(true);//from   www  .j  a v  a 2s .c  o m
    }
    SystemBarTintManager tintManager = new SystemBarTintManager(this);
    tintManager.setStatusBarTintEnabled(true);
    tintManager.setStatusBarTintResource(R.color.bordenpurple);
    FeedbackSettings feedbackSettings = new FeedbackSettings();
    feedbackSettings.setCancelButtonText("Cancel");
    feedbackSettings.setSendButtonText("Send");
    feedbackSettings.setText("Send feedback to improve the app");
    feedbackSettings.setTitle("Feedback");
    feedbackSettings.setToast("We value your feedback");
    feedBack = new FeedbackDialog(this, "AF-186C1F794D93-1A", feedbackSettings);
    ActionBar actionBar = getActionBar();
    assert actionBar != null;
    actionBar.setDisplayHomeAsUpEnabled(true);
    PACKAGE_NAME = getApplicationContext().getPackageName();

    //Now lets get down into the twitter

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Toqp03fcUErG5P8e9nhfsw")
            .setOAuthConsumerSecret("SEqktstO9h7SqSm7zmcuWlH3bOtElJm1Ds2TFSwFBc")
            .setOAuthAccessToken("2245935685-U5LMfl4oEcOv6Khw58JZqRdcH2PlABEeUP2JeXj")
            .setOAuthAccessTokenSecret("uFcGRpCx8aGXdv3AiAkfVImnoLrlNNCUnZ2UtE76Zbnpa");

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    List<Status> statuses = null;
    String user;
    user = "bordengrammar";
    try {
        statuses = twitter.getUserTimeline(user);
    } catch (TwitterException e) {
        e.printStackTrace();
    }
    assert statuses != null;
    twitter4j.Status status1 = statuses.get(0);
    Format formatter = new SimpleDateFormat("MMM d, K:mm");
    savePrefs("twitter", status1.getText());
    savePrefs("twittertime", formatter.format(status1.getCreatedAt()));
    twitter4j.Status status2 = statuses.get(1);
    twitter4j.Status status3 = statuses.get(2);
    twitter4j.Status status4 = statuses.get(3);
    twitter4j.Status status5 = statuses.get(4);
    twitter4j.Status status6 = statuses.get(5);
    twitter4j.Status status7 = statuses.get(6);
    twitter4j.Status status8 = statuses.get(7);
    twitter4j.Status status9 = statuses.get(8);
    twitter4j.Status status10 = statuses.get(9);
    TextView time1 = (TextView) findViewById(R.id.time1);
    TextView time2 = (TextView) findViewById(R.id.time2);
    TextView time3 = (TextView) findViewById(R.id.time3);
    TextView time4 = (TextView) findViewById(R.id.time4);
    TextView time5 = (TextView) findViewById(R.id.time5);
    TextView time6 = (TextView) findViewById(R.id.time6);
    TextView time7 = (TextView) findViewById(R.id.time7);
    TextView time8 = (TextView) findViewById(R.id.time8);
    TextView time9 = (TextView) findViewById(R.id.time9);
    TextView time10 = (TextView) findViewById(R.id.time10);
    time1.setText(formatter.format(status1.getCreatedAt()));
    time2.setText(formatter.format(status2.getCreatedAt()));
    time3.setText(formatter.format(status3.getCreatedAt()));
    time4.setText(formatter.format(status4.getCreatedAt()));
    time5.setText(formatter.format(status5.getCreatedAt()));
    time6.setText(formatter.format(status6.getCreatedAt()));
    time7.setText(formatter.format(status7.getCreatedAt()));
    time8.setText(formatter.format(status8.getCreatedAt()));
    time9.setText(formatter.format(status9.getCreatedAt()));
    time10.setText(formatter.format(status10.getCreatedAt()));
    TextView text1 = (TextView) findViewById(R.id.text1);
    TextView text2 = (TextView) findViewById(R.id.text2);
    TextView text3 = (TextView) findViewById(R.id.text3);
    TextView text4 = (TextView) findViewById(R.id.text4);
    TextView text5 = (TextView) findViewById(R.id.text5);
    TextView text6 = (TextView) findViewById(R.id.text6);
    TextView text7 = (TextView) findViewById(R.id.text7);
    TextView text8 = (TextView) findViewById(R.id.text8);
    TextView text9 = (TextView) findViewById(R.id.text9);
    TextView text10 = (TextView) findViewById(R.id.text10);
    text1.setText(readPrefs("twitter"));
    text2.setText(status2.getText());
    text3.setText(status3.getText());
    text4.setText(status4.getText());
    text5.setText(status5.getText());
    text6.setText(status6.getText());
    text7.setText(status7.getText());
    text8.setText(status8.getText());
    text9.setText(status9.getText());
    text10.setText(status10.getText());
    /* i think i could have used a for loop... oh well i typed it all already. */
}

From source file:com.cafeform.iumfs.twitterfs.files.AbstractTimelineFile.java

License:Apache License

/**
 * Convert Status to formated text.//w  w  w. j  a va  2  s  .  com
 *
 * @param status Status
 * @return formatted text
 */
public static String statusToFormattedString(Status status) {
    // Add user name time..
    StringBuilder sb = new StringBuilder();
    Date createdDate = status.getCreatedAt();
    SimpleDateFormat simpleFormat = new SimpleDateFormat("MM/dd HH:mm:ss");

    sb.append(simpleFormat.format(createdDate));
    sb.append(" ");
    sb.append(status.getUser().getScreenName());
    sb.append("[");
    sb.append(status.getUser().getName());
    sb.append("] \n");
    sb.append(status.getText());
    sb.append("\n\n");
    return sb.toString();
}

From source file:com.chimpler.example.TwitterStatusProducer.java

License:Apache License

public synchronized void startSample(String username, String password) {
    if (twitterStream != null) {
        return;//w  w w  .j a va  2s .c  o m
    }
    TwitterStreamFactory factory = new TwitterStreamFactory(
            new ConfigurationBuilder().setUser(username).setPassword(password).build());
    twitterStream = factory.getInstance();
    twitterStream.addListener(new StatusAdapter() {
        public void onStatus(Status status) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "OK");
            map.put("createdAt", status.getCreatedAt().toString());
            map.put("username", status.getUser().getName());
            map.put("profileImageUrl", status.getUser().getMiniProfileImageURL());
            map.put("text", status.getText());
            cometTwitterService.publishMessage(map, Long.toString(status.getId()));
        }

        @Override
        public void onException(Exception ex) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", "ERR");
            map.put("text", ex.getMessage());
            cometTwitterService.publishMessage(map, "-1");
            stopSample();
        }
    });
    logger.log(Level.INFO, "Starting listening to twitter sample");
    twitterStream.sample();
}

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

License:Apache License

/**
 * Start processing events. This uses the Twitter Streaming API to sample
 * Twitter, and process tweets./*w  w  w.j a v a  2  s.c  o m*/
 */
@Override
public void start() {
    // The channel is the piece of Flume that sits between the Source and Sink,
    // and is used to process events.
    final ChannelProcessor channel = getChannelProcessor();

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

    // The StatusListener is a twitter4j API, which can be added to a Twitter
    // stream, and will execute methods every time a message comes in through
    // the stream.
    StatusListener listener = new StatusListener() {
        // The onStatus method is executed every time a new tweet comes in.
        public void onStatus(Status status) {
            // The EventBuilder is used to build an event using the headers and
            // the raw JSON of a tweet
            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) {
        }

        public void onStallWarning(StallWarning warning) {
        }
    };

    logger.debug("Setting up Twitter sample stream using consumer key {} and" + " access token {}",
            new String[] { consumerKey, accessToken });
    // Set up the stream's listener (defined above),
    twitterStream.addListener(listener);

    // 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.company.TwitterPopularLinks.java

License:Apache License

public void sparkStreaming(SparkConf conf) {

    ///Creates Streaming Context
    JavaStreamingContext jsc = new JavaStreamingContext(conf, Durations.seconds(1));

    //Create a Twitter
    Twitter twitter = new TwitterFactory().getInstance();
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
    twitter.setOAuthAccessToken(new AccessToken(accessTokenKey, accessTokenKey_secret));

    JavaDStream<Status> stream = TwitterUtils.createStream(jsc, twitter.getAuthorization());

    JavaDStream<String> words = stream.map(new Function<Status, String>() {
        public String call(Status status) {
            return status.getText();
        }/*from w  w w .ja va  2s.com*/
    });

    JavaDStream<String> statuses = words.flatMap(new FlatMapFunction<String, String>() {
        public Iterable<String> call(String in) {
            return Arrays.asList(in.split(" "));
        }
    });
    //Get the stream of hashtags from the stream of tweets
    JavaDStream<String> hashTags = statuses.filter(new Function<String, Boolean>() {
        public Boolean call(String word) {
            return word.startsWith("#");
        }
    });
    //Count the hashtags over a 5 minute window
    JavaPairDStream<String, Integer> tuples = hashTags.mapToPair(new PairFunction<String, String, Integer>() {
        public Tuple2<String, Integer> call(String in) {
            return new Tuple2<String, Integer>(in, 1);
        }
    });
    //count these hashtags over a 5 minute moving window
    JavaPairDStream<String, Integer> counts = tuples
            .reduceByKeyAndWindow(new Function2<Integer, Integer, Integer>() {
                public Integer call(Integer i1, Integer i2) {
                    return i1 + i2;
                }
            }, new Function2<Integer, Integer, Integer>() {
                public Integer call(Integer i1, Integer i2) {
                    return i1 - i2;
                }
            }, new Duration(60 * 5 * 1000), new Duration(1 * 1000));

    counts.print();
    //jsc.checkpoint(checkPoint);
    jsc.start();
    jsc.awaitTermination();

}

From source file:com.controller.SearchController.java

License:Open Source License

public static String displayTweets(String query) {
    StringBuilder sb = new StringBuilder();
    sb.append(//from   w  ww  .  j  a  va 2 s.c  o m
            " <h3 class=\"text-center\"><i class=\"fa fa-twitter-square\"></i>&nbsp;Comments from Twitter</h3>");
    List<Status> tweet = TwitterSearch.configure(query);
    if (tweet.isEmpty()) {
        return "<span class=\"label label-info\">No Tweets results found.</span>";
    }

    if (tweet.size() > 5) {
        // Display a maximum of 5 tweets.
        tweet.subList(5, tweet.size()).clear();
    }

    for (Status status : tweet) {
        sb.append("<div class='thumbnail row'>");
        sb.append("<div class=\"text-center col-xs-2\">");
        sb.append("<img class=\"img-responsive\"' src=");
        sb.append(status.getUser().getBiggerProfileImageURL());
        sb.append(">");
        sb.append("</div>");
        sb.append("<div class=\"col-xs-10\">");
        sb.append(status.getCreatedAt());
        sb.append("<br />");
        sb.append("<strong>");
        sb.append(status.getUser().getScreenName());
        sb.append("&nbsp;</strong>said<br />");
        sb.append(status.getText());
        sb.append("</div>");
        sb.append("</div>");
    }

    return sb.toString();
}

From source file:com.daemon.database.Transactor.java

License:Open Source License

/**
 * Saves a given tweet in the DB if that tweet is not already saved. Only saves
 * the tweet no other information!/*from  ww  w  . j av a 2  s  .  com*/
 * 
 * @param tweet The tweet to be saved.
 * @throws SQLException
 */
private void saveTweet(Status tweet, RegressionSentimentClassifier sentimentClassifier) throws SQLException {
    // for reweet, save the original tweet first
    if (tweet.getRetweetedStatus() != null) {
        saveAllTransactionSafe(tweet.getRetweetedStatus(), null, sentimentClassifier);
    }
    // then, save the current tweet

    // 1: Set Tweet ID
    prepStatementTweet.setLong(1, tweet.getId());

    // 2 / 3: Set GeoLocation
    if (tweet.getGeoLocation() != null) {
        prepStatementTweet.setFloat(2, (float) tweet.getGeoLocation().getLatitude());
        prepStatementTweet.setFloat(3, (float) tweet.getGeoLocation().getLongitude());
    } else {
        prepStatementTweet.setNull(2, java.sql.Types.NULL);
        prepStatementTweet.setNull(3, java.sql.Types.NULL);
    }

    // 4: Set User ID
    prepStatementTweet.setLong(4, tweet.getUser().getId());

    // 5: Set Reply-Tweet ID
    if (tweet.getInReplyToStatusId() == -1) {
        prepStatementTweet.setNull(5, java.sql.Types.NULL);
    } else {
        prepStatementTweet.setLong(5, tweet.getInReplyToStatusId());
    }

    // 6: Set Retweet-ID
    if (tweet.getRetweetedStatus() != null) {
        prepStatementTweet.setLong(6, tweet.getRetweetedStatus().getId());
    } else {
        prepStatementTweet.setNull(6, java.sql.Types.NULL);
    }

    // 7: Set Creation Date of Tweet
    java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(tweet.getCreatedAt().getTime());
    prepStatementTweet.setTimestamp(7, sqlTimestamp);

    // 8-11: Other attributes:
    prepStatementTweet.setString(8, tweet.getSource());
    prepStatementTweet.setString(9, tweet.getText());
    prepStatementTweet.setString(10, tweet.getIsoLanguageCode());
    prepStatementTweet.setInt(11, tweet.getRetweetCount());

    // 12: Sentiment
    Float sentiment = sentimentClassifier.determineSentiment(tweet.getText(), tweet.getIsoLanguageCode());
    if (sentiment == null) {
        prepStatementTweet.setNull(12, java.sql.Types.NULL);
    } else {
        prepStatementTweet.setFloat(12,
                sentimentClassifier.determineSentiment(tweet.getText(), tweet.getIsoLanguageCode()));
    }

    // execute statement
    prepStatementTweet.addBatch();
}