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:tweetcrawling.TweetCrawler.java

public ArrayList<String> getValueToWrite(Status status) {

    // Getting the value to be written

    Long tid = status.getId();/*from w  w  w . j  av  a2 s.  co  m*/
    String tweetid = tid.toString();

    ArrayList<String> valueToWrite = new ArrayList<String>();

    User user = status.getUser();
    String screenname = user.getScreenName();
    String name = user.getName();
    String url = getTweetUrl(screenname, tweetid);

    String body = status.getText().replace("\n", " ");

    valueToWrite.add(body.replace(",", " ")); // element: body
    valueToWrite.add(url); // element: id
    valueToWrite.add(screenname); // element: userid
    valueToWrite.add(name); // element: user

    // element: gender
    if (name != null && !name.isEmpty()) {
        valueToWrite.add(getUserGender(name));
    } else if (screenname != null && !screenname.isEmpty()) {
        valueToWrite.add(getUserGender(screenname));
    } else {
        valueToWrite.add("");
    }

    valueToWrite.add(user.getLocation()); // element: location
    valueToWrite.add("" + user.getFollowersCount()); // element: followercount
    valueToWrite.add("" + user.getFriendsCount()); // element: friendscount
    valueToWrite.add("" + user.getStatusesCount()); // element: statuscount

    try {
        List<String> coor = new ArrayList<String>();
        String latitude = "" + status.getGeoLocation().getLatitude();
        String longitude = "" + status.getGeoLocation().getLongitude();
        coor.add(latitude);
        coor.add(longitude);

        if (coor != null && !coor.isEmpty() && coor.size() > 0) {
            valueToWrite.add(coor.get(0)); // element: latitude
            valueToWrite.add(coor.get(1)); // element: longitude
            valueToWrite.add(coor.get(0) + "," + coor.get(1));
        } else {
            valueToWrite.add(null);
            valueToWrite.add(null);
            valueToWrite.add(null);
        }
    } catch (Exception e) {
        valueToWrite.add(null);
        valueToWrite.add(null);
        valueToWrite.add(null);
    }

    try {

        String geoname = status.getPlace().getName();
        String country = status.getPlace().getCountry();

        if (geoname != null) {
            valueToWrite.add(geoname);
        } else {
            valueToWrite.add(null);
        }

        if (country != null) {
            valueToWrite.add(country);
        } else {
            valueToWrite.add(null);
        }

    } catch (Exception e) {
        valueToWrite.add(null);
        valueToWrite.add(null);
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    Date date = status.getCreatedAt();
    valueToWrite.add(dateFormat.format(date)); // element: date
    valueToWrite.add(getDateCrawler()); // element: datecrawler
    valueToWrite.add(status.getInReplyToScreenName()); // element: replyto

    String tooltip = "";
    try {

        String geoname = status.getPlace().getName();
        if (geoname != null) {
            tooltip = "user = " + name + ", geoname = " + geoname;
        }

    } catch (Exception e) {
        tooltip = "";
    }
    valueToWrite.add(tooltip.trim()); // element: tooltip
    valueToWrite.add(SOURCE); // element: source

    return valueToWrite;
}

From source file:tweetcrawling.TweetCrawler.java

public void printTweets(String csvOut) throws IOException, TwitterException {

    for (Status status : getStatuses()) {

        // Getting the value to be written

        Long tid = status.getId();
        String tweetid = tid.toString();

        ArrayList<String> valueToWrite = new ArrayList<String>();

        User user = status.getUser();
        String screenname = user.getScreenName();
        String name = user.getName();
        String url = getTweetUrl(screenname, tweetid);

        valueToWrite.add(url); // element: id
        valueToWrite.add(screenname); // element: userid
        valueToWrite.add(name); // element: user

        // element: gender
        if (name != null && !name.isEmpty()) {
            valueToWrite.add(getUserGender(name));
        } else if (screenname != null && !screenname.isEmpty()) {
            valueToWrite.add(getUserGender(screenname));
        } else {/*from  ww  w.  j  a  v  a2  s  .  c  o m*/
            valueToWrite.add("");
        }

        valueToWrite.add(user.getLocation()); // element: location
        valueToWrite.add("" + user.getFollowersCount()); // element: followercount
        valueToWrite.add("" + user.getFriendsCount()); // element: friendscount
        valueToWrite.add("" + user.getStatusesCount()); // element: statuscount

        try {
            List<String> coor = new ArrayList<String>();
            String latitude = "" + status.getGeoLocation().getLatitude();
            String longitude = "" + status.getGeoLocation().getLongitude();
            coor.add(latitude);
            coor.add(longitude);

            if (coor != null && !coor.isEmpty() && coor.size() > 0) {
                valueToWrite.add(coor.get(0)); // element: latitude
                valueToWrite.add(coor.get(1)); // element: longitude
                valueToWrite.add(coor.get(0) + "," + coor.get(1));
            } else {
                valueToWrite.add(null);
                valueToWrite.add(null);
                valueToWrite.add(null);
            }
        } catch (Exception e) {
            valueToWrite.add(null);
            valueToWrite.add(null);
            valueToWrite.add(null);
        }

        try {

            String geoname = status.getPlace().getName();
            String country = status.getPlace().getCountry();

            if (geoname != null) {
                valueToWrite.add(geoname);
            } else {
                valueToWrite.add(null);
            }

            if (country != null) {
                valueToWrite.add(country);
            } else {
                valueToWrite.add(null);
            }

        } catch (Exception e) {
            valueToWrite.add(null);
            valueToWrite.add(null);
        }

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        Date date = status.getCreatedAt();
        valueToWrite.add(dateFormat.format(date)); // element: date
        valueToWrite.add(getDateCrawler()); // element: datecrawler
        valueToWrite.add(status.getText()); // element: body
        valueToWrite.add(status.getInReplyToScreenName()); // element: replyto

        String tooltip = "";
        try {

            String geoname = status.getPlace().getName();
            if (geoname != null) {
                tooltip = "user = " + name + ", geoname = " + geoname;
            }

        } catch (Exception e) {
            tooltip = "";
        }
        valueToWrite.add(tooltip.trim()); // element: tooltip
        valueToWrite.add(SOURCE); // element: source

        // Write valueToWrite to csv external file

        FileWriter fw = new FileWriter(csvOut, true);
        PrintWriter pw = new PrintWriter(fw);

        String content = "'";

        for (int i = 0; i < valueToWrite.size() - 1; i++) {
            content += valueToWrite.get(i) + "','";
        }

        content += valueToWrite.get(valueToWrite.size()) + "'";

        pw.print(content);

        pw.flush();
        pw.close();
        fw.close();

    }
}

From source file:tweetdownloader.cnr_stable.version.TweetDownload.java

/**
 * this method return an ArrayList of dataOfTweets
 * @param allMyTweets/*from w  ww . j  a  va  2 s . c  o m*/
 * @return allMyTweet
 */
public ArrayList<dataOfTweet> downloadMyTweet(ArrayList<dataOfTweet> allMyTweets) {
    {
        try {
            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
            RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
            for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
                dataOfTweet tweet = new dataOfTweet();

                //System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                if (searchTweetsRateLimit.getRemaining() == 0) {
                    try {
                        //System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset());
                        Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                    } catch (InterruptedException ex) {
                        java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE,
                                null, ex);
                    }
                }
                Query q = new Query(SEARCH_TERM);
                q.setCount(TWEETS_PER_QUERY);
                q.setLang("it");

                if (maxID != -1) {
                    q.setMaxId(maxID - 1);
                }

                QueryResult r = twitter.search(q);

                if (r.getTweets().isEmpty()) {
                    break;
                }
                for (Status s : r.getTweets()) {

                    totalTweets++;
                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }
                    if (s.isRetweeted() == false) {

                        tweet.setUsername(s.getUser().getScreenName());
                        tweet.setCreatedAt(s.getCreatedAt().toString());
                        tweet.setTweetText(s.getText());

                        if (s.getGeoLocation() != null) {
                            tweet.setLat(s.getGeoLocation().getLatitude());
                            tweet.setLongi(s.getGeoLocation().getLongitude());
                        }
                    }
                }
                allMyTweets.add(tweet);
            }
        } catch (TwitterException ex) {
            java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return allMyTweets;
}

From source file:tweetmining.MiningFunctions.java

/**
 * This method creates an instance of Miningfunctions based on your TwitterApss credentials.
 * You should as well check filepaths to put yours.
 * /* w w w .j  a va  2  s .co m*/
 * @throws FileNotFoundException 
 */

public MiningFunctions() throws FileNotFoundException, IOException {
    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);

    tf = new TwitterFactory(configurationBuilder.build());

    twitter = tf.getInstance();

    File f = new File(fichero1);
    File f2 = new File(fichero2);
    File f3 = new File(fichero3);
    if (!f.exists())
        f.createNewFile();
    if (!f2.exists())
        f2.createNewFile();
    if (!f3.exists())
        f3.createNewFile();
    pw = new PrintWriter(new FileOutputStream(f, true));
    pw2 = new PrintWriter(new FileOutputStream(f2, true));
    pw3 = new PrintWriter(new FileOutputStream(f3, true));

    listener = new StatusListener() {
        public void onStatus(Status status) {
            if (status.getGeoLocation() != null) {
                cont++;
                System.out.println("Loc not null----" + cont);
                GeoLocation loc = status.getGeoLocation();
                pw.println(String.valueOf(loc.getLatitude()) + ";" + String.valueOf(loc.getLongitude()) + ";"
                        + status.getUser().getName());
                System.out.println(
                        loc.getLatitude() + " " + loc.getLongitude() + " " + status.getUser().getName());
            }
            pw2.println(status.getUser().getName() + "--->" + status.getText());
            try {
                CloseWriteAndOpen();
            } catch (FileNotFoundException ex) {
                java.util.logging.Logger.getLogger(MiningFunctions.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        }

        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
        }

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

        @Override
        public void onScrubGeo(long l, long l1) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void onStallWarning(StallWarning sw) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    };
    configurationBuilder = new ConfigurationBuilder();
    configurationBuilder.setDebugEnabled(true).setOAuthConsumerKey(ConsumerKey)
            .setOAuthConsumerSecret(ConsumerSecret).setOAuthAccessToken(AccessToken)
            .setOAuthAccessTokenSecret(AccessTokenSecret);
    twitterStream = new TwitterStreamFactory(configurationBuilder.build()).getInstance();
}

From source file:tweetmining.MiningFunctions.java

/**
 * This method mines data from a particular twitter user.
 * @param user String which has the name of a Twitter user without @ 
 */// ww  w.j  a  v a 2  s  .co  m
public void MineFromUser(String user) {
    int pageno = 1;
    List<Status> statuses = new ArrayList();

    while (true) {

        try {

            int size = statuses.size();
            Paging page = new Paging(pageno++, 100);
            statuses.addAll(twitter.getUserTimeline(user, page));
            if (statuses.size() == size)
                break;
        } catch (TwitterException e) {

            e.printStackTrace();
        }
    }

    System.out.println(statuses.size());

    for (Status st : statuses) {
        GeoLocation loc = st.getGeoLocation();
        if (loc != null) {
            System.out.println("Loc not null");
            Double lat = loc.getLatitude();
            Double lon = loc.getLongitude();
            pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName());
        }
        pw2.println(st.getUser().getName() + "-----" + st.getText());
    }

    pw.close();
    pw2.close();
}

From source file:tweetmining.MiningFunctions.java

/**
 * This method mines data from youw twitter account based on the query string that you pass by
 * parameters.// ww w. j  a v a 2  s .co  m
 * @param query Query you want to place.
 * @throws FileNotFoundException
 * @throws TwitterException 
 */
public void MineFromQuery(String query) throws FileNotFoundException, TwitterException {
    Query q = new Query(query);
    QueryResult r;
    q.count(100);

    do {
        r = twitter.search(q);
        List<Status> statuses = r.getTweets();
        for (Status st : statuses) {
            GeoLocation loc = st.getGeoLocation();
            if (loc != null) {
                System.out.println("Loc not null");
                Double lat = loc.getLatitude();
                Double lon = loc.getLongitude();
                pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName());
            }
        }
        q = r.nextQuery();
    } while (r.hasNext());
}

From source file:tweets.Tweets.java

/**
 * @param args the command line arguments
 *//*from   w  w  w  . j a v  a  2 s  .  com*/
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:twit.Twit.java

public static void onStatus(Status status, int kode) {
    Twitter tf = new TwitterFactory().getInstance();
    //kode 1 : Format benar
    if (kode == 1) {
        StatusUpdate st = new StatusUpdate("Hi @" + status.getUser().getScreenName()
                + ", terima kasih telah membantu monitoring harga Cabe Indonesia :D");
        st.inReplyToStatusId(status.getId());
        try {//from   ww w  .  j av a2s  .c  om
            tf.updateStatus(st);
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //kode 2 : Format salah
    } else if (kode == 2) {
        StatusUpdate st = new StatusUpdate(
                "Hi @" + status.getUser().getScreenName() + ", terima kasih atas laporan Anda! :)");
        st.inReplyToStatusId(status.getId());
        try {
            tf.updateStatus(st);
        } catch (TwitterException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //kode 2 : Format salah
    } else {
        System.out.println("error");
    }
}

From source file:twit.Twit.java

public void userMention() throws SQLException, ParseException {
    Twitter twitter = new TwitterFactory().getInstance();
    try {//from  ww w  . j av a 2 s .c o  m
        Long since_id = cek_last_mention();
        Paging paging = new Paging().sinceId(since_id);
        List<Status> statuses = twitter.getMentionsTimeline(paging);
        for (twitter4j.Status status : statuses) {
            long ID_TWEET = status.getId();
            String USERNAME = status.getUser().getScreenName();
            String TWEET = status.getText().replace("'", "\\'");
            save_user(USERNAME);
            String ID_MASYARAKAT = cekMasyarakat(USERNAME);
            if (USERNAME.equals("tahupongcode")) { //reply akun sendiri
                save_data_mentions(ID_TWEET);
            } else {
                if (Regex(TWEET)[0].equals("harga")) {
                    //masukkan hasil regex pada array
                    String[] hasil = Regex(TWEET);
                    //ambil isi array
                    int KOMODITAS = cekKomoditas(hasil[2]);
                    String TITIK_DISTRIBUSI = cekTitik(hasil[3]);
                    String HARGA = hasil[4];
                    save_harga(KOMODITAS, TITIK_DISTRIBUSI, ID_MASYARAKAT, USERNAME, HARGA);
                    if (cek_replied(ID_TWEET) == false) {
                        save_data_mentions(ID_TWEET);
                        onStatus(status, 1);
                    }
                } else if (Regex(TWEET)[0].equals("keluhan")) {
                    //masukkan hasil regex pada array
                    String[] hasil = Regex(TWEET);
                    //ambil isi array
                    String SUBJECT = hasil[2];
                    String KELUHAN = hasil[3];
                    String KABUPATEN = cekKabupaten(hasil[4]);
                    insertKeluhan(ID_MASYARAKAT, SUBJECT, KELUHAN, KABUPATEN);
                    if (cek_replied(ID_TWEET) == false) {
                        save_data_mentions(ID_TWEET);
                        onStatus(status, 2);
                    }
                } else {
                    System.out.println("error");
                }
            }
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        System.exit(-1);
    }
}

From source file:twitah.Metodos.java

/**
 * Used to collect the user's twitter timeline in a collection.
 *///from   w w  w.  j a v  a2s.co  m
public static void lineaTiempo() {

    List<Status> statuses = null;

    try {
        statuses = twitter.getHomeTimeline();
    } catch (TwitterException ex) {
        java.util.logging.Logger.getLogger(Metodos.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Showing home timeline.");
    for (Status status : statuses) {
        System.out.println(status.getUser().getName() + ":" + status.getText());
        twits.add(status);
    }

}