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:aic.group5.topic3.analysis.TwitterQueryWrapper.java

License:Apache License

public List<Status> query(String queryString) throws Exception {
    List<Status> result = new ArrayList<Status>();

    twitter = twitterFactory.getInstance();
    Query query = new Query(queryString);
    query.setCount(100);//from   w  w w .j  ava 2  s  .  c  om
    QueryResult queryResult = null;

    queryResult = searchWithRetry(query, retryAttempts);

    List<Status> tweets = queryResult.getTweets();
    for (Status tweet : tweets)
        result.add(tweet);

    return result;
}

From source file:alberapps.java.noticias.tw.tw4j.ProcesarTwitter4j.java

License:Open Source License

/**
 * Buscar/*from   w w  w  . j  a  v  a 2  s  .  c o  m*/
 *
 * @return lista
 */
public List<TwResultado> recuperarSearch() {

    List<TwResultado> listaResultados = null;

    try {

        Query query = new Query("from:Alicante_City");

        QueryResult resultados = twitter.search(query);

        List<Status> timeline = resultados.getTweets();

        listaResultados = new ArrayList<>();

        TwResultado resultado = null;

        for (int i = 0; i < timeline.size(); i++) {

            resultado = new TwResultado();

            resultado.setId(Long.toString(timeline.get(i).getId()));
            resultado.setFechaDate(timeline.get(i).getCreatedAt());
            resultado.setNombreCompleto(timeline.get(i).getUser().getName());
            resultado.setUsuario(timeline.get(i).getUser().getScreenName());
            resultado.setMensaje(timeline.get(i).getText());
            resultado.setImagen(timeline.get(i).getUser().getMiniProfileImageURLHttps());

            // Imagen de perfil
            resultado.setImagenBitmap(recuperaImagen(resultado.getImagen()));

            resultado.setUrl("");

            listaResultados.add(resultado);

        }

    } catch (TwitterException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return listaResultados;

}

From source file:android.stickynotes.StickyNotesActivity.java

License:Apache License

private void getTweets(String twit) {
    wifi.setWifiEnabled(true);/*from  ww w  .  j  a va 2s  .co  m*/
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("TvywVhWx7r7QQev2UGfA4g")
            .setOAuthConsumerSecret("Nv22zsyf1VS0vvi6hwAMyvJk9LUtSXwRUB4xwp2gRs");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    try {
        QueryResult result = twitter.search(new Query(twit));
        List<Tweet> tweets = result.getTweets();
        textStatus.setText("");
        textStatus.append("Recent tweets about '" + twit + "':\n");
        for (Tweet tweet : tweets) {
            textStatus.append("@" + tweet.getFromUser() + " - " + tweet.getText() + "\n\n");
        }
    } catch (TwitterException te) {
        te.printStackTrace();
        textStatus.append("Failed to search tweets: " + te.getMessage() + " " + twit);
    }
}

From source file:apptwitter.Metodos.java

public void buscarTrending(String busqueda) throws TwitterException {

    Query query = new Query(busqueda);
    QueryResult result = twitter.search(query);
    for (Status status : result.getTweets()) {
        System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
    }/*  ww w  .j  a  v a  2  s.  c  om*/

}

From source file:au.com.infiniterecursion.hashqanda.MainActivity.java

public boolean loadTweets() {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("Q2DfeCNOxprbDp66fWlw")
            .setOAuthConsumerSecret("TgyJ26CKXz1SxGiEJx4HG9rytFsqiMZlEPeCO7S9g");

    Twitter twitter = new TwitterFactory(cb.build()).getInstance();
    // clear tweet list.
    MainActivity.this.runOnUiThread(new Runnable() {

        public void run() {
            // add to it , via the runOnUIThread
            app.getTweetList().clear();/* ww w  .  j a v a2 s  .c  om*/
        }

    });

    try {
        Log.d(TAG, " starting Tweets loading ");
        Query q = new Query("#qanda");

        q.setRpp(numberTweets);

        QueryResult result = twitter.search(q);
        List<Tweet> tweets = result.getTweets();
        for (Tweet tweet : tweets) {
            // Log.d(TAG, "@" + tweet.getFromUser() + " - " +
            // tweet.getText());
            // Log.d(TAG, " img url " + tweet.getProfileImageUrl());

            final CachedBitmapAndTweet cachedbmtwt = new CachedBitmapAndTweet();

            cachedbmtwt.twt = tweet;

            try {
                URL url = new URL(tweet.getProfileImageUrl());
                InputStream is = (InputStream) url.getContent();

                if (is != null) {
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    cachedbmtwt.bm = bitmap;
                } else {
                    cachedbmtwt.bm = null;
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
                cachedbmtwt.bm = null;
            } catch (IOException e) {
                e.printStackTrace();
                cachedbmtwt.bm = null;
            } catch (NullPointerException npe) {
                npe.printStackTrace();
                cachedbmtwt.bm = null;
            }

            MainActivity.this.runOnUiThread(new Runnable() {

                public void run() {
                    // add to it , via the runOnUIThread
                    app.getTweetList().add(cachedbmtwt);
                }

            });

        }

        Log.d(TAG, " finished Tweets loading ");

        return true;

    } catch (TwitterException te) {
        te.printStackTrace();
        Log.d(TAG, "Failed to search tweets: " + te.getMessage());
        return false;
    }
}

From source file:Beans.Crawler.java

public String teste() {
    String result = "";
    int totalTweets = 0;
    long maxID = -1;

    GeoLocation geo = new GeoLocation(Double.parseDouble("-19.9225"), Double.parseDouble("-43.9450"));
    result += geo.getLatitude() + " " + geo.getLongitude() + "<br><br>";

    Twitter twitter = getTwitter();/*  w  ww .j a  v  a2 s .  c om*/

    try {
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");

        result += "You have " + searchTweetsRateLimit.getRemaining() + " calls remaining out of "
                + searchTweetsRateLimit.getLimit() + ", Limit resets in "
                + searchTweetsRateLimit.getSecondsUntilReset() + " seconds<br/><br/>";

        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            //   Do we need to delay because we've already hit our rate limits?
            if (searchTweetsRateLimit.getRemaining() == 0) {
                //   Yes we do, unfortunately ...
                //                        System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset());

                //   If you sleep exactly the number of seconds, you can make your query a bit too early
                //   and still get an error for exceeding rate limitations
                //
                //    Adding two seconds seems to do the trick. Sadly, even just adding one second still triggers a
                //   rate limit exception more often than not.  I have no idea why, and I know from a Comp Sci
                //   standpoint this is really bad, but just add in 2 seconds and go about your business.  Or else.
                //               Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset()+2) * 1000l);
            }

            Query q = new Query(SEARCH_TERM); //.geoCode((geo), 100, "mi");         // Search for tweets that contains this term
            q.setCount(TWEETS_PER_QUERY); // How many tweets, max, to retrieve
            //                    q.setGeoCode(geo, 100, Query.Unit.mi);
            //                    q.setSince("2012-02-20");
            //                                
            //            q.resultType("recent");                  // Get all tweets
            //            q.setLang("en");                     // English language tweets, please

            //   If maxID is -1, then this is our first call and we do not want to tell Twitter what the maximum
            //   tweet id is we want to retrieve.  But if it is not -1, then it represents the lowest tweet ID
            //   we've seen, so we want to start at it-1 (if we start at maxID, we would see the lowest tweet
            //   a second time...
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }

            //   This actually does the search on Twitter and makes the call across the network
            QueryResult r = twitter.search(q);

            //   If there are NO tweets in the result set, it is Twitter's way of telling us that there are no
            //   more tweets to be retrieved.  Remember that Twitter's search index only contains about a week's
            //   worth of tweets, and uncommon search terms can run out of week before they run out of tweets
            if (r.getTweets().size() == 0) {
                break; // Nothing? We must be done
            }

            //   loop through all the tweets and process them.  In this sample program, we just print them
            //   out, but in a real application you might save them to a database, a CSV file, do some
            //   analysis on them, whatever...
            for (Status s : r.getTweets()) // Loop through all the tweets...
            {
                //   Increment our count of tweets retrieved
                totalTweets++;

                //   Keep track of the lowest tweet ID.  If you do not do this, you cannot retrieve multiple
                //   blocks of tweets...
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }
                //   Do something with the tweet....
                result += "ID: " + s.getId() + " Data " + s.getCreatedAt().toString() + " user "
                        + s.getUser().getScreenName() + " texto: " + cleanText(s.getText()) + "  <br/>";

            }

            //   As part of what gets returned from Twitter when we make the search API call, we get an updated
            //   status on rate limits.  We save this now so at the top of the loop we can decide whether we need
            //   to sleep or not before making the next call.
            searchTweetsRateLimit = r.getRateLimitStatus();
        }

    } catch (Exception e) {
        //   Catch all -- you're going to read the stack trace and figure out what needs to be done to fix it
    }
    result += "<br><br>" + totalTweets + "<br>";
    return result;
}

From source file:Beans.Crawler.java

public List search(Categoria categoria, Localizacao localizacao) throws Exception {
    long maxID = -1;

    List<Tweet> list = new ArrayList<Tweet>();
    Twitter twitter = getTwitter();//from w  ww.  j a  v  a2  s . c  o m
    try {
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            if (searchTweetsRateLimit.getRemaining() == 0) {
            }

            String works = localizacao.getPalavrasChaves();
            String[] arrWorks = works.split(",");
            String keywork = "", or = "OR";

            for (int i = 0; i < arrWorks.length; i++) {
                if ((i + 1) >= arrWorks.length) {
                    or = "";
                }
                keywork += " \"" + arrWorks[i] + "\" " + or;
            }
            System.out.println("exclude:retweets " + categoria.getDescricao() + keywork);
            Query q = new Query("exclude:retweets " + categoria.getDescricao() + keywork);
            q.setCount(TWEETS_PER_QUERY);
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }
            QueryResult r = twitter.search(q);
            if (r.getTweets().size() == 0) {
                break;
            }
            for (Status s : r.getTweets()) {
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }
                Tweet t = new Tweet();
                t.setUsuario(s.getUser().getId());
                String dataPostagem = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(s.getCreatedAt());
                t.setDataPostagem(dataPostagem);
                t.setTweet(s.getText());
                t.setTweetId(s.getId());
                t.setCategoriaId(categoria.getId());
                t.setLocalizacaoId(localizacao.getId());
                list.add(t);
            }
            searchTweetsRateLimit = r.getRateLimitStatus();
        }
    } catch (Exception e) {
        throw e;
    }

    return list;
}

From source file:br.com.controller.TweetController.java

public String search() {
    Categoria c = new CategoriaDAO().find(Integer.parseInt(categoria));
    Localizacao l = new LocalizacaoDAO().find(Integer.parseInt(localizacao));
    long maxID = -1;

    Twitter twitter = getTwitter();//w  w  w. j av a  2  s .  c  om
    try {
        Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
        RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
        for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
            if (searchTweetsRateLimit.getRemaining() == 0) {
            }

            String works = c.getPalavrasChaves();
            String[] arrWorks = works.split(",");
            String keywork = "", or = "OR", query = "";

            for (int i = 0; i < arrWorks.length; i++) {
                if ((i + 1) >= arrWorks.length) {
                    or = "";
                }
                keywork += " \"" + arrWorks[i] + "\" " + or;
            }

            query = "exclude:retweets " + keywork;

            works = l.getPalavrasChaves();
            arrWorks = works.split(",");
            keywork = "";
            or = "OR";

            for (int i = 0; i < arrWorks.length; i++) {
                if ((i + 1) >= arrWorks.length) {
                    or = "";
                }
                keywork += " \"" + arrWorks[i] + "\" " + or;
            }

            query += keywork;

            Query q = new Query(query);
            q.setCount(TWEETS_PER_QUERY);
            if (maxID != -1) {
                q.setMaxId(maxID - 1);
            }
            QueryResult r = twitter.search(q);
            if (r.getTweets().size() == 0) {
                break;
            }
            for (Status s : r.getTweets()) {
                if (maxID == -1 || s.getId() < maxID) {
                    maxID = s.getId();
                }

                Tweet t = new Tweet();
                t.setUsuario(s.getUser().getId());
                t.setDataPostagem(s.getCreatedAt());
                t.setTweet(s.getText());
                if (!new DAO.TweetDAO().hastTweet(s.getId())) {
                    t.setTweetId(s.getId());
                    t.setCategoria(c);
                    t.setLocalizacao(l);
                    jpa.saveOrUpdate(t);
                }
            }
            searchTweetsRateLimit = r.getRateLimitStatus();
        }
    } catch (Exception e) {
    }

    return "index";
}

From source file:br.com.porcelli.hornetq.integration.twitter.stream.reclaimer.AbstractBaseReclaimLostTweets.java

License:Apache License

protected void loadQuery(final String query, final Long lastTweetId, final Twitter twitter) throws Exception {
    try {//from  w w  w .j  a  va2s  . co m
        if (lastTweetId == null) {
            return;
        }
        int page = 1;
        while (true) {
            final Query qry = new Query(query).sinceId(lastTweetId).page(page);
            final QueryResult qr = twitter.search(qry);
            if (qr.getTweets().size() == 0) {
                break;
            }
            for (final Tweet activeTweet : qr.getTweets()) {
                message.postMessage(activeTweet, true);
            }
            page++;
        }
    } catch (Exception e) {
        exceptionNotifier.notifyException(e);
    }
}

From source file:br.unisal.twitter.bean.TwitterBean.java

public void consultarTweets() {
    TwitterFactory TwitterFactory = new TwitterFactory();
    Twitter twitter = TwitterFactory.getSingleton();
    List<Status> tweets = new ArrayList<>();
    Query query = new Query(getTwittQuery());
    try {/* ww w.  j a va  2 s .  c  o  m*/
        QueryResult result = twitter.search(query);
        tweets.addAll(result.getTweets());
        StringBuilder builder = new StringBuilder();
        double lon = 0;
        double lat = 0;
        for (Status s : tweets) {
            if ((s.getGeoLocation() != null)) {
                lon = s.getGeoLocation().getLongitude();
                lat = s.getGeoLocation().getLatitude();
            }
            Tweet t = new Tweet(s.getUser().getName(), s.getUser().getLocation(), s.getText(), s.getCreatedAt(),
                    lat, lon);
            dao.insert(t);
            builder.append(t.toString());
        }
        this.getUiResultQuery().setSubmittedValue(builder.toString());
    } catch (TwitterException te) {
        System.out.println("Failed to search tweets: " + te.getMessage());
    }
}