Example usage for twitter4j Twitter getHomeTimeline

List of usage examples for twitter4j Twitter getHomeTimeline

Introduction

In this page you can find the example usage for twitter4j Twitter getHomeTimeline.

Prototype

ResponseList<Status> getHomeTimeline() throws TwitterException;

Source Link

Document

Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends.

Usage

From source file:TimeLine.java

private void btTimelineActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTimelineActionPerformed
    // TODO add your handling code here:
    txtTimeline.setText("");

    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();

    List<Status> statuses = null;
    try {/*  ww w.j a v a 2  s  .c  om*/
        statuses = twitter.getHomeTimeline();

        statuses.stream().forEach((status) -> {
            txtTimeline.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });
    } catch (TwitterException ex) {
        Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + ex.getMessage());
    }
}

From source file:NewMain.java

/**
 * @param args the command line arguments
 */// w w  w.j av  a 2  s.com

public static void main(String[] args) throws TwitterException {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    ResponseList<twitter4j.Status> statuses = twitter.getHomeTimeline();
    System.out.println("Mostrando el timeline...");
    for (twitter4j.Status status : statuses) {
        System.out.println("@" + status.getUser().getScreenName() + ": " + status.getText());

    }
}

From source file:Demo.java

/**
 * Main method./*from  w w w . j a v a 2s .com*/
 *
 * @param args
 * @throws TwitterException
 */
public static void main(String[] args) throws TwitterException, IOException {

    // The TwitterFactory object provides an instance of a Twitter object
    // via the getInstance() method. The Twitter object is the API consumer.
    // It has the methods for interacting with the Twitter API.
    TwitterFactory tf = new TwitterFactory();
    Twitter twitter = tf.getInstance();

    boolean keepItGoinFullSteam = true;
    do {
        // Main menu
        Scanner input = new Scanner(System.in);
        System.out.print("\n--------------------" + "\nH. Home Timeline\nS. Search\nT. Tweet"
                + "\n--------------------" + "\nA. Get Access Token\nQ. Quit" + "\n--------------------\n> ");
        String choice = input.nextLine();

        try {

            // Home Timeline
            if (choice.equalsIgnoreCase("H")) {

                // Display the user's screen name.
                User user = twitter.verifyCredentials();
                System.out.println("\n@" + user.getScreenName() + "'s timeline:");

                // Display recent tweets from the Home Timeline.
                for (Status status : twitter.getHomeTimeline()) {
                    System.out.println("\n@" + status.getUser().getScreenName() + ": " + status.getText());
                }

            } // Search
            else if (choice.equalsIgnoreCase("S")) {

                // Ask the user for a search string.
                System.out.print("\nSearch: ");
                String searchStr = input.nextLine();

                // Create a Query object.
                Query query = new Query(searchStr);

                // Send API request to execute a search with the given query.
                QueryResult result = twitter.search(query);

                // Display search results.
                result.getTweets().stream().forEach((Status status) -> {
                    System.out.println("\n@" + status.getUser().getName() + ": " + status.getText());
                });

            } // Tweet
            else if (choice.equalsIgnoreCase("T")) {

                boolean isOkayLength = true;
                String tweet;
                do {
                    // Ask the user for a tweet.
                    System.out.print("\nTweet: ");
                    tweet = input.nextLine();

                    // Ensure the tweet length is okay.
                    if (tweet.length() > 140) {
                        System.out.println("Too long! Keep it under 140.");
                        isOkayLength = false;
                    }
                } while (isOkayLength == false);

                // Send API request to create a new tweet.
                Status status = twitter.updateStatus(tweet);
                System.out.println("Just tweeted: \"" + status.getText() + "\"");

            } // Get Access Token
            else if (choice.equalsIgnoreCase("A")) {

                // First, we ask Twitter for a request token.
                RequestToken reqToken = twitter.getOAuthRequestToken();
                System.out.println("\nRequest token: " + reqToken.getToken() + "\nRequest token secret: "
                        + reqToken.getTokenSecret());

                AccessToken accessToken = null;
                while (accessToken == null) {

                    // The authorization URL sends the request token to Twitter in order
                    // to request an access token. At this point, Twitter asks the user
                    // to authorize the request. If the user authorizes, then Twitter
                    // provides a PIN.
                    System.out
                            .print("\nOpen this URL in a browser: " + "\n    " + reqToken.getAuthorizationURL()
                                    + "\n" + "\nAuthorize the app, then enter the PIN here: ");
                    String pin = input.nextLine();
                    try {
                        // We use the provided PIN to get the access token. The access
                        // token allows this app to access the user's account without
                        // knowing his/her password.
                        accessToken = twitter.getOAuthAccessToken(reqToken, pin);
                    } catch (TwitterException te) {
                        System.out.println(te.getMessage());
                    }
                }
                System.out.println("\nAccess token: " + accessToken.getToken() + "\nAccess token secret: "
                        + accessToken.getTokenSecret() + "\nSuccess!");

            } // Quit
            else if (choice.equalsIgnoreCase("Q")) {

                keepItGoinFullSteam = false;
                GeoApiContext context = new GeoApiContext()
                        .setApiKey("AIzaSyArz1NljiDpuOriFWalOerYEdHOyi8ow8Y");

                System.out.println(GeocodingApi.geocode(context, "Sigma Phi Epsilon, Lincoln, Nebraska, USA")
                        .await()[0].geometry.location.toString());
                System.out.println(GeocodingApi.geocode(context, "16th and R, Lincoln, Nebraska, USA")
                        .await()[0].geometry.location.toString());
                File htmlFile = new File("map.html");
                Desktop.getDesktop().browse(htmlFile.toURI());
            } // Bad choice
            else {

                System.out.println("Invalid option.");
            }

        } catch (IllegalStateException ex) {
            System.out.println(ex.getMessage());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }

    } while (keepItGoinFullSteam == true);
}

From source file:GetTweetsAndSaveToFile.java

License:Apache License

/**
 * Usage: java twitter4j.examples.user.ShowUser [screen name]
 *
 * @param args message/*from  w  w  w . j a v  a 2s.  c  o  m*/
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    if (args.length < 1) {
        System.out.println("Usage: java twitter4j.examples.user.ShowUser [screen name]");
        System.exit(-1);
    }
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer("men2JyLEaAsxcbfmgzOAwUnTp",
                "2AGN0ie9TfCDJyWeH8qhTLtMhqRvRlNBtQU3lAP2M8k3Xk1KWl");
        RequestToken requestToken = twitter.getOAuthRequestToken();
        System.out.println("Authorization URL: \n" + requestToken.getAuthorizationURL());

        AccessToken accessToken = new AccessToken("2811255124-zigkuv8MwDQbr5s9HdjLRSbg8aCOyxeD2gYGMfH",
                "D7jFABWHQa8QkTWwgYj1ISUbWP8twdfbzNgYkXI3jwySR");

        twitter.setOAuthAccessToken(accessToken);
        /*
        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 available) and hit enter after you granted access.[PIN]:");
        String pin = br.readLine();
        try {
            if (pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken(requestToken);
            }
        } catch (TwitterException te) {
            if (401 == te.getStatusCode()) {
                System.out.println("Unable to get the access token.");
            } else {
                te.printStackTrace();
            }
        }
        }
        */
        System.out.println("Got access token.");
        System.out.println("Access token: " + accessToken.getToken());
        System.out.println("Access token secret: " + accessToken.getTokenSecret());

        User user = twitter.showUser(args[0]);
        if (user.getStatus() != null) {
            System.out.println("@" + user.getScreenName() + " - " + user.getStatus().getText());
        } else {
            // the user is protected
            System.out.println("@" + user.getScreenName());
        }

        FileWriter file = new FileWriter("./" + user.getScreenName() + "_Tweets.txt");
        List<Status> list = twitter.getHomeTimeline();
        for (Status each : list) {
            file.write("Sent by: @" + each.getUser().getScreenName() + " - " + each.getUser().getName() + "---"
                    + each.getText() + "\n");
        }

        file.close();
        System.exit(0);
    } catch (Exception te) {
        te.printStackTrace();
        System.exit(-1);
    }
}

From source file:clientetwitter.ClienteTwitter.java

public static void ReadTimeLine() throws TwitterException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("ZpF1TSpAyQlBLMN7egUz3uT3D")
            .setOAuthConsumerSecret("r2icg36QB6G862Re2IvwHNGuDK25z5awKSeNG9kV9LRpcAmuOW")
            .setOAuthAccessToken("4314010284-QGXKFbFQ5TK4zqbplRsfoP0wL6NTv7bsMJypWex")
            .setOAuthAccessTokenSecret("4v61YXTkzM3Kob0xAHu59ISgM0fTKSLrOuDXTG5ctX7rr");

    TwitterFactory tf = new TwitterFactory(cb.build());
    twitter4j.Twitter tw = tf.getInstance();

    //reading/*from  w  ww. j  a  v  a 2  s  .  co  m*/
    List<Status> statuses = tw.getHomeTimeline();
    for (Status status1 : statuses) {
        System.out.println(status1.getUser().getName() + ": " + status1.getText());
    }

}

From source file:com.arihant15.ActionServlet.java

@RequestMapping("/getTimeline.arihant15")
public void doTimeline(HttpServletRequest req, HttpServletResponse res) throws IOException {
    try {/* ww w  . j  ava2  s .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.eclipsesource.iot.photosensor.example.Main.java

License:Open Source License

private static LightStatus getCurrentStatus(Twitter twitter) throws TwitterException {
    ResponseList<Status> homeTimeline = twitter.getHomeTimeline();
    String text = homeTimeline.get(0).getText();
    if (text.contains("on")) {
        return LightStatus.ON;
    }//from w w w. j  a  v  a2  s.c  om
    return LightStatus.OFF;
}

From source file:com.ikungolf.java.javatwitter.GetHomeTimeline.java

License:Apache License

/**
 * Usage: java twitter4j.examples.timeline.GetHomeTimeline
 *
 * @param args String[]//from   www  . j a va  2  s.c  om
 */
public static void main(String[] args) {
    try {
        // gets Twitter instance with default credentials
        Twitter twitter = new TwitterFactory().getInstance();
        User user = twitter.verifyCredentials();
        List<Status> statuses = twitter.getHomeTimeline();
        System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:com.marklogic.tweetdeck.SaveRawJSON.java

License:Apache License

/**
 * Usage: java twitter4j.examples.json.SaveRawJSON
 *
 * @param args/*from  w w w .j a va2 s  .c om*/
 *            String[]
 */
public static void main(String[] args) {
    Twitter twitter = new TwitterFactory().getInstance();
    System.out.println("Saving public timeline.");
    try {
        new File("statuses").mkdir();
        List<Status> statuses = twitter.getHomeTimeline();
        for (Status status : statuses) {
            String rawJSON = TwitterObjectFactory.getRawJSON(status);
            String fileName = "statuses/" + status.getId() + ".json";
            storeJSON(rawJSON, fileName);
            System.out.println(fileName + " - " + status.getText());
        }
        System.out.print("\ndone.");
        System.exit(0);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.out.println("Failed to store tweets: " + ioe.getMessage());
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:edu.allegheny.gatortweet.GetHomeTimeline.java

License:Apache License

public static void main(String[] args) {
    try {/*from w w w  .j  a  v a 2  s  .c  om*/
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("rPtRCCRqdDyoxHS3E2UARA")
                .setOAuthConsumerSecret("hhDnR4NETStvN4F84km2xuBy3eXJ8l2FnjdL23YPs");
        // gets Twitter instance with default credentials
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        /* Twitter twitter = new TwitterFactory().getInstance(); */
        User user = twitter.verifyCredentials();
        List<Status> statuses = twitter.getHomeTimeline();
        //System.out.println("Showing @" + user.getScreenName() + "'s home timeline.");
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}