Example usage for twitter4j Twitter getUserTimeline

List of usage examples for twitter4j Twitter getUserTimeline

Introduction

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

Prototype

ResponseList<Status> getUserTimeline() throws TwitterException;

Source Link

Document

Returns the 20 most recent statuses posted from the authenticating user.

Usage

From source file:TimeLine.java

private void btTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btTwitActionPerformed
    // Tombol update status, show setelah update
    txtStatus.setText("");

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

    try {/*  w  w w .  j a  v a2 s .  c o  m*/
        Status status = twitter.updateStatus(txStatus.getText());
        JOptionPane.showMessageDialog(rootPane, "Twit \n [ " + status.getText() + " ]\nTerkirim!");
    } catch (TwitterException ex) {
        JOptionPane.showMessageDialog(rootPane, "Tidak bisa mengirim : " + ex.getMessage());
        Logger.getLogger(TimeLine.class.getName()).log(Level.SEVERE, null, ex);
    }

    List<Status> statuses = null;
    try {
        statuses = twitter.getUserTimeline();

        statuses.stream().forEach((status) -> {
            txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });

        txStatus.setText(""); //reload field
    } catch (TwitterException te) {
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage());
    }
}

From source file:TimeLine.java

private void btReloadTwitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btReloadTwitActionPerformed
    // Tombol reload twit saya
    txtStatus.setText("");

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

    List<Status> statuses = null;
    try {/*w  w w. j  a  v  a 2s . c o m*/
        statuses = twitter.getUserTimeline();

        statuses.stream().forEach((status) -> {
            txtStatus.append(status.getUser().getName() + " : " + status.getText() + " - "
                    + status.getCreatedAt() + " \n Via : " + status.getSource() + "\n\n");
        });

        txStatus.setText(""); //reload field
    } catch (TwitterException te) {
        JOptionPane.showMessageDialog(rootPane, "Failed to Show Status!" + te.getMessage());
    }
}

From source file:SwingAndTweetUI.java

private void jButtoNActionPerformed(java.awt.event.ActionEvent evt) {
    try {//from  ww  w  .  j a  va2 s  .  c  om
        Twitter twitter = new Twitter("username", "password");
        twitter.verifyCredentials();
        JOptionPane.showMessageDialog(null, "You're logged in!");
        java.util.List<Status> statusList = twitter.getUserTimeline();
        String s = String.valueOf(statusList.get(0).getText());
        jTextField1.setText(s);
    } catch (TwitterException e) {

        JOptionPane.showMessageDialog(null, "Login failed");

    }
}

From source file:h2weibo.controllers.CallbackServlet.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpServletRouter r = new HttpServletRouter(request);
    r.setPattern("/:type");

    if (request.getParameter("denied") != null) {
        response.sendRedirect("/");
        return;//  ww  w .  ja  v a2s  . c om
    }

    HttpSession session = request.getSession(false);
    String loginUser = (String) session.getAttribute(Keys.SESSION_LOGIN_USER);
    String token = (String) session.getAttribute(Keys.SESSION_TOKEN);
    String tokenSecret = (String) session.getAttribute(Keys.SESSION_TOKEN_SECRET);
    String oauthVerifier = request.getParameter("oauth_verifier");

    DBHelper helper = (DBHelper) request.getAttribute(Keys.REQUEST_DB_HELPER);

    if (r.is(":type", "weibo")) {
        try {
            Weibo weibo = new Weibo();

            AccessToken accessToken = weibo.getOAuthAccessToken(token, tokenSecret, oauthVerifier);
            if (accessToken != null) {
                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getToken() == null) { // send for the first time
                    session.setAttribute(Keys.SESSION_PROMPT_TWEET,
                            "You are ready to go! Do you want to tweet about this service and share it with your friends?");
                }

                tid.setToken(accessToken.getToken());
                tid.setTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);
            } else {
                log.error("Can't auth " + loginUser + " for Weibo. " + request.getQueryString());
            }
        } catch (WeiboException e) {
            log.error("Weibo Exception", e);
            throw new RuntimeException(e);
        }
    } else if (r.is(":type", "twitter")) {
        try {
            TwitterFactory factory = new TwitterFactory();
            Twitter t = factory.getInstance();

            twitter4j.auth.RequestToken req = (RequestToken) session.getAttribute(Keys.SESSION_REQUEST_TOKEN);
            twitter4j.auth.AccessToken accessToken = t.getOAuthAccessToken(req, oauthVerifier);
            session.removeAttribute(Keys.SESSION_REQUEST_TOKEN);

            if (accessToken != null) {
                t.setOAuthAccessToken(accessToken);
                User user = t.verifyCredentials();
                loginUser = user.getScreenName();

                T2WUser tid = helper.findOneByUser(loginUser);

                if (tid.getTwitterToken() == null) {
                    // save latest id for the first time. sync from that tweet
                    ResponseList<Status> tl = t.getUserTimeline();
                    if (tl.size() > 0) {
                        Status s = tl.get(0);
                        tid.setLatestId(s.getId());
                    }
                }

                tid.setTwitterToken(accessToken.getToken());
                tid.setTwitterTokenSecret(accessToken.getTokenSecret());
                helper.saveUser(tid);

                session.setAttribute(Keys.SESSION_LOGIN_USER, loginUser);
            }
        } catch (TwitterException e) {
            log.error("Twitter Exception", e);
            throw new RuntimeException(e);
        }
    }

    String requestUrl = (String) session.getAttribute(Keys.SESSION_REQUEST_URL);
    if (requestUrl != null) {
        session.removeAttribute(Keys.SESSION_REQUEST_URL);
        response.sendRedirect(requestUrl);
    } else {
        response.sendRedirect("/u/" + loginUser);
    }
}

From source file:mineTwit.Main.java

License:Open Source License

private String getCurrentStatus(Twitter twitter) throws TwitterException {
    // Gets last user tweet from timeline.
    ResponseList<Status> userTimeLine = twitter.getUserTimeline();
    //Split off first line.
    String timeLine = userTimeLine.get(0).getText();
    return timeLine;
}

From source file:org.onehippo.forge.blog.components.socialmedia.TwitterListing.java

License:Apache License

/**
 * Fetches both Tweets and ReTweets for the configured user.
 * Adds them combined in a reversed order (newest first) to the {@link HstRequest}.
 * <p/>/*from   w w w. ja va  2s.  c  o  m*/
 * Required parameters:
 * <dl>
 * <dt>token</dt>
 * <dd>needed for oAuth {@link twitter4j.http.AccessToken}</dd>
 * <dt>tokenSecret</dt>
 * <dd>needed for oAuth {@link twitter4j.http.AccessToken}</dd>
 * <dt>consumerKey<dt>
 * <dd>needed for oAuth</dd>
 * <dt>consumerSecret<dt>
 * <dd>needed for oAuth</dd>
 * </dl>
 */
@Override
public void doBeforeRender(HstRequest request, HstResponse response) throws HstComponentException {
    super.doBeforeRender(request, response);

    request.setAttribute("boxTitle", getParameter("boxTitle", request));

    Twitter twitter = getTwitterObject(request);
    if (twitter == null) {
        return;
    }

    try {
        List<Status> statuses = twitter.getUserTimeline();
        // for backwards compatibility Twitter does not return retweets when the user timeline is requested
        // that's why we have to merge them
        List<Status> retweets = twitter.getRetweetedByMe();
        statuses.addAll(retweets);
        Set<Status> allStatuses = new TreeSet<Status>(Collections.reverseOrder());
        allStatuses.addAll(statuses);
        allStatuses.addAll(retweets);
        if (!allStatuses.isEmpty()) {
            request.setAttribute("statuses", allStatuses);
        }
    } catch (TwitterException e) {
        log.warn("Error getting Twitter status updates", e);
    }

}

From source file:tweets.Tweets.java

/**
 * @param args the command line arguments
 *///w ww. ja v a2s.co  m
public static void main(String[] args) throws Exception {

    ConfigurationBuilder configurtacion = new ConfigurationBuilder();
    configurtacion.setDebugEnabled(true).setOAuthConsumerKey("KdVOb7h8mqcjWIfkXXED2G6sJ")
            .setOAuthConsumerSecret("EXImfgfGCYIbWZIOSEeYVvaDE5oxwJZY7UIuwUusbyRWf2ds7l")
            .setOAuthAccessToken("785481406654722049-aRARaHgZujPZIdpYla4mVZIMMlvzJRb")
            .setOAuthAccessTokenSecret("YWWQwbFw8K7rxsnivwpBRZVoQlUhMYy7gOs7KUWOb8Rvy");
    Twitter twitter = new TwitterFactory(configurtacion.build()).getInstance();
    twitter.getUserTimeline();

    String hashtag = "#ElectionNight";
    Query busqueda = new Query(hashtag);
    int numeroTweets = 1500;
    long ultimo = Long.MAX_VALUE;
    ArrayList<Status> tweets = new ArrayList<Status>();

    while (tweets.size() < numeroTweets) {
        if (numeroTweets - tweets.size() > 255) {
            busqueda.setCount(255);
        } else {
            busqueda.setCount(numeroTweets - tweets.size());
        }
        try {
            QueryResult result = twitter.search(busqueda);
            tweets.addAll(result.getTweets());
            System.out.println("Generados " + tweets.size() + " tweets" + "\n");
            for (Status t : tweets) {
                if (t.getId() < ultimo) {
                    ultimo = t.getId();
                }
                System.out.println("Generados " + tweets.size() + " tweets" + "\n");

            }

        } catch (TwitterException excepcion) {
            System.out.println("Sin conexin " + excepcion);
        }
        ;
        busqueda.setMaxId(ultimo - 1);
    }

    // guardamos los datos
    java.util.Date fecha = new Date();
    int hora = fecha.getHours();
    int minuto = fecha.getMinutes();
    System.out.println();
    String nombre = "Datos_" + hashtag + " " + hora + " " + minuto + ".txt";
    File f = new File(nombre);
    FileWriter fw = new FileWriter(f);
    BufferedWriter bw = new BufferedWriter(fw);

    System.out.println("identificador\tUsuario\ttweet\n");
    for (int i = 0; i < tweets.size(); i++) {
        Status estadoTweet = (Status) tweets.get(i);

        GeoLocation loc = estadoTweet.getGeoLocation();
        String user = estadoTweet.getUser().getScreenName();
        String msg = estadoTweet.getText();
        Boolean sensitive = estadoTweet.isPossiblySensitive();
        int fav = estadoTweet.getFavoriteCount();

        System.out.println("Id: " + i + "| User: " + user + "| Texto: " + msg + "| SentimientoPositivo: "
                + sensitive + "$\n");
        int id = i + 1;
        bw.append(msg + " | " + sensitive + ";");
        bw.newLine();

    }
    bw.close();
}

From source file:WebApp.TwitterConsumer.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    OAuthConsumer consumer = null;// www .  j a  va2 s  .c  om
    OAuthAccessor accessor = null;
    try {
        consumer = CookieConsumer.getConsumer("twitter", getServletContext());
        accessor = CookieConsumer.getAccessor(request, response, consumer);

        String TWITTER_CONSUMER_KEY = consumer.consumerKey;
        String TWITTER_SECRET_KEY = consumer.consumerSecret;
        String TWITTER_ACCESS_TOKEN = accessor.accessToken;
        String TWITTER_ACCESS_TOKEN_SECRET = accessor.tokenSecret;
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(TWITTER_CONSUMER_KEY)
                .setOAuthConsumerSecret(TWITTER_SECRET_KEY).setOAuthAccessToken(TWITTER_ACCESS_TOKEN)
                .setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET);
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE html>");
        out.println("<html lang=\"es\"><head>");
        out.println("<meta charset=\"UTF-8\">");
        out.println(
                "   <link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>\n"
                        + "   <link rel=\"stylesheet\" href=\"css/style.css\">\n"
                        + "   <link rel=\"stylesheet\" href=\"css/bootstrap.css\">");
        out.println("<link rel=\"stylesheet\" href=\"css/flat-ui.css\">\n");
        //Query query = new Query("Dom2D");
        //QueryResult result;
        //do {
        //result = twitter.
        out.println("<body><header>\n" + "      <img src =\"Stalker.jpg \" width = 800 >\n" + "      <br>\n"
                + "      <br>\n" + "   </header>\n" + "   <section style=\"height: auto;\">\n"
                //+ "      <p> \n"
                //+ "          <input id=\"user\" type=\"text\" placeholder=\"Nombre de usuario\"/>"
                //+ "      </p>\n"
                + "      <h4 style=\"font-family:Comic Sans MS\">Timeline</h4>\n");
        List<Status> tweets = twitter.getUserTimeline();
        tweets.stream().forEach((tweet) -> {
            out.println("      <div class=\"tweet\">\n" + "         <div class=\"info\">\n"
                    + "            <p class=\"user\">\n" + "               <span class=\"name\">"
                    + tweet.getUser().getName() + "</span>\n" + "               <span class=\"username\">"
                    + tweet.getUser().getScreenName() + "</span>\n" + "               <span class=\"date\">"
                    + tweet.getCreatedAt() + "</span>\n" + "            </p>\n"
                    + "            <p class=\"text\">" + tweet.getText() + "</p>\n" + "         </div>\n"
                    + "      </div>\n");
        });
        out.println("   </section>\n" + "   <footer>\n"
                + "         <a href = \"https://www.facebook.com/\">Desarrolladores</a>\n"
                + "<a href=\"Reset\">Logout</a>" + "   </footer></body>");
        out.println("</html>");
        //} while ((query = result.nextQuery()) != null);
    } catch (Exception e) {
        CookieConsumer.handleException(e, request, response, consumer);
    }
}