Example usage for twitter4j Status getUser

List of usage examples for twitter4j Status getUser

Introduction

In this page you can find the example usage for twitter4j Status getUser.

Prototype

User getUser();

Source Link

Document

Return the user associated with the status.
This can be null if the instance is from User.getStatus().

Usage

From source file:twitah.Metodos.java

/**
 * Used to search for twits/*from  w  w  w  .  j  a v a 2 s .  c  o  m*/
 *
 * @param busca String where we enter the content to search
 */
public static void buscarTwit(String busca) {

    Query query = new Query(busca);
    QueryResult result;
    try {
        result = twitter.search(query);
        for (Status status : result.getTweets()) {
            System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());

        }
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(Metodos.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:twitbak.MentionBak.java

License:Open Source License

public void statusToJson(Status status) throws TwitterException, JSONException {
    JSONObject result = new JSONObject();
    User poster = status.getUser();
    result.put("Poster ID", poster.getId());
    result.put("Poster", poster.getScreenName());
    result.put("Poster Name", poster.getName());
    result.put("Created At", status.getCreatedAt().toString());
    result.put("ID", status.getId());
    result.put("Text", status.getText());
    long inReplyToStatusId = status.getInReplyToStatusId();
    if (inReplyToStatusId != -1) {
        result.put("In Reply To Status ID", status.getInReplyToStatusId());
    }//from   ww  w.  j  av  a2  s.c  o  m
    long inReplyToUserID = status.getInReplyToUserId();
    result.put("In Reply To User ID", inReplyToUserID);
    if (inReplyToUserID != -1) {
        result.put("In Reply To Screen Name", status.getInReplyToScreenName());
    }
    boolean isFavorited = status.isFavorited();
    if (isFavorited) {
        result.put("Favorited", status.isFavorited());
    }
    statusArray().put(result);
}

From source file:twitfeedbot.RespondServlet.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ResponseList<Status> mentions;
    Twitter twit;/*w w w.  j a v a 2 s  .  c o m*/
    StringBuilder builder = new StringBuilder();
    long lastPostId = 0;

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Entity lastPostIdEntity;

    resp.setContentType("text/html");
    resp.getWriter().println("<html>");
    resp.getWriter().println("<body>");
    try {
        ConfigurationBuilder twitterConfigBuilder = new ConfigurationBuilder();
        twitterConfigBuilder.setDebugEnabled(false);

        System.setProperty("WORDNIK_API_KEY", WORDNIK_KEY);
        twitterConfigBuilder.setOAuthConsumerKey(CONSUMER_KEY);
        twitterConfigBuilder.setOAuthConsumerSecret(CONSUMER_SECRET);
        twitterConfigBuilder.setOAuthAccessToken(ACCESS_TOKEN);
        twitterConfigBuilder.setOAuthAccessTokenSecret(ACCESS_SECRET);

        twit = new TwitterFactory(twitterConfigBuilder.build()).getInstance();
        mentions = twit.getMentionsTimeline();

        lastPostIdEntity = datastore.get(KeyFactory.createKey("lastPostIDEntity", "ID"));
        lastPostId = Long.parseLong(lastPostIdEntity.getProperty("lastPostID").toString());

        if (mentions.size() == 0 || mentions.get(0).getId() == lastPostId)
            resp.getWriter().println("No mentions so far...<br>");
        else {
            resp.getWriter().println("Responding to mentions...<br>");
            for (Status mention : mentions) {
                builder.setLength(0); // Clear the String Builder
                if (lastPostId < mention.getId()) {
                    //Figure out how to like a reply with certain words (best fuck etc)
                    if (mention.getUser().getId() == twit.getId())
                        ;//don't respond to myself
                    else if (mention.isRetweeted())
                        ; //don't respond to retweet
                    else if (mention.getText().toLowerCase().contains("bye")) // Say goodbye
                    {
                        builder.setLength(0); // Clear the String Builder 
                        builder.append("@").append(mention.getUser().getScreenName()).append(" Ok. Bye");
                    } else {
                        builder.setLength(0); // Clear the String Builder
                        builder.append("@").append(mention.getUser().getScreenName());
                        builder.append(" ");

                        //Append Wordnik example sentence
                        builder.append(WordApi.topExample(WordsApi.randomWord().getWord()).getText());
                        if (builder.length() > 140) {
                            if (builder.lastIndexOf(";", 110) > 0)
                                builder.setLength(builder.lastIndexOf(";", 110));
                            else if (builder.lastIndexOf(":", 110) > 0)
                                builder.setLength(builder.lastIndexOf(":", 110));
                            else if (builder.lastIndexOf(",", 110) > 0)
                                builder.setLength(builder.lastIndexOf(",", 110));
                            else
                                builder.setLength(110);
                        }
                    }
                    twit.updateStatus(builder.toString());
                    resp.getWriter().println("Reply posted: " + builder.toString() + "<br>");
                    builder.delete(0, builder.length()); //Clear the builder
                }
            }
            //Save last post ID
            lastPostIdEntity.setProperty("lastPostID", (Long.toString(mentions.get(0).getId())));
            datastore.put(lastPostIdEntity);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Input file(s) not found<br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (EntityNotFoundException e) {
        resp.getWriter().println("lastPostID not found. Creating...<br>");
        lastPostIdEntity = new Entity("lastPostIDEntity", "ID");
        //lastPostIdEntity.setProperty("lastPostID", 0);
        lastPostIdEntity.setProperty("lastPostID", "883352596160946176");
        datastore.put(lastPostIdEntity);

    } catch (TwitterException e) {
        resp.getWriter().println("Problem with Twitter <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (KnickerException e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("Problem with Wordnik <br>");
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    } catch (Exception e) {
        e.printStackTrace(System.err);
        resp.getWriter().println("<pre>");
        e.printStackTrace(resp.getWriter());
        resp.getWriter().println("</pre>");
    }
}

From source file:twitter.crawler.TwitterCrawler.java

public static void main(String[] args) {
    try {/*w ww .j  av a2s.co m*/
        // Authorise the library
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setOAuthConsumerKey("AhoydO8uSe4v8NEq7j2ISGFlq");
        cb.setOAuthConsumerSecret("ptKEYwq3G9vpFkqAhvwFLSWFcBW8U1SfqycECwK4cH6wThVba6");
        cb.setOAuthAccessToken("778240255577194496-taafqDIHebrg972oxT5kTqcNd3Uojod");
        cb.setOAuthAccessTokenSecret("DMRmeRahnLJRvCBIGQGTaTzE6Pr3PAZMgMsfWIT5ue3PD");
        Twitter twitter = new TwitterFactory(cb.build()).getInstance();
        User user = twitter.verifyCredentials(); // Get main user

        long cursor = -1;

        // Print user profile
        System.out.println("@" + user.getScreenName());
        System.out.println(user.getId());
        System.out.println(user.getProfileImageURL());
        System.out.println(user.getFriendsCount() + " friends.");
        System.out.println("-------");

        // Print Home Timeline
        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());
        }

        //Print followers
        System.out.println("-------");
        System.out.println("Showing Follwers:");

        PagableResponseList<User> followers;

        //do
        //{
        followers = twitter.getFollowersList(user.getScreenName(), cursor);

        for (User follower : followers) {
            System.out.println("@" + follower.getScreenName());
        }
        //}
        //while ((cursor = followers.getNextCursor())!=-1);

        //Print follwees

        System.out.println("-------");
        System.out.println("Showing Followees:");

        PagableResponseList<User> followees;

        do {
            followees = twitter.getFriendsList(user.getScreenName(), cursor);

            for (User followee : followees) {
                System.out.println("@" + followee.getScreenName());
            }
        } while ((cursor = followees.getNextCursor()) != -1);
    }

    catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:Twitter.FilterStream.java

License:Apache License

public static void main(String[] args) throws TwitterException {

    System.getProperties().put("http.proxyHost", "127.0.0.1");
    System.getProperties().put("http.proxyPort", "8580");

    /* if (args.length < 1) {
    System.out.println("Usage: java twitter4j.examples.PrintFilterStream [follow(comma separated numerical user ids)] [track(comma separated filter terms)]");
    System.exit(-1);//ww w.j a  va2  s.c  om
     }*/

    final FilterStream fs = new FilterStream();

    try {
        fs.LinkMongodb();
    } catch (Exception e) {
        e.printStackTrace();
    }

    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            String str = DataObjectFactory.getRawJSON(status);
            try {
                //JSONObject nnstr = new JSONObject(newstr);  
                DBObject dbObject = (DBObject) JSON.parse(str);
                fs.collection.insert(dbObject);
                //System.out.println(dbObject);  
                fs.count++;
                if (fs.count > 900000000) {
                    fs.mongo.close();
                    System.exit(0);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @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();
        }
    };

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("7ZVgfKiOvBDcDFpytRWSA")
            .setOAuthConsumerSecret("JmeJVeym78arzmGthrDUshQyhkq6nWA9tWLUKxc")
            .setOAuthAccessToken("321341780-Zy7LptVYBZBVvAeQ5GFJ4aKFw8sdqhWBnvA3pDuO")
            .setOAuthAccessTokenSecret("foi8FnQCeN0J5cdwad05Q6d7dbytFayQn1ZOvmhF6Qc");
    cb.setJSONStoreEnabled(true);

    TwitterStreamFactory tf = new TwitterStreamFactory(cb.build());

    TwitterStream twitterStream = tf.getInstance();
    twitterStream.addListener(listener);
    ArrayList<Long> follow = new ArrayList<Long>();
    ArrayList<String> track = new ArrayList<String>();

    //String[] keywords = {"RT @justinbieber"};
    String[] keywords = { "27260086" }; // user_id(justinbieber)
    for (String arg : keywords) {
        if (isNumericalArgument(arg)) {
            for (String id : arg.split(",")) {
                follow.add(Long.parseLong(id));
            }
        } else {
            track.addAll(Arrays.asList(arg.split(",")));
        }
    }
    long[] followArray = new long[follow.size()];
    for (int i = 0; i < follow.size(); i++) {
        followArray[i] = follow.get(i);
    }
    String[] trackArray = track.toArray(new String[track.size()]);

    // filter() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
    //twitterStream.filter(new FilterQuery(0, followArray, trackArray));
    twitterStream.filter(new FilterQuery(followArray));
}

From source file:Twitter.Frame.java

public Document statustoJSON(Status status) {
    Document doc = new Document();
    if (status.getText() != null)
        doc.append("tweet", status.getText());
    if (status.getUser().getName() != null)
        doc.append("name", status.getUser().getName());
    if (status.getPlace() != null)
        doc.append("place", status.getPlace().toString());
    if (status.getUser().getScreenName() != null)
        doc.append("nick", status.getUser().getScreenName());
    if (status.getGeoLocation() != null)
        doc.append("gloc", status.getGeoLocation().toString());
    doc.append("fcont", status.getFavoriteCount());
    doc.append("rcunt", status.getRetweetCount());
    if (status.getRetweetedStatus() != null)
        doc.append("rstate", status.getRetweetedStatus().getText());

    tacol.setText(tacol.getText() + doc.toJson() + "\n");//imprimimos el tweet en el frame
    return doc;/*from   ww w. j  a va 2s.  c om*/
}

From source file:twitter.SingleTweet.java

public SingleTweet(Status st) {
    this();/*from  ww w  .j  a v a2s .  c o m*/
    mainTxt.setText(st.getText());
    timeTxt.setText(st.getCreatedAt().toString());
    userTxt.setText(st.getUser().getName());
}

From source file:twitter.stream.PrintSampleStream.java

License:Apache License

/**
 * Main entry of this application./*from   w  w w  .j  a va  2s  . com*/
 *
 * @param args
 *            arguments doesn't take effect with this example
 * @throws TwitterException
 *             when Twitter service or network is unavailable
 */
public static void main(String[] args) throws TwitterException {
    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    StatusListener listener = new StatusListener() {
        @Override
        public void onStatus(Status status) {
            if (status.getGeoLocation() != null)
                System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText() + "Lat:"
                        + status.getGeoLocation().getLatitude() + "Long"
                        + status.getGeoLocation().getLongitude());
        }

        @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();
        }
    };
    twitterStream.addListener(listener);
    twitterStream.sample();
}

From source file:twitter.TweetGet.java

public List<MyStatus> getTweet() {
    List<MyStatus> stats = new ArrayList<>();
    SellerClassifier sc = new SellerClassifier();
    try {/*w w w .  j  a v  a 2 s.c o  m*/
        File file = new File(".");
        System.out.println("PATH: " + file.getAbsolutePath());
        sc.initModel("data\\training.arff");
    } catch (Exception ex) {
        Logger.getLogger(TweetGet.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (Status tweet : tweets) {
        MyStatus myStatus = new MyStatus();
        myStatus.setTweet(tweet.getText());
        myStatus.setStatusId(tweet.getId());
        myStatus.setUsername(tweet.getUser().getName());
        myStatus.setUserScreenName(tweet.getUser().getScreenName());
        myStatus.setImageUrl(tweet.getUser().getProfileImageURLHttps());

        int classRes = (int) sc.classifyTweet(myStatus);

        if (classRes == 1) {
            myStatus.setClassification(classRes);
            stats.add(myStatus);
        }
    }

    return stats;
}

From source file:twitter4j.examples.favorite.GetFavorites.java

License:Apache License

/**
 * Usage: java twitter4j.examples.favorite.GetFavorites
 *
 * @param args message//from w w  w.j a v a 2  s.  co  m
 */
public static void main(String[] args) {
    try {
        Twitter twitter = new TwitterFactory().getInstance();
        List<Status> statuses = twitter.getFavorites();
        for (Status status : statuses) {
            System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
        }
        System.out.println("done.");
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get favorites: " + te.getMessage());
        System.exit(-1);
    }
}