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:com.wso2.stream.connector.protocol.TweetContent.java

License:Open Source License

public OMElement createBodyContent(OMFactory omFactory, Status status) {
    OMElement tweet = omFactory.createOMElement(qTweet);

    OMElement text = omFactory.createOMElement(qText);
    tweet.addChild(text);/*from  ww w.  j  av a 2 s. c om*/
    text.addChild(omFactory.createOMText(status.getText()));

    OMElement createdAt = omFactory.createOMElement(qCreatedAt);
    tweet.addChild(createdAt);
    createdAt.addChild(omFactory.createOMText(status.getCreatedAt().toString()));

    OMElement latitude = omFactory.createOMElement(qLatitude);
    tweet.addChild(latitude);
    OMElement longitude = omFactory.createOMElement(qLongitude);
    tweet.addChild(longitude);
    if (status.getGeoLocation() != null) {
        latitude.addChild(omFactory.createOMText(String.valueOf(status.getGeoLocation().getLatitude())));
        longitude.addChild(omFactory.createOMText(String.valueOf(status.getGeoLocation().getLongitude())));
    }

    OMElement country = omFactory.createOMElement(qCountry);
    tweet.addChild(country);
    OMElement countryCode = omFactory.createOMElement(qCountryCode);
    tweet.addChild(countryCode);

    if (status.getPlace() != null) {
        country.addChild(omFactory.createOMText(status.getPlace().getCountry()));
        countryCode.addChild(omFactory.createOMText(status.getPlace().getCountryCode()));
    }

    OMElement location = omFactory.createOMElement(qLocation);
    tweet.addChild(location);
    if (status.getUser() != null) {
        location.addChild(omFactory.createOMText(status.getUser().getLocation()));
    }

    OMElement hashTags = omFactory.createOMElement(qHasTags);
    tweet.addChild(hashTags);

    if (status.getHashtagEntities().length > 0) {
        String tags = "";
        for (HashtagEntity h : status.getHashtagEntities()) {
            tags += h.getText() + ";";
        }
        tags = tags.substring(0, tags.length() - 1);
        hashTags.addChild(omFactory.createOMText(tags));
    }

    return tweet;

}

From source file:com.yfiton.notifiers.twitter.TwitterNotifier.java

License:Apache License

@Override
protected void notify(Parameters parameters) throws NotificationException {
    try {/*from w  w w. j  a v a  2s. c  o m*/
        StatusUpdate statusUpdate = new StatusUpdate(status);
        Status status = twitter.updateStatus(statusUpdate);

        log.info("https://twitter.com/" + status.getUser().getScreenName() + "/status/" + status.getId());
    } catch (TwitterException e) {
        throw new NotificationException(new String[] { e.getErrorMessage(),
                "Error code " + e.getErrorCode() + ": https://dev.twitter.com/overview/api/response-codes" },
                e);
    }
}

From source file:com.yoshio3.javaee7.sampleapp.TwitterStreamImpl.java

@Override
public void onStatus(Status status) {
    try {//from ww  w  . j  a v  a2  s  .c o m
        //Twitter ????????
        User user = status.getUser();
        String resStr = "@" + user.getScreenName() + " : " + status.getText();
        String encodedString = encode(resStr);
        session.getBasicRemote().sendText(encodedString);
        System.out.println(encodedString);
    } catch (IOException ex) {
        Logger.getLogger(TwitterStreamImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:cp.Demo.java

private void MoviesListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_MoviesListValueChanged

    // Obtain the movie object
    Movie mov;/*  w w  w.  ja  v a 2  s  .c  o  m*/
    try {
        mov = (Movie) MoviesList.getSelectedValue();
        System.out.println(mov.getApiQuery());
    } catch (Exception ex) {
        PosterLabel.setIcon(null);
        PosterLabel.setText("Movie not found");
        return;
    }

    // Display the movie poster
    try {
        // Load the movie poster
        URL url = new URL(mov.getPosterLink());
        ImageIcon img = new ImageIcon(url);

        // Rescale the movie poster
        int w = img.getIconWidth();
        int h = img.getIconHeight();
        int labelH = MovieTabs.getHeight() - 36;
        img.setImage(img.getImage().getScaledInstance(labelH * w / h, labelH, Image.SCALE_SMOOTH));

        // Put the movie poster into the label, and change the text
        PosterLabel.setIcon(img);
        PosterLabel.setText("");
    } catch (Exception ex) {
        // If for some reason the poster isn't available, indicate this
        PosterLabel.setIcon(null);
        PosterLabel.setText("Poster could not be displayed");
    }

    // Display tweets about the movie
    try {
        // clear out the tweets
        TweetsArea.setText("");

        // The factory instance is re-useable and thread safe.
        Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(mov.getTitle());
        QueryResult result = twitter.search(query);
        String tweet;
        for (Status status : result.getTweets()) {
            tweet = String.format("[%s] @%s tweeted %s\n", status.getCreatedAt(),
                    status.getUser().getScreenName(), status.getText());
            TweetsArea.append(tweet);
        }
    } catch (TwitterException ex) {
        TweetsArea.setText(ex.toString());
    }

    // Display reviews of the movie
    try {
        ReviewsArea.setText("");
        for (Review rev : (new ReviewRequest(mov.getMovie())).getReviews()) {
            String review = String.format("[%s] (by %s, %s)\n%s\n%s\n\n", rev.getDateOfReview(),
                    rev.getCritic(), rev.getPublication(), rev.getQuote(), rev.getReviewLinkUrl());
            ReviewsArea.append(review);
        }
    } catch (IOException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ReviewRequest.ReviewRequestException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ParseException ex) {
        Logger.getLogger(Demo.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:crawler.DataStorage.java

License:Apache License

private static void sqlStore(Status status) throws SQLException {
    long sql_pid = Settings.pid;
    Settings.pid++;/*from  w ww.j av a 2 s. c  om*/

    SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd, HH:mm:ss, z");
    String sqlCreateAt = tempDate.format(new java.util.Date(status.getCreatedAt().getTime()));

    double sqlGeoLocationLat = 0;
    double sqlGeoLocationLong = 0;

    if (status.getGeoLocation() != null) {
        sqlGeoLocationLat = status.getGeoLocation().getLatitude();
        sqlGeoLocationLong = status.getGeoLocation().getLongitude();
    }

    String sqlPlace = (status.getPlace() != null ? status.getPlace().getFullName() : "");
    long sqlId = status.getId();
    String sqlTweet = status.getText().replace("'", "''");
    String sqlSource = status.getSource().replace("'", "''");
    sqlSource = sqlSource.replace("\\", "\\\\");
    String sqlLang = status.getUser().getLang();
    String sqlScreenName = status.getUser().getScreenName();
    String sqlReplyTo = status.getInReplyToScreenName();
    long sqlRtCount = status.getRetweetCount();

    HashtagEntity[] hashs = status.getHashtagEntities();
    String sqlHashtags = "";
    for (HashtagEntity hash : hashs)
        sqlHashtags += hash.getText() + " ";

    pstm.setLong(1, sql_pid);
    pstm.setString(2, sqlCreateAt);
    pstm.setDouble(3, sqlGeoLocationLat);
    pstm.setDouble(4, sqlGeoLocationLong);
    pstm.setString(5, sqlPlace);
    pstm.setLong(6, sqlId);
    pstm.setString(7, sqlTweet);
    pstm.setString(8, sqlSource);
    pstm.setString(9, sqlLang);
    pstm.setString(10, sqlScreenName);
    pstm.setString(11, sqlReplyTo);
    pstm.setLong(12, sqlRtCount);
    pstm.setString(13, sqlHashtags);

    pstm.addBatch();
}

From source file:crawler.TwitterFeed.java

/**
 *
 *//*from  w  ww .ja  v  a  2 s  . c om*/
public void get_tweets() throws SQLException {
    CSVReader cr = new CSVReader();
    ArrayList<String> names = new ArrayList<>();
    Map<String, String> name_ticker;
    names = cr.get_company_names(tickers);
    System.out.println(names);
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setOAuthConsumerKey("WNSycI2GS33ZAwHJ9Fb4A");
    cb.setOAuthConsumerSecret("BBWeSThT3ZV2g9c5BDuUduDyNAWyzouMI0XjQy7KUc");
    cb.setOAuthAccessToken("1852271029-SLfE061bImfcRxWQZpy1pAgpEkfFhg3757Q9JRf");
    cb.setOAuthAccessTokenSecret("1uPSfYPbaENtXFYWsryBIAHnUsmG3pT6lGH0NzxTCGW7O");
    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    for (String s : names) {
        String[] temp;
        if (s.contains(",")) {
            temp = s.split(",");
        } else {
            temp = s.split(" ");
        }

        System.out.println(
                "--------------------------------------------------------------------------------------"
                        + temp[0]);
        Query query = new Query("#" + temp[0]);
        query.lang("en");
        int numberOfTweets = 500;
        long lastID = Long.MAX_VALUE;
        ArrayList<Status> tweets = new ArrayList<>();
        while (tweets.size() < numberOfTweets) {
            if (numberOfTweets - tweets.size() > 100) {
                query.setCount(100);
            } else {
                query.setCount(numberOfTweets - tweets.size());
            }
            try {
                QueryResult result = twitter.search(query);
                tweets.addAll(result.getTweets());
                System.out.println("Gathered " + tweets.size() + " tweets");
                for (Status t : tweets) {
                    if (t.getId() < lastID) {
                        lastID = t.getId();
                    }
                }

            } catch (TwitterException te) {
                System.out.println("Couldn't connect: " + te);
            }
            query.setMaxId(lastID - 1);
        }
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/CrawledData", "root", "");
        for (int i = 0; i < tweets.size(); i++) {
            Status t = (Status) tweets.get(i);

            //GeoLocation loc = t.getGeoLocation();
            String user = t.getUser().getScreenName();
            String msg = t.getText();
            String time = t.getCreatedAt().toString();
            //if (loc!=null) {
            //    Double lat = t.getGeoLocation().getLatitude();
            //    Double lon = t.getGeoLocation().getLongitude();
            //    System.out.println(i + " USER: " + user + " wrote: " + msg + " located at " + lat + ", " + lon);
            //} 
            //else{ 
            System.out.println(i + " USER: " + user + " wrote: " + msg + " at: " + time);
            //}
            try {
                Class.forName("com.mysql.jdbc.Driver");

                PreparedStatement ps = con
                        .prepareStatement("INSERT IGNORE INTO TwitterFeed VALUES (?,?,?,?,?)");
                ps.setString(1, s);
                ps.setString(2, cr.get_ticker_from_company(s));
                ps.setString(3, user);
                ps.setString(4, msg);
                ps.setString(5, time);

                int k = ps.executeUpdate();
                if (k <= 0) {
                    System.out.println("Entry Unsuccessful");
                } else {
                    System.out.println("Entry Successful");
                }

            } catch (ClassNotFoundException | SQLException e) {
                System.out.println(e);
            }

        }
        con.close();
    }
}

From source file:crawling.FoundUsersBySearchGeo.java

License:Apache License

private static void doASearch(Twitter twitter, Query query) throws TwitterException {
    //try {/*from  w  w w.  j  a  v  a 2s  . c o  m*/
    QueryResult result = twitter.search(query);
    List<Status> tweets = result.getTweets();
    int thisCount = 0;
    for (Status tweet : tweets) {
        //System.out.println("@" + tweet.getFromUser() + tweet.getId() + " - " + tweet.getText());

        // Check the tweet
        Long id = tweet.getUser().getId();
        String screenName = tweet.getUser().getScreenName();

        /*String location = "";
        if (tweet.getUser().getLocation() != null){
          location += tweet.getUser().getLocation();
        if (tweet.getGeoLocation() != null){
          location += "::" + tweet.getGeoLocation().toString();
        }*/
        String location = tweet.getUser().getLocation() + "::" + tweet.getGeoLocation();
        // If the tweet is a retweet, the source of the tweet is from the target area
        if (tweet.isRetweet()) {
            id = tweet.getRetweetedStatus().getUser().getId();
            screenName = tweet.getRetweetedStatus().getUser().getScreenName();
            //location = tweet.getRetweetedStatus().getUser().getLocation();
            location = tweet.getRetweetedStatus().getUser().getLocation() + "::"
                    + tweet.getRetweetedStatus().getGeoLocation();
        }

        if (discoveredUsers.containsKey(id)) {
            //System.out.println("Already found this user: " + id);
            long num = discoveredUsers.get(id);
            discoveredUsers.put(id, num + 1);
        } else {
            discoveredUsers.put(id, (long) 1);
            storeUserID(id, screenName, location);
            thisCount++;
        }
    }
    if (currentIndex < histCount) {
        avgUsers[currentIndex] = thisCount;
        currentIndex++;
    } else {
        currentIndex = 0;
    }

    /* Calculate the average #users in last 10 times */
    double sum = 0;
    for (int num : avgUsers)
        sum += num;
    System.out.print(
            "\r" + count + ", the average number of users in last " + histCount + " is: " + sum / histCount);

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

}

From source file:crawling.FoundUsersBySearchHashtag.java

License:Apache License

private static void doASearch(Twitter twitter, Query query) throws TwitterException {
    //try {/*from  www . ja va2s .com*/
    QueryResult result = twitter.search(query);
    List<Status> tweets = result.getTweets();
    int thisCount = 0;
    for (Status tweet : tweets) {
        //System.out.println("@" + tweet.getFromUser() + tweet.getId() + " - " + tweet.getText());

        // Check the tweet
        Long id = tweet.getUser().getId();
        String screenName = tweet.getUser().getScreenName();

        /*String location = "";
        if (tweet.getUser().getLocation() != null){
          location += tweet.getUser().getLocation();
        if (tweet.getGeoLocation() != null){
          location += "::" + tweet.getGeoLocation().toString();
        }*/
        String location = tweet.getUser().getLocation() + "::" + tweet.getGeoLocation();
        // If the tweet is a retweet, the source of the tweet is from the target area
        /*if (tweet.isRetweet()){
          id = tweet.getRetweetedStatus().getUser().getId();
          screenName = tweet.getRetweetedStatus().getUser().getScreenName();
          //location = tweet.getRetweetedStatus().getUser().getLocation();
          location = tweet.getRetweetedStatus().getUser().getLocation() + "::" + tweet.getRetweetedStatus().getGeoLocation();
        }*/

        if (discoveredUsers.containsKey(id)) {
            //System.out.println("Already found this user: " + id);
            long num = discoveredUsers.get(id);
            discoveredUsers.put(id, num + 1);
        } else {
            discoveredUsers.put(id, (long) 1);
            storeUserID(id, screenName, location);
            thisCount++;
        }
    }
    if (currentIndex < histCount) {
        avgUsers[currentIndex] = thisCount;
        currentIndex++;
    } else {
        currentIndex = 0;
    }

    /* Calculate the average #users in last 10 times */
    double sum = 0;
    for (int num : avgUsers)
        sum += num;
    System.out.print(
            "\r" + count + ", the average number of users in last " + histCount + " is: " + sum / histCount);

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

}

From source file:crawling.FoundUsersByStreamHashtag.java

License:Apache License

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

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            // my shutdown code here
            // Record the user status
            idOut.println("Final status -------------------:");
            for (Long id : discoveredUsers.keySet()) {
                idOut.println(id + "," + discoveredUsers.get(id));
            }/*  www.  j  a va2 s .com*/
            idOut.close();
        }
    });

    if (args.length != 1) {
        System.out.println("Usage: java twitter4j.examples.PrintFilterStreamHashtag hashtag");
        System.exit(-1);
    }
    /*if(args.length == 2){
       // Preload the collected user IDs
       preloadID(args[1]);
    }*/

    //buildStartTime();

    File file = new File(fileName);
    InputStream is = null;

    try {
        if (file.exists()) {
            is = new FileInputStream(file);
            prop.load(is);
        } else {
            System.out.println(fileName + " doesn't exist!");
            System.exit(-1);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(-1);
    }

    StatusListener listener = new StatusListener() {
        public void onStatus(Status status) {
            //System.out.println("@" + status.getUser().getScreenName() + " - " + status.getText());
            CheckUser(status);

            /*storeATweet(status);
            tweets += 1;
            if (tweets % 1000 == 0){
               System.out.println("We now have tweets: " + tweets);
            }*/
        }

        private void CheckUser(Status status) {
            // TODO Auto-generated method stub
            Long id = status.getUser().getId();
            String username = status.getUser().getScreenName();
            String realname = status.getUser().getName();
            String text = status.getText();
            Date date = status.getCreatedAt();
            if (discoveredUsers.containsKey(id)) {
                //System.out.println("Already found this user: " + id);
                long num = discoveredUsers.get(id);
                discoveredUsers.put(id, num + 1);
            } else {
                discoveredUsers.put(id, (long) 1);
                storeUserID(status);
            }
        }

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

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

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

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

        @Override
        public void onStallWarning(StallWarning arg0) {
            // TODO Auto-generated method stub

        }
    };

    try {
        FileWriter outFile = new FileWriter("discoveredUser" + args[0] + ".txt", true);
        idOut = new PrintWriter(outFile);
        //out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    TwitterStream twitterStream = getOAuthTwitterStream();
    twitterStream.addListener(listener);

    FilterQuery query = new FilterQuery();
    String[] track = { args[0] };
    //String[] track = {"#BaltimoreRiots"};
    query.track(track);
    twitterStream.filter(query);
}

From source file:crawling.FoundUsersByStreamHashtag.java

License:Apache License

private static void storeUserID(Status status) {
    // TODO Auto-generated method stub
    Long id = status.getUser().getId();
    String username = status.getUser().getScreenName();
    String realname = status.getUser().getName();
    String text = status.getText();
    Date date = status.getCreatedAt();

    //String line = id + "::" + username + "::" + realname + "::" + text + "::" + date + "::" + (new Date());
    String line = id + "," + username;
    //System.out.println(line);
    idOut.println(line);// w ww  . j a v a 2  s .  c  o  m
    idOut.flush();
    System.out.print("\r" + ++count);

}