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:edu.cmu.geolocator.coder.utils.JSON2Tweet.java

License:Apache License

public JSONTweet readLine() {
    String line;/*from  w  w  w  . jav a 2 s  . c  o m*/
    try {
        line = br.readLine();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }
    if (line == null)
        return null;

    Status tweet = null;
    try {
        // parse json to object type
        tweet = DataObjectFactory.createStatus(line);
    } catch (TwitterException e) {
        System.err.println("error parsing tweet object");
        return null;
    }

    jsontweet.JSON = line;
    jsontweet.id = tweet.getId();
    jsontweet.source = tweet.getSource();
    jsontweet.text = tweet.getText();
    jsontweet.createdat = tweet.getCreatedAt();
    jsontweet.tweetgeolocation = tweet.getGeoLocation();

    User user;
    if ((user = tweet.getUser()) != null) {

        jsontweet.userdescription = user.getDescription();
        jsontweet.userid = user.getId();
        jsontweet.userlanguage = user.getLang();
        jsontweet.userlocation = user.getLocation();
        jsontweet.username = user.getName();
        jsontweet.usertimezone = user.getTimeZone();
        jsontweet.usergeoenabled = user.isGeoEnabled();

        if (user.getURL() != null) {
            String url = user.getURL().toString();

            jsontweet.userurl = url;

            String addr = url.substring(7).split("/")[0];
            String[] countrysuffix = addr.split("[.]");
            String suffix = countrysuffix[countrysuffix.length - 1];

            jsontweet.userurlsuffix = suffix;

            try {
                InetAddress address = null;//InetAddress.getByName(user.getURL().getHost());

                String generate_URL
                // =
                // "http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="
                        = "http://www.geoplugin.net/php.gp?ip=" + address.getHostAddress();
                URL data = new URL(generate_URL);
                URLConnection yc = data.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                String inputLine;
                String temp = "";
                while ((inputLine = in.readLine()) != null) {
                    temp += inputLine + "\n";
                }
                temp = temp.split("s:2:\"")[1].split("\"")[0];

                jsontweet.userurllocation = temp;

            } catch (Exception uhe) {
                //uhe.printStackTrace();
                jsontweet.userurllocation = null;
            }
        }
    }

    return jsontweet;

}

From source file:edu.cmu.geolocator.coder.utils.JSON2Tweet.java

License:Apache License

public static JSONTweet getJSONTweet(String JSONString) {
    JSONTweet jsontweet = new JSONTweet();
    if (JSONString == null)
        return null;

    Status tweet = null;
    try {/* www. j  a  va2s.  c o  m*/
        // parse json to object type
        tweet = DataObjectFactory.createStatus(JSONString);
    } catch (TwitterException e) {
        System.err.println("error parsing tweet object");
        return null;
    }

    jsontweet.JSON = JSONString;
    jsontweet.id = tweet.getId();
    jsontweet.source = tweet.getSource();
    jsontweet.text = tweet.getText();
    jsontweet.createdat = tweet.getCreatedAt();
    jsontweet.tweetgeolocation = tweet.getGeoLocation();

    User user;
    if ((user = tweet.getUser()) != null) {

        jsontweet.userdescription = user.getDescription();
        jsontweet.userid = user.getId();
        jsontweet.userlanguage = user.getLang();
        jsontweet.userlocation = user.getLocation();
        jsontweet.username = user.getName();
        jsontweet.usertimezone = user.getTimeZone();
        jsontweet.usergeoenabled = user.isGeoEnabled();

        if (user.getURL() != null) {
            String url = user.getURL().toString();

            jsontweet.userurl = url;

            String addr = url.substring(7).split("/")[0];
            String[] countrysuffix = addr.split("[.]");
            String suffix = countrysuffix[countrysuffix.length - 1];

            jsontweet.userurlsuffix = suffix;

            try {
                InetAddress address = null;//InetAddress.getByName(user.getURL().getHost());

                String generate_URL
                // =
                // "http://www.geobytes.com/IpLocator.htm?GetLocation&template=php3.txt&IpAddress="
                        = "http://www.geoplugin.net/php.gp?ip=" + address.getHostAddress();
                URL data = new URL(generate_URL);
                URLConnection yc = data.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
                String inputLine;
                String temp = "";
                while ((inputLine = in.readLine()) != null) {
                    temp += inputLine + "\n";
                }
                temp = temp.split("s:2:\"")[1].split("\"")[0];

                jsontweet.userurllocation = temp;

            } catch (Exception uhe) {
                //uhe.printStackTrace();
                jsontweet.userurllocation = null;
            }
        }
    }

    return jsontweet;

}

From source file:edu.cmu.geoparser.ui.CommandLine.TwitterJsonParser.java

License:Apache License

public static void main(String argv[]) throws IOException {

    /**//from  www .j a v a  2  s.c  om
     * Preparation: initialize the parser.
     */
    String uri = "/Users/indri/Eclipse_workspace/";
    String geonames = uri + "GeoNames/cities1000.txt";
    String gazindex = uri + "GazIndex";
    CollaborativeIndex ci = new CollaborativeIndex()
            .config("GazIndex/StringIndex", "GazIndex/InfoIndex", "mmap", "mmap").open();
    EnglishParser enparser = new EnglishParser("res/", ci, false);

    ContextDisamb c = new ContextDisamb();

    /**
     * read the tweets, one Json tweet per line.
     * 
     */
    BufferedReader br = GetReader.getUTF8FileReader("SampleInput/jsonTweets.txt");
    String line = null;
    while ((line = br.readLine()) != null) {

        // parse the tweet json file into a Status object( twitter4j convention).
        Status rawTweet = null;
        try {
            rawTweet = DataObjectFactory.createStatus(line.trim());
        } catch (TwitterException e) {
            System.err.println("JSON File is corrupted. Continue");
            /**
             * Do something to handle this problem. Ignore it, or output the JSON.
             */
            continue;
        }

        /**
         *  wrap it into our tweet object. Here we only copy the text.
         */
        Tweet aTweet = new Tweet();
        aTweet.setText(rawTweet.getText());

        /**
         *  The next several lines are identical to CmdInputParser.java
         */

        List<String> match = enparser.parse(aTweet);

        if (match == null || match.size() == 0) {
            System.out.println("No toponyms in text. Do something, then continue.");
            continue;
        } else { // if matches are found:
            HashSet<String> reducedmatch = new HashSet<String>();
            for (String s : match)
                reducedmatch.add(s.substring(3, s.length() - 3));

            HashMap<String, String[]> result = c.returnBestTopo(ci, reducedmatch);

            if (result == null) {
                System.out.println("No GPS for any location is found.");
            } else {
                System.out.println("The grounded location(s) are: (topo: country_state, latitude, longitude.");
                for (String topo : result.keySet())
                    System.out.println(topo + ": " + result.get(topo)[2] + " " + result.get(topo)[0] + " "
                            + result.get(topo)[1]);
            }

        }
    }
}

From source file:edu.csupomona.nlp.tool.crawler.Twitter.java

/**
 * Construct Twitter for crawling with Stream API
 * @throws IOException//from   w ww . j a  v a2s  .co  m
 */
public Twitter() throws IOException {
    // init default parameters
    lang_ = "en";
    includeRetweet_ = false;

    // init default restriction
    sizeLimit_ = 3000;
    hourLimit_ = 24; // 24 hours

    // read and construct property
    Properties key = new Properties();
    key.load(getClass().getResourceAsStream("/etc/twitter.properties"));

    // set authentication key&token
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(key.getProperty("ConsumerKey"))
            .setOAuthConsumerSecret(key.getProperty("ConsumerSecret"))
            .setOAuthAccessToken(key.getProperty("AccessToken"))
            .setOAuthAccessTokenSecret(key.getProperty("AccessTokenSecret"));

    // create twitter stream
    ts_ = new TwitterStreamFactory(cb.build()).getInstance();

    // add listener
    ts_.addListener(new StatusListener() {

        @Override
        public void onStatus(Status status) {
            // only record tweet matches requirement
            if (isRetweetMatch(status) && !isIdRedundant(status)) {
                String text = status.getText();
                Long id = status.getId();

                text = text.replaceAll("\\n", ""); // to the same line
                tweet_.add(id.toString() + ":" + text);
                idSet_.add(id);
            }

            System.out.println(
                    "[" + idSet_.size() + "/" + sizeLimit_ + "]" + status.getId() + ": " + status.getText());

            // when limit is reached
            if (isLimitReached()) {
                try {
                    // write tweet to file
                    finishup();

                } catch (IOException ex) {
                    Logger.getLogger(Twitter.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice sdn) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void onTrackLimitationNotice(int i) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void onScrubGeo(long l, long l1) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

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

            // anything wrong, just save everything we have and stop
            try {
                finishup();

            } catch (IOException ex) {
                Logger.getLogger(Twitter.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

}

From source file:edu.uci.ics.asterix.external.util.TweetProcessor.java

License:Apache License

public AMutableRecord processNextTweet(Status tweet) {
    User user = tweet.getUser();// w  ww .  j  a va2s  .c  o  m
    ((AMutableString) mutableUserFields[0]).setValue(getNormalizedString(user.getScreenName()));
    ((AMutableString) mutableUserFields[1]).setValue(getNormalizedString(user.getLang()));
    ((AMutableInt32) mutableUserFields[2]).setValue(user.getFriendsCount());
    ((AMutableInt32) mutableUserFields[3]).setValue(user.getStatusesCount());
    ((AMutableString) mutableUserFields[4]).setValue(getNormalizedString(user.getName()));
    ((AMutableInt32) mutableUserFields[5]).setValue(user.getFollowersCount());

    ((AMutableString) mutableTweetFields[0]).setValue(tweet.getId() + "");

    for (int i = 0; i < 6; i++) {
        ((AMutableRecord) mutableTweetFields[1]).setValueAtPos(i, mutableUserFields[i]);
    }
    if (tweet.getGeoLocation() != null) {
        ((AMutableDouble) mutableTweetFields[2]).setValue(tweet.getGeoLocation().getLatitude());
        ((AMutableDouble) mutableTweetFields[3]).setValue(tweet.getGeoLocation().getLongitude());
    } else {
        ((AMutableDouble) mutableTweetFields[2]).setValue(0);
        ((AMutableDouble) mutableTweetFields[3]).setValue(0);
    }
    ((AMutableString) mutableTweetFields[4]).setValue(getNormalizedString(tweet.getCreatedAt().toString()));
    ((AMutableString) mutableTweetFields[5]).setValue(getNormalizedString(tweet.getText()));

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

    return mutableRecord;

}

From source file:edu.uml.TwitterDataMining.TwitterConsumer.java

/**
 * Save the results that we got from queryTwitter method This will append to
 * a file if it already exists// w  w w .j  a v a  2 s  .  com
 *
 * @param tweets
 * @param filePath
 */
public static void saveResults(List<Status> tweets, String filePath) {
    try (FileWriter fw = new FileWriter(filePath, true)) { // try with resources (will close file pointers)
        for (Status tweet : tweets) {
            fw.write("@" + tweet.getUser().getScreenName() + "\t" + tweet.getText() + "\n");
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:ehealth.external.twitter.UpdateStatus.java

License:Apache License

/**
 * Post tweets on Twitter/*from  w  w w .  j a v a 2 s  . com*/
 *
 * @param tweet
 * 
 */
public int postTwitterStatus(String tweet) {

    try {

        loginTwitter();

        Status status = twitter.updateStatus(tweet);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
        return 1;
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
    } catch (Exception e) {

    }
    return 0;
}

From source file:ens.demo.twitter.TwittEmergencyMessage.java

@Override
public void run() {
    try {/* w w  w  .  j  a  v a  2s  .com*/
        if (toCustomer.getToken() == null || toCustomer.getToken().isEmpty()) {
            return;
        }
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Properties properties = new Properties();
        properties.load(classLoader.getResourceAsStream("twitter4j.properties"));
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(properties.getProperty("twitter4j.oauth.consumerKey"))
                .setOAuthConsumerSecret(properties.getProperty("twitter4j.oauth.consumerSecret"))
                .setOAuthAccessToken(toCustomer.getToken())
                .setOAuthAccessTokenSecret(toCustomer.getTokenSecret());
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        StatusUpdate update = new StatusUpdate(message);
        Status status = twitter.updateStatus(update);
        System.out.println("Successfully updated the status to [" + status.getText() + "].");
    } catch (TwitterException ex) {
        Logger.getLogger(TwittEmergencyMessage.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(TwittEmergencyMessage.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:entities.TwitterFeed.java

public void initTimeline() {
    timelineFrame = new JFrame("@SIM_IST Timeline");

    timelineFrame.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    timelineBack = new JButton("Back");
    timelineBack.addActionListener(this);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0.5;//from   ww w.j a  v  a 2  s .  c o  m
    c.gridx = 1;
    c.gridy = 1;
    c.gridwidth = 1;
    timelineFrame.add(timelineBack, c);

    timelineTweets = new JTextArea();
    Font font = new Font("Gotham Narrow", Font.BOLD, 12);
    timelineTweets.setFont(font);
    timelineTweets.setEditable(false);
    timelineScrollPane = new JScrollPane(timelineTweets);
    c.fill = GridBagConstraints.HORIZONTAL;
    c.weightx = 0;
    c.ipady = 200;
    c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 3;
    timelineFrame.add(timelineScrollPane, c);

    KeyReader keys = new KeyReader();

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(keys.getConsumerKey())
            .setOAuthConsumerSecret(keys.getConsumerSecret()).setOAuthAccessToken(keys.getAccessToken())
            .setOAuthAccessTokenSecret(keys.getAccessTokenSecret());
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    try {
        System.out.println("timeline retreval worked");

        List<Status> statuses = twitter.getHomeTimeline();
        for (Status status : statuses) {
            timelineTweets
                    .append("@" + status.getUser().getScreenName() + " : " + status.getText() + "\n" + "\n");
            timelineTweets.setLineWrap(true);
            timelineTweets.setWrapStyleWord(true);
            timelineTweets.setCaretPosition(0);
            System.out.println("@" + status.getUser().getName() + " : " + status.getText());
        }

    } catch (TwitterException te) {
        System.out.print("timeline retreval failed");
        te.printStackTrace();
    }

    timelineFrame.pack();
    timelineFrame.setSize(600, 300);
    timelineFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    timelineFrame.setLocationRelativeTo(null);
    timelineFrame.setVisible(true);
}

From source file:es.portizsan.twitrector.tasks.TweetSearchTask.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    long before = System.currentTimeMillis() - (1000 * 60 * 15);
    try {//from   www. ja v a 2 s  .  c om
        List<Twitrector> trl = new TwitrectorService().getTwitrectors();
        if (trl == null || trl.isEmpty()) {
            logger.log(Level.WARNING, "No Twitrectors found!!!!!");
            return;
        }
        for (Twitrector tr : trl) {
            logger.info("Searching for :" + tr.getQuery());
            String search = tr.getQuery();
            Twitter twitter = new TwitterService().getTwitterInstance();
            Query query = new Query(search);
            query.setLocale("es");
            query.setCount(100);
            if (tr.getLocation() != null) {
                GeoLocation location = new GeoLocation(tr.getLocation().getLatitude(),
                        tr.getLocation().getLongitude());
                Unit unit = Unit.valueOf(tr.getLocation().getUnit().name());
                query.setGeoCode(location, tr.getLocation().getRadius(), unit);
            }
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    if (tweet.getCreatedAt().getTime() < before)
                        continue;
                    Queue queue = QueueFactory.getQueue("default");
                    queue.add(TaskOptions.Builder.withUrl("/tasks/tweetReply")
                            .param("statusId", String.valueOf(tweet.getId()))
                            .param("message", "@" + tweet.getUser().getScreenName() + " "
                                    + String.valueOf(tr.getResponse())));

                    logger.info("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
        }
    } catch (TwitterException te) {
        logger.log(Level.WARNING, "Failed to search tweets: ", te);
    }
}