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:teambootje.TwitterAPI.java

public static void timeline() throws TwitterException, SQLException {
    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query("ssrotterdam");
    query.setCount(100);/*from w w w .j  a  va 2  s .c o m*/
    /**
     ** setSince kan alleen tot 7 dagen terug worden gebruikt***
     */

    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        if (status.getPlace() != null) {
            cityVar = status.getPlace().getName();
            countryVar = status.getPlace().getCountry();
        } else {
            countryVar = null;
            cityVar = null;
        }

        java.util.Date utilDate = status.getCreatedAt();
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        date = sqlDate;
        post = status.getText();
        screenName = status.getUser().getScreenName();
        try {
            ImportIntoSQL.TwitterImport();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:testtweet.TweetUsingTwitter4jExample.java

/**
 * @param args the command line arguments
 *///from  w  ww  . j  ava  2  s  . co  m
public static void main(String[] args) throws IOException, TwitterException {

    //Instantiate a re-usable and thread-safe factory
    TwitterFactory twitterFactory = new TwitterFactory(Data.getConf().build());

    //Instantiate a new Twitter instance
    Twitter twitter = twitterFactory.getInstance();

    /*
    //setup OAuth Consumer Credentials
    twitter.setOAuthConsumer(consumerKey, consumerSecret);
            
    //setup OAuth Access Token
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));
    */

    //Instantiate and initialize a new twitter status update
    StatusUpdate statusUpdate = new StatusUpdate(
            //your tweet or status message
            "Twitter API #Hacked");
    //attach any media, if you want to
    /*
    statusUpdate.setMedia(
    //title of media
    "http://h1b-work-visa-usa.blogspot.com"
    , new URL("http://lh6.ggpht.com/-NiYLR6SkOmc/Uen_M8CpB7I/AAAAAAAAEQ8/tO7fufmK0Zg/h-1b%252520transfer%252520jobs%25255B4%25255D.png?imgmax=800").openStream());
    */
    //tweet or update status
    Status status = twitter.updateStatus(statusUpdate);

    //response from twitter server
    System.out.println("status.toString() = " + status.toString());
    System.out.println("status.getInReplyToScreenName() = " + status.getInReplyToScreenName());
    System.out.println("status.getSource() = " + status.getSource());
    System.out.println("status.getText() = " + status.getText());
    System.out.println("status.getContributors() = " + Arrays.toString(status.getContributors()));
    System.out.println("status.getCreatedAt() = " + status.getCreatedAt());
    System.out.println("status.getCurrentUserRetweetId() = " + status.getCurrentUserRetweetId());
    System.out.println("status.getGeoLocation() = " + status.getGeoLocation());
    System.out.println("status.getId() = " + status.getId());
    System.out.println("status.getInReplyToStatusId() = " + status.getInReplyToStatusId());
    System.out.println("status.getInReplyToUserId() = " + status.getInReplyToUserId());
    System.out.println("status.getPlace() = " + status.getPlace());
    System.out.println("status.getRetweetCount() = " + status.getRetweetCount());
    System.out.println("status.getRetweetedStatus() = " + status.getRetweetedStatus());
    System.out.println("status.getUser() = " + status.getUser());
    System.out.println("status.getAccessLevel() = " + status.getAccessLevel());
    System.out.println("status.getHashtagEntities() = " + Arrays.toString(status.getHashtagEntities()));
    System.out.println("status.getMediaEntities() = " + Arrays.toString(status.getMediaEntities()));
    if (status.getRateLimitStatus() != null) {
        System.out
                .println("status.getRateLimitStatus().getLimit() = " + status.getRateLimitStatus().getLimit());
        System.out.println(
                "status.getRateLimitStatus().getRemaining() = " + status.getRateLimitStatus().getRemaining());
        System.out.println("status.getRateLimitStatus().getResetTimeInSeconds() = "
                + status.getRateLimitStatus().getResetTimeInSeconds());
        System.out.println("status.getRateLimitStatus().getSecondsUntilReset() = "
                + status.getRateLimitStatus().getSecondsUntilReset());
        System.out.println("status.getRateLimitStatus().getRemainingHits() = "
                + status.getRateLimitStatus().getRemaining());
    }
    System.out.println("status.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
    System.out.println("status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
}

From source file:tiofortwitter.TioForTwitter.java

/**
 * @param args the command line arguments
 *///w w w .  j  av  a2  s  .co  m
public static void main(String[] args) throws JSONException, IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Gkr9iZwYDALZ16OdxMp5rubBH")
            .setOAuthConsumerSecret("nhEwYFfiX5qp90sLLwO2eeYMxLwb3WC120lgihrocZDPWRNcUK")
            .setOAuthAccessToken("94107100-572UpcOkkz9kMWGaJS8YFsIGdlmJAd2cDw8y9rOnA")
            .setOAuthAccessTokenSecret("ST0XtXUjYgYWKHryL2feNM0VcDQQAgrov2V7nB7hq1xBC");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    JSONObject obj = new JSONObject();
    int counterTweet = 0;
    FileWriter file = new FileWriter("Users\\user\\IdeaProjects\\TwitterStringMatching\\input.txt");
    file.flush();
    try {
        Query query = new Query("Satria");
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                counterTweet++;
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                obj.put("user", tweet.getUser().getScreenName());
                obj.put("tweets", tweet.getText());

                //Tulis file ke dalam txt

                try {
                    file.write(obj.toString());
                    System.out.println("Successfully Copied JSON Object to File...");
                    System.out.println("\nJSON Object: " + obj);

                } catch (IOException e) {
                    e.printStackTrace();

                }
            }
        } while (counterTweet < 1000);

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

From source file:toninbot.ToninStatusListener.java

@Override
public void onStatus(Status tweetRecibido) {
    if (tweetRecibido.getUser().getId() != 184742273L && tweetRecibido.getUser().getId() != 2841338087L) {
        return;/*from   w ww .  ja va 2  s.c  o  m*/
    }
    System.out.println(tweetRecibido.getUser().getName() + " " + tweetRecibido.getText());
    Calendar cal = Calendar.getInstance();
    cal.setTime(tweetRecibido.getCreatedAt());
    long hora = cal.get(Calendar.HOUR_OF_DAY);
    System.out.println("Hora: " + cal.get(Calendar.HOUR_OF_DAY));

    //comprobar la hora
    if (hora > 7 || hora < 1) {
        return;
    }

    //comprobar que no sea una respuesta a alguien
    if (tweetRecibido.getText().contains("@")) {
        return;
    }

    StatusUpdate stat = new StatusUpdate(
            "@" + tweetRecibido.getUser().getScreenName() + " " + respuestaRandom());
    System.out.println("Fora de horario!");

    stat.inReplyToStatusId(tweetRecibido.getId());

    try {
        twitter.updateStatus(stat);
        System.out.println("Twitteado: " + stat.toString());
    } catch (TwitterException ex) {
        System.out.println("Error");
    }
}

From source file:traffickarmasent.newgetpage.java

public static void main(String[] args) throws IOException {
    // gets Twitter instance with default credentials
    Twitter twitter = new TwitterFactory().getInstance();
    try {//ww w .j  a va2 s .  c o m
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true);
        cb.setOAuthConsumerKey("GPtsu5cjC08KTOEojEoaHw");
        cb.setOAuthConsumerSecret("SsgeXn73bN4CXUYtJfEdKOwBxVTmAEPvmFo3q2CX45w");
        cb.setOAuthAccessToken("154196958-J1Gqy86jmQ6YSoFVVq69bmbJB0acGxiDEocxtvre");
        cb.setOAuthAccessTokenSecret("DpTJr3huuDy2qMwsCMgsTn5yNbi0oQzSDGhDDWQsLog");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter1 = tf.getInstance();
        List<Status> statuses;
        String user;
        String[] users = { "livetrafficsyd", "trafficnsw", "sydtraffic_cs", "WazeTrafficSYD",
                "livetrafficnsw" };
        Date[] d_users = { new Date(99, 2, 12), new Date(99, 2, 12), new Date(99, 2, 12), new Date(99, 2, 12),
                new Date(99, 2, 12) };

        while (true) {
            for (int i = 0; i < users.length; i++) {

                statuses = twitter1.getUserTimeline(users[i]);

                for (int j = statuses.size() - 1; j >= 0; j--) {
                    Status st = statuses.get(j);
                    if (d_users[i].before(st.getCreatedAt())) {
                        String message = removeUrl(st.getText());

                        File file = new File("out_sydney_new.txt");

                        //if file doesnt exists, then create it
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        //true = append file
                        FileWriter fileWritter = new FileWriter(file.getName(), true);
                        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
                        bufferWritter.write(message + "\n");
                        bufferWritter.close();

                        System.out.println("Done");

                        System.out.println("@" + st.getUser().getScreenName() + " - " + st.getText());
                        d_users[i] = st.getCreatedAt();
                    }
                }
            }
            try {
                Thread.sleep(300000); //1000 milliseconds is one second.
            } catch (InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
            System.out.println("firse");

        }

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

From source file:traffickarmasent.TweetCollection.java

public static void main(String[] args) throws FileNotFoundException, IOException, Exception {
    // loading slang dictionary with key as slang and value as its full form
    slangMap = new HashMap<String, String>();
    BufferedReader slangRead = new BufferedReader(new FileReader("extras/out.txt"));
    String line = "";
    while ((line = slangRead.readLine()) != null) {
        String parts[] = line.split("\t");
        slangMap.put(parts[0], parts[1]);
    }//  www  .  ja  v  a2 s . c o  m
    slangRead.close();

    //loading entity list
    BufferedReader htm_in = new BufferedReader(new FileReader("extras/html_ent.txt"));
    entityList = new ArrayList<String>();
    while ((line = htm_in.readLine()) != null) {
        entityList.add(line);
    }
    FileInputStream fos1 = new FileInputStream(new File("extras/hash1.dat")); // loading emoticon dictionary, with key as emoticon and value as its sentiment score
    ObjectInputStream out1 = new ObjectInputStream(fos1);
    emohash1 = (HashMap<String, Double>) out1.readObject();
    //System.out.println(hm1);

    FileInputStream fos2 = new FileInputStream(new File("extras/hash2.dat")); // loading emoticon dictionary, with key as emoticon and value as its sentiment score
    ObjectInputStream out2 = new ObjectInputStream(fos2);
    emohash2 = (HashMap<String, Double>) out2.readObject();
    //System.out.println(hm2);

    //loading senti-wordnet
    FileReader fr2 = new FileReader("extras/SentiWordNet_scores_final.txt");
    BufferedReader br2 = new BufferedReader(fr2);
    String str2;
    senti_map = new HashMap<String, Double>();
    while ((str2 = br2.readLine()) != null) {
        StringTokenizer st = new StringTokenizer(str2, "^");
        senti_map.put(st.nextToken(), Double.parseDouble(st.nextToken()));
    }

    String serializedClassifier = "english.all.3class.distsim.crf.ser.gz"; //NER configuration
    AbstractSequenceClassifier classifier = CRFClassifier.getClassifierNoExceptions(serializedClassifier);
    DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    InputSource is = new InputSource();

    MaxentTagger tagger = new MaxentTagger("taggers/english-left3words-distsim.tagger");

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);
    cb.setOAuthConsumerKey("ufulV3imKoYNzdh58LotTC1YD");
    cb.setOAuthConsumerSecret("2A781ma736HTenAXXYn9tRIelQYJkbCqY0GLi7W71ZwwDmNU59");
    cb.setOAuthAccessToken("2564905075-MY9osfHabaRnonQVHHhHeA1vCLSOhuHWjBNBiIY");
    cb.setOAuthAccessTokenSecret("JsD8Woc7iiFiDSwoCwjNAb6KNEurz7tBqSj9pJV8WXabr");
    twitter4j.TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();

    StatusListener listener = new StatusListener() {
        double score = 0.0;
        double count = 0;
        ArrayList<String> locArray = new ArrayList<String>();

        @Override

        public void onStatus(Status status) {
            String text = status.getText();

            double geoLat = 0.0;
            double geoLng = 0.0;
            String tweetId = status.getId() + "";
            String userName = status.getUser().getName();
            String userId = status.getUser().getId() + "";
            if (status.getGeoLocation() != null) {
                geoLat = status.getGeoLocation().getLatitude();
                geoLng = status.getGeoLocation().getLongitude();
            }

            tweetClean(text, status.getGeoLocation());
            System.out.println(text + "\n" + tweetId + " " + userName + " " + userId);

        }

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

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

        @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.
        }

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

        public void tweetClean(String message, GeoLocation loc) {
            try {

                // URL removal 
                message = removeUrl(message);
                System.out.println("lalala" + message);
                //removing user mentions
                message = userMentions(message);
                //slang removal
                String[] acro = slangRemoval(message);
                //entity removal
                String[] finaldata = entityRemoval(acro);
                message = "";
                for (String word : finaldata) {
                    message += word + " ";
                }
                //System.out.println(message);
                //Ner Taggging
                String XmlData = classifier.classifyWithInlineXML(message);
                message = XmlData;

                //handling words to the spell_checked
                String[] data = message.split("<");
                String val = "";
                for (String word : data) {
                    if (word.startsWith("PER") || word.startsWith("LOC")) {
                        word = word.replaceAll("PERSON>", "");
                        word = word.replaceAll("/PERSON>", "");
                        word = word.replaceAll("LOCATION>", "");
                        word = word.replaceAll("/LOCATION>", "");
                        //insert word into database here 
                        locArray.add(word);
                    } else {
                        word = word.replaceAll("/PERSON>", "");
                        word = word.replaceAll("/LOCATION>", "");
                        //System.out.println(word);
                        val += word;
                    }
                }
                //System.out.println("see" + val);
                if (loc != null || locArray.size() > 0) {
                    val = val.replaceAll("\\s+", " ");
                    String[] temp = val.split(" ");
                    String match = "";
                    //spell_check
                    for (String word : temp) {
                        //System.out.println(word);
                        if (emohash2.containsKey(word)) {
                            score += emohash2.get(word);
                            count++;
                            message = message.replace(word, "");
                        }
                        Process p = Runtime.getRuntime().exec("python extras/text_blob.py " + word);
                        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                        //System.out.println(in.readLine());
                        match = in.readLine();
                        //match = spell_check(word);
                        //System.out.println(match);
                        if (!match.equals(word)) {
                            message = message.replaceAll(word, match);
                        }

                    }
                    System.out.println(message);
                    //UTF-8 emoji's
                    emojiDetection(message);
                    //handle NerTags
                    message = af_spellcheck(message);
                    //System.out.println(a);

                    //removing irrelevant chars         
                    message = removeChars(message);
                    //System.out.println(a);

                    //POS- TAGGING
                    message = posTagging(message);

                    // removing prepositions and nouns
                    message = removePrepn(message);
                    //System.out.println(a);

                    sentiScores(message);
                    System.out.println(score);
                    System.out.println(score / count);
                }

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

        }

        public String removeUrl(String message) {
            String urlPattern = "((https?|ftp|gopher|telnet|file|Unsure|http):((//)|(\\\\))+[\\w\\d:#@%/;$()~_?\\+-=\\\\\\.&]*)";
            Pattern p = Pattern.compile(urlPattern, Pattern.CASE_INSENSITIVE);
            Matcher m = p.matcher(message);
            int i = 0;
            while (m.find()) {
                message = message.replaceAll(m.group(i), "").trim();
                i++;
            }
            return message;
        }

        public String af_spellcheck(String message) {

            message = message.replaceAll("<PERSON>", "");
            message = message.replaceAll("</PERSON>", "");
            message = message.replaceAll("<LOCATION>", "");
            message = message.replaceAll("</LOCATION>", "");
            return message;
        }

        public String removeChars(String message) {

            message = message.replaceAll("\\.", "");
            message = message.replaceAll("\\!", "");
            message = message.replaceAll("\\$", "");
            message = message.replaceAll("\\%", "");
            message = message.replaceAll("\\^", "");
            message = message.replaceAll("\\|", "");
            message = message.replaceAll("\\+", "");
            message = message.replaceAll("\\:", "");
            message = message.replaceAll("\\(", "");
            message = message.replaceAll("\\)", "");
            message = message.replaceAll("\\*", "");
            message = message.replaceAll("\\{", "");
            return message;
        }

        public void sentiScores(String message) {

            message = message.replaceAll("_NNS", "_n");
            message = message.replaceAll("_NN", "_n");
            message = message.replaceAll("_RBR", "_r");
            message = message.replaceAll("_RBS", "_r");
            message = message.replaceAll("_RB", "_r");
            message = message.replaceAll("_JJR", "_a");
            message = message.replaceAll("_JJS", "_a");
            message = message.replaceAll("_JJ", "_a");
            message = message.replaceAll("_VBD", "_v");
            message = message.replaceAll("_VBG", "_v");
            message = message.replaceAll("_VBN", "_v");
            message = message.replaceAll("_VBP", "_v");
            message = message.replaceAll("_VBZ", "_vs");
            message = message.replaceAll("_VB", "_v");

            message = message.replaceAll("\\s+", " ");
            // System.out.println(message);
            String[] senti_token = message.split(" ");

            for (String word : senti_token) {
                word = word.toLowerCase();
                System.out.println(word);
                if (senti_map.containsKey(word)) {

                    score += senti_map.get(word);
                    //System.out.println(score);
                    count++;
                }

            }

        }

        public void emojiDetection(String message) {
            Pattern emo = Pattern.compile("[\\uD83D\\uDE01-\\uD83D\\uDE4F]");
            Matcher m_emo = emo.matcher(message);
            while (m_emo.find()) {
                if (emohash1.containsKey(m_emo.group())) //System.out.println("llalala");
                {
                    score += emohash1.get(m_emo.group());
                }
                count++;
            }
        }

        public String userMentions(String message) {
            Pattern p = Pattern.compile("\\@\\w+");
            Matcher m = p.matcher(message);
            while (m.find()) {
                //System.out.println(m.group());
                message = message.replaceAll(m.group(), "");
            }
            return message;

        }

        public String[] slangRemoval(String message) {
            ArrayList<String> slangRemovalList = new ArrayList<String>();
            String[] words = message.split(" ");
            for (String single : words) {
                if (slangMap.containsKey(single.toUpperCase())) {
                    slangRemovalList.add(slangMap.get(single.toUpperCase()));
                } else {
                    slangRemovalList.add(single);
                }
            }
            String[] myArray = new String[slangRemovalList.size()];
            slangRemovalList.toArray(myArray);
            return myArray;
        }

        public String posTagging(String message) throws Exception {

            String tagged = tagger.tagString(message);

            return tagged;
        }

        public String removePrepn(String message) {
            String delims = " ";
            String[] tokens = message.split(delims);
            for (String word : tokens) {
                if (word.endsWith("_IN") || word.endsWith("_NNP") || word.endsWith("_NNPS")) {
                    message = message.replace(word, "");
                }

            }
            return message;
        }

        public String[] entityRemoval(String[] message) {
            List<String> finalList = new ArrayList<String>();
            for (String word : message) {
                if (!entityList.contains(word.trim())) {
                    finalList.add(word);
                }
            }
            String[] myArray = new String[finalList.size()];
            finalList.toArray(myArray);
            return myArray;
        }

    };
    FilterQuery fq = new FilterQuery();

    String keywords[] = { "Mumbai traffic", "@TrafflineMUM", "TrafficMum", "MumbaiTrafficPol",
            "avoid traffic Mumbai", "Breakdown Mumbai traffic", "@smart_mumbaikar", "@TrafficBOM",
            "#StreetSmartWithTraffline mumbai", "#mumbai #TRAFFICALERT ", "#mumbai #TRAFFIC" };

    fq.track(keywords);
    twitterStream.addListener(listener);
    twitterStream.filter(fq);
}

From source file:tv.phantombot.cache.TwitterCache.java

License:Open Source License

private void handleRetweetRewards(long lastTime, long presentTime) {
    if (presentTime - lastTime < 300) {
        return;// w  w w.ja v  a2  s .  com
    }
    updateDBLong("lastpoll_retweets_reward", presentTime);

    long lastID = getDBLong("lastid_retweets_reward", true, 0L);
    List<Status> statuses = TwitterAPI.instance().getRetweetsOfMe(lastID);

    if (statuses == null) {
        return;
    }

    /* This seems redundant but, Twitter provides the Tweet content of the Retweets in the
     * getRetweetsOfMe() call. So, walk that list of Tweets to get at the Retweet information
     * that includes the Screen Name (@screenName) of the person that performed the Retweet.
     */
    ArrayList<String> userNameList = new ArrayList<String>();
    for (Status status : statuses) {
        List<Status> retweetStatuses = TwitterAPI.instance().getRetweets(status.getId());
        if (retweetStatuses != null) {
            for (Status retweetStatus : retweetStatuses) {
                userNameList.add(retweetStatus.getUser().getScreenName());
            }
        }
    }

    if (!userNameList.isEmpty()) {
        EventBus.instance()
                .post(new TwitterRetweetEvent(userNameList.toArray(new String[userNameList.size()])));
    }

    /* Update DB with the last Tweet ID processed. */
    long twitterID = statuses.get(0).getId();
    updateDBLong("lastid_retweets_reward", twitterID);
}

From source file:tweekan.kotikan.com.tweekan.twitter.BasicTwitterClient.java

License:Open Source License

@Override
public void tweetsForQuery(final String query, final Twitter.Callback callback) {
    new AsyncTask<String, Void, QueryResult>() {

        @Override/*from  www . ja v a 2  s  . c om*/
        protected QueryResult doInBackground(String... params) {
            QueryResult result = null;
            try {
                result = instance.search().search(new Query(params[0]));
            } catch (TwitterException e) {
                e.printStackTrace();
            }
            return result;
        }

        @Override
        protected void onPostExecute(QueryResult queryResult) {
            final Twitter.ServerResponse response = queryResult != null ? Twitter.ServerResponse.SUCCESS
                    : Twitter.ServerResponse.FAILURE;
            final ArrayList<String> results = new ArrayList<String>();
            if (queryResult != null) {
                for (twitter4j.Status tweet : queryResult.getTweets()) {
                    String name = tweet.getUser().getName();
                    String tweetText = tweet.getText();
                    results.add(String.format("user : %s" + "\nmsg  : %s", name, tweetText));
                }
            }

            callback.onRequestComplete(new Twitter.Result() {
                @Override
                public Twitter.ServerResponse response() {
                    return response;
                }

                @Override
                public List<String> tweets() {
                    return results;
                }
            });
        }
    }.execute(query);
}

From source file:tweet.Miner.java

License:Apache License

/**
 * Usage: java twitter4j.examples.search.SearchTweets [query]
 *
 * @param toSearch  /*from www  . ja v a  2 s .com*/
 */
public List<Status> mine(String toSearch) {
    List<Status> results = new ArrayList<Status>();
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET)
            .setOAuthAccessToken(OAUTH_ACCESS_TOKEN).setOAuthAccessTokenSecret(OAUTH_ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    try {
        Query query = new Query(toSearch);
        query.setCount(100);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            results.addAll(result.getTweets());
            for (Status tweet : tweets) {
                System.out.println(
                        tweet.getId() + " @ " + tweet.getUser().getScreenName() + " - " + tweet.getText());
            }
        } while ((query = result.nextQuery()) != null);

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return results;
}

From source file:tweetcrawling.TweetCrawler.java

public void getTweets(TwitterConfiguration tc_) throws IOException, InterruptedException {

    try {//from   w w w .  j  a  va 2 s  . c  o m

        for (String query_ : Queries) {

            // Ngambil tweet dari tiap page lalu disimpan di Statuses
            int maxTweetCrawled = 3240; // This is the number of the latest tweets that we can crawl, specified by Twitter

            Query query = new Query(query_);
            query.setLang("id");
            QueryResult result;
            do {
                rateLimitHandler(tc_, "/search/tweets"); // Check rate limit first
                //System.out.println("kanya sini");
                result = tc_.getTwitter().search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    ArrayList<String> ValToWrite = getValueToWrite(tweet);
                    writeValue(ValToWrite, OutputFile);
                    System.out.println(
                            "@" + tweet.getUser().getScreenName() + " - " + tweet.getText().replace("\n", " "));
                }
                addStatuses(tweets);

            } while ((query = result.nextQuery()) != null);

            //printTweets(OutputFile); // Printing out crawling result per page of this keywords
            //emptyStatuses(); // Empty out the current attribute Statuses so that it can be used for other keywords    

        }

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

}