Example usage for twitter4j Query Query

List of usage examples for twitter4j Query Query

Introduction

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

Prototype

public Query(String query) 

Source Link

Usage

From source file:tweets.Tweets.java

/**
 * @param args the command line arguments
 *//*  w w  w  .j a v a 2  s  . c  o  m*/
public static void main(String[] args) throws Exception {

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

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

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

            }

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

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

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

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

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

    }
    bw.close();
}

From source file:tweets_stock_price_prediction.TweetsManager.java

public ArrayList<String> getTweets(String topic, String fromDate, String toDate) {

    //Twitter twitter = new TwitterFactory().getInstance();
    System.out.println("*** TWITTER QUERY: " + topic);
    ArrayList<String> tweetList = new ArrayList<String>();
    try {/*from  www. j  a v  a2 s. co  m*/
        Query query = new Query(topic);
        query.setLang("en");
        //query.setCount(count);
        query.setSince(fromDate);
        query.setUntil(toDate);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                //System.out.print("LANGUAGE " + tweet.getLang() + "\n\n");
                //if (tweet.getLang().equals("en")) {
                tweetList.add(tweet.getText());
                //}
            }
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    }

    System.out.println("************ TWEET LIST: " + tweetList.size());
    return tweetList;
}

From source file:twit.TwitterConnector.java

/**
 * Mencari tweet yang mengandung keyword tertentu
 * @param n merupakan jumlah tweet terbaru
 * @param keyword merupakan kata kunci yang ingin dicari
 * @return List yang mengandung keyword//from w ww.  ja  v  a 2  s .c  o m
 */
public List<Status> searchKeyword(int n, String keyword) {
    try {
        query = new Query(keyword);
        query.setCount(n);
        QueryResult result;
        result = twitter.search(query);
        tweets = result.getTweets();

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

From source file:twitah.Metodos.java

/**
 * Used to search for twits//w ww  .j  av 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:Twitter.Frame.java

public void getTwitters() {
    flag = false;/*from   ww w  . j a v  a2s . c  o  m*/
    query = new Query(squery);
    try {
        result = twitter.search(query);
        tacol.setText("");
        for (Status status : result.getTweets()) {
            insertTwitt(statustoJSON(status));
        }
    } catch (TwitterException ex) {
        ex.printStackTrace();
    }
    flag = true;
}

From source file:twitter.TweetGet.java

public void query(String queryString) {
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("2MZnm7LM7Ik9W3hzcXJOBaNER")
            .setOAuthConsumerSecret("0GER2kH3o1gOAyfPEDd870Iiuiu6XbQDayAXWfUBxU5APg4Le6")
            .setOAuthAccessToken("18972247-HgBP0djVaLw4U9fSX4lUdhKpZcqsJIAgnUCW3DRS5")
            .setOAuthAccessTokenSecret("bn8EQoOyGSRVUNX6elTmX9Wt9jiFJaxDaCZDk3U3hQB0g");

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    Query query = new Query(queryString);
    query.setCount(20);/*from w  w  w. j  a  va2 s. co m*/
    QueryResult result;
    try {
        result = twitter.search(query);
        tweets = result.getTweets();

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

From source file:TwitterAnalytics.TwitterAPI.java

private Query makeQuery(List<String> keywords) throws TwitterException {
    // asumsi: pake OR
    if (keywords.isEmpty()) {
        throw new TwitterException("No keyword entered!");
    } else {//w w  w .  j  a  v a  2s  .  c o m
        StringBuilder sb = new StringBuilder();

        int i = 0;
        sb.append("(").append(keywords.get(i)).append(")");
        i++;

        while (i < keywords.size()) {
            sb.append("OR (").append(keywords.get(i)).append(")");
            i++;
        }

        return new Query(sb.toString());
    }
}

From source file:twitterapi.TwitterAPI.java

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

    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        String locationCity = null;
        String locationCountry = null;
        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:twitterAPI.Twitter_testing.java

public void getSearchTweets(String regex) {
    //String queryStr = "@RobotGrrl";
    try {/*from  www .  jav a 2 s.  c  o m*/
        //Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(regex);
        query.count(100);
        System.out.println(query.getCount());

        QueryResult result = twitter.search(query);
        for (Status status : result.getTweets()) {

            searchHandler sh = new searchHandler();
            sh.nama = status.getUser().getScreenName();
            sh.tweet = status.getText();

            StringBuffer address = new StringBuffer();
            address.append("http://twitter.com/#!/");
            address.append(sh.nama);
            address.append("/status/");
            address.append(status.getId());

            String theAddressYouWant = address.toString();
            sh.URL = theAddressYouWant;
            shholder.add(sh);
            //System.out.println(theAddressYouWant); ini buat test bener apa ga url nya , udah bener
            //System.out.println("@" + sh.nama + ":" + sh.tweet);
        }
    } catch (TwitterException e) {
        System.out.println("Search tweets: " + e);
    }
}

From source file:twitterapidemo.TwitterAPIDemo.java

License:Apache License

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

    //TwitterAPIDemo twitterApiDemo = new TwitterAPIDemo();

    ConfigurationBuilder builder = new ConfigurationBuilder();
    builder.setOAuthConsumerKey(consumerKey);
    builder.setOAuthConsumerSecret(consumerSecret);
    Configuration configuration = builder.build();

    TwitterFactory twitterFactory = new TwitterFactory(configuration);
    Twitter twitter = twitterFactory.getInstance();
    twitter.setOAuthAccessToken(new AccessToken(accessToken, accessTokenSecret));

    Scanner sc = new Scanner(System.in);
    System.out.println(//from  w w  w.  j  a v  a  2s .c  o m
            "Enter your choice:\n1. To post tweet\n2.To search tweets\n3. Recent top 3 trends and number of posts of each trending topic");
    int choice = sc.nextInt();
    switch (choice) {
    case 1:
        System.out.println("What's happening: ");
        String post = sc.next();
        StatusUpdate statusUpdate = new StatusUpdate(post + "-Posted by TwitterAPI");
        Status status = twitter.updateStatus(statusUpdate);

        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.getURLEntities() = " + Arrays.toString(status.getURLEntities()));
        System.out.println(
                "status.getUserMentionEntities() = " + Arrays.toString(status.getUserMentionEntities()));
        break;
    case 2:
        System.out.println("Enter keyword");
        String keyword = sc.next();
        try {
            Query query = new Query(keyword);
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    System.out.println(tweet.getCreatedAt() + ":\t@" + tweet.getUser().getScreenName() + " - "
                            + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
            System.exit(0);
        } catch (TwitterException te) {
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
            break;
        }
    case 3:
        //WOEID for India = 23424848
        Trends trends = twitter.getPlaceTrends(23424848);
        int count = 0;
        for (Trend trend : trends.getTrends()) {
            if (count < 3) {
                Query query = new Query(trend.getName());
                QueryResult result;
                int numberofpost = 0;
                do {
                    result = twitter.search(query);
                    List<Status> tweets = result.getTweets();
                    for (Status tweet : tweets) {
                        numberofpost++;
                    }
                } while ((query = result.nextQuery()) != null);
                System.out
                        .println("Number of post for the topic '" + trend.getName() + "' is: " + numberofpost);
                count++;
            } else
                break;
        }
        break;
    default:
        System.out.println("Invalid input");
    }
}