Example usage for twitter4j QueryResult nextQuery

List of usage examples for twitter4j QueryResult nextQuery

Introduction

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

Prototype

Query nextQuery();

Source Link

Document

Returns a Query instance to fetch next page or null if there is no next page.

Usage

From source file:moderation.Moderate.java

public List getTwitterpost() {

    List posts = new ArrayList();
    try {/*from  ww w  .  j a va2s  . co m*/
        List savedpost = getSavedList(album_id);
        String tagname = this.hash;
        Twitter twitter = setting.TwitterToken.twitterObject();
        Query query = new Query(tagname);
        query.setCount(50);
        QueryResult result;
        result = twitter.search(query);
        List<Status> tweets = result.getTweets();
        for (Status tweet : tweets) {
            System.out.println("\n\n\n" + tweet);
            PostModel post = new PostModel();
            post.setAlbum_id(this.album_id);
            if (savedpost.contains(tweet.getId()))
                post.setStatus("old");
            else
                post.setStatus("new");
            post.setPost_id("" + tweet.getId());
            post.setSender_name(URLEncoder.encode(tweet.getUser().getScreenName(), "UTF-8"));
            post.setCaption_text(URLEncoder.encode(tweet.getText(), "UTF-8"));
            post.setSender_pic(tweet.getUser().getProfileImageURL());
            post.setSender_id("" + tweet.getUser().getId());

            for (MediaEntity mediaEntity : tweet.getMediaEntities()) {
                post.setImage_standard(mediaEntity.getMediaURL());
                post.setImage_low(mediaEntity.getMediaURL());
            }
            post.setPost_time(tweet.getCreatedAt().toString());
            post.setType("twitter_post");
            post.setLink(null);
            post.setParam("post_id=" + post.getPost_id() + "&album_id=" + post.getAlbum_id() + "&type="
                    + post.getType() + "&post_time=" + post.getPost_time() + "&link=" + post.getLink()
                    + "&pic_low=" + post.getImage_low() + "&pic_standard=" + post.getImage_standard()
                    + "&post_message=" + post.getCaption_text() + "&sender_name=" + post.getSender_name()
                    + "&sender_id=" + post.getSender_id() + "&sender_pic=" + post.getSender_pic());

            posts.add(post);

        }
        this.twitternext = result.nextQuery();

    } catch (Exception e) {
        System.err.println("Exception occure in getTwitter " + e);
    }

    return posts;
}

From source file:ontoSentiment.Busca.java

public void buscarPorAssunto(String busca, String lang) throws TwitterException {
    int totalTweets = 0;
    long maxID = -1;
    Query q = new Query(busca + " -filter:retweets -filter:links -filter:replies -filter:images");
    q.setCount(Util.TWEETS_PER_QUERY); // How many tweets, max, to retrieve 
    q.resultType(Query.ResultType.recent); // Get all tweets 
    q.setLang(lang);//from www .  j av  a 2s  . c  o  m
    QueryResult r = Util.getTwitter().search(q);
    do {
        for (Status s : r.getTweets()) {
            totalTweets++;
            if (maxID == -1 || s.getId() < maxID) {
                maxID = s.getId();
            }

            //System.out.printf("O tweet de id %s disse as %s, @%-20s disse: %s\n", new Long(s.getId()).toString(), s.getCreatedAt().toString(), s.getUser().getScreenName(), Util.cleanText(s.getText()));
            System.out.println(Util.cleanText(s.getText()));
        }
        q = r.nextQuery();
        if (q != null) {
            q.setMaxId(maxID);
            r = Util.getTwitter().search(q);
            System.out.println("Total tweets: " + totalTweets);
            System.out.println("Maximo ID: " + maxID);
            Util.imprimirRateLimit(Util.RATE_LIMIT_OPTION_SEARCH_TWEETS);
        }
    } while (q != null);
}

From source file:org.apache.blur.demo.twitter.Whiteboard.java

License:Apache License

/**
 * @param args/*w  ww  .j a va 2  s  . co m*/
 * @throws TwitterException
 */
public static void main(String[] args) throws TwitterException {
    Twitter twitter = new TwitterFactory(new ConfigurationBuilder().build()).getInstance();
    OAuth2Token token = twitter.getOAuth2Token();
    System.out.println(token.getTokenType());

    try {
        Query query = new Query("Apache");
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                System.out.println("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());

            }
        } while ((query = result.nextQuery()) != null);
        System.exit(0);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
        System.exit(-1);
    }

}

From source file:org.apache.camel.component.twitter.consumer.search.SearchConsumer.java

License:Apache License

private List<Status> search(Query query) throws TwitterException {
    Integer numberOfPages = 1;/*w  w w.j  a  v  a  2s .c om*/

    if (ObjectHelper.isNotEmpty(te.getProperties().getLang())) {
        query.setLang(te.getProperties().getLang());
    }

    if (ObjectHelper.isNotEmpty(te.getProperties().getCount())) {
        query.setCount(te.getProperties().getCount());
    }

    if (ObjectHelper.isNotEmpty(te.getProperties().getNumberOfPages())) {
        numberOfPages = te.getProperties().getNumberOfPages();
    }

    LOG.debug("Searching with " + numberOfPages + " pages.");

    Twitter twitter = te.getProperties().getTwitter();
    QueryResult qr = twitter.search(query);
    List<Status> tweets = qr.getTweets();

    for (int i = 1; i < numberOfPages; i++) {
        if (!qr.hasNext()) {
            break;
        }

        qr = twitter.search(qr.nextQuery());
        tweets.addAll(qr.getTweets());
    }

    if (te.getProperties().isFilterOld()) {
        for (Status t : tweets) {
            checkLastId(t.getId());
        }
    }

    return tweets;
}

From source file:org.apache.camel.component.twitter.producer.SearchProducer.java

License:Apache License

@Override
public void process(Exchange exchange) throws Exception {
    long myLastId = lastId;
    // KEYWORDS//from   w  ww  .  j  ava  2  s  .  co m
    // keywords from header take precedence
    String keywords = exchange.getIn().getHeader(TwitterConstants.TWITTER_KEYWORDS, String.class);
    if (keywords == null) {
        keywords = te.getProperties().getKeywords();
    }

    if (keywords == null) {
        throw new CamelExchangeException("No keywords to use for query", exchange);
    }

    Query query = new Query(keywords);

    // filter of older tweets
    if (te.getProperties().isFilterOld() && myLastId != 0) {
        query.setSinceId(myLastId);
    }

    // language
    String lang = exchange.getIn().getHeader(TwitterConstants.TWITTER_SEARCH_LANGUAGE, String.class);
    if (lang == null) {
        lang = te.getProperties().getLang();
    }

    if (ObjectHelper.isNotEmpty(lang)) {
        query.setLang(lang);
    }

    // number of elemnt per page
    Integer count = exchange.getIn().getHeader(TwitterConstants.TWITTER_COUNT, Integer.class);
    if (count == null) {
        count = te.getProperties().getCount();
    }
    if (ObjectHelper.isNotEmpty(count)) {
        query.setCount(count);
    }

    // number of pages
    Integer numberOfPages = exchange.getIn().getHeader(TwitterConstants.TWITTER_NUMBER_OF_PAGES, Integer.class);
    if (numberOfPages == null) {
        numberOfPages = te.getProperties().getNumberOfPages();
    }

    Twitter twitter = te.getProperties().getTwitter();
    log.debug("Searching twitter with keywords: {}", keywords);
    QueryResult results = twitter.search(query);
    List<Status> list = results.getTweets();

    for (int i = 1; i < numberOfPages; i++) {
        if (!results.hasNext()) {
            break;
        }
        log.debug("Fetching page");
        results = twitter.search(results.nextQuery());
        list.addAll(results.getTweets());
    }

    if (te.getProperties().isFilterOld()) {
        for (Status t : list) {
            long newId = t.getId();
            if (newId > myLastId) {
                myLastId = newId;
            }
        }
    }

    exchange.getIn().setBody(list);
    // update the lastId after finished the processing
    if (myLastId > lastId) {
        lastId = myLastId;
    }
}

From source file:org.kawalpemilukada.web.controller.SentimentAnalysis.java

private void cariText(JSONArray returnVals, Twitter twitter, String topic) throws ParseException {
    try {//from w  w  w.  ja va2 s.com
        Query query = new Query(topic);
        query.setCount(100);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                JSONObject returnVal = new JSONObject();
                returnVal.put("Text", tweet.getText());
                //returnVal.put("HashtagEntities", tweet.getHashtagEntities().toString());
                //returnVal.put("UserMentionEntities", tweet.getUserMentionEntities().toString());
                returnVal.put("FavoriteCount", tweet.getFavoriteCount());
                returnVal.put("RetweetCount", tweet.getRetweetCount());
                returnVal.put("UserImg", tweet.getUser().getBiggerProfileImageURLHttps().toString());
                returnVal.put("UserLink",
                        "https://twitter.com/" + CommonServices.getVal(tweet.getUser().getScreenName()));
                returnVal.put("CreatedAt", JakartaTime(tweet.getCreatedAt()).toString());
                returnVals.add(returnVal);
            }
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        te.printStackTrace();
    }
}

From source file:org.luwrain.app.twitter.Base.java

License:Open Source License

static private TweetWrapper[] search(Twitter twitter, String text, int numPages) {
    NullCheck.notNull(twitter, "twitter");
    NullCheck.notEmpty(text, "text");
    if (numPages < 1)
        throw new IllegalArgumentException("numPages must be greater than zero");
    final LinkedList<TweetWrapper> wrappers = new LinkedList<TweetWrapper>();
    try {/*www .j av a 2s . c  o  m*/
        Query query = new Query(text);
        QueryResult result;
        int pageNum = 1;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            System.out.println("" + tweets.size());
            for (Status tweet : tweets)
                wrappers.add(new TweetWrapper(tweet));
            if (pageNum >= numPages)
                return wrappers.toArray(new TweetWrapper[wrappers.size()]);
            ++pageNum;
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException e) {
        e.printStackTrace();
        return null;
    }
    return wrappers.toArray(new TweetWrapper[wrappers.size()]);
}

From source file:org.wandora.application.tools.extractors.twitter.AbstractTwitterExtractor.java

License:Open Source License

public void searchTwitter(Query[] queries, int pages, TopicMap tm) {
    if (tm == null || queries == null || queries.length == 0)
        return;// w  ww  .j  av a 2s.  c  om

    initializeTwitter();

    if (pin == null || pin.length() == 0) {
        try {
            AccessToken accessToken = null;
            String authorizationURL = requestToken.getAuthorizationURL();

            TwitterAuthorizationDialog authorizer = new TwitterAuthorizationDialog();
            authorizer.open(authorizationURL);

            if (authorizer.wasAccepted()) {
                pin = authorizer.getPin();
            } else {
                return;
            }

            if (pin != null && pin.length() > 0) {
                accessToken = twitter.getOAuthAccessToken(requestToken, pin);
            } else {
                accessToken = twitter.getOAuthAccessToken();
            }
        } catch (TwitterException ex) {
            log("Invalid Twitter authorization. Please, check the PIN code '" + pin + "' and try again.");
            //log(ex);
            pin = null;
            return;
        }
    }

    try {
        Topic twitterSearchTopic = tm.createTopic();
        if (twitterSearchTopic != null) {
            long stamp = System.currentTimeMillis();
            twitterSearchTopic.addSubjectIdentifier(new Locator(TWITTER_SEARCH_BODY + "/" + stamp));
            twitterSearchTopic.setBaseName("Twitter search " + stamp);
            twitterSearchTopic.addType(getTwitterSearchType(tm));

            Topic twitterSearchDateType = getTwitterSearchDateType(tm);
            if (twitterSearchDateType != null) {
                Date d = new Date(stamp);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dStr = sdf.format(d);
                twitterSearchTopic.setData(twitterSearchDateType,
                        TMBox.getLangTopic(twitterSearchTopic, DEFAULT_LANG), dStr);
            }

            for (Query currentQuery : queries) {
                if (currentQuery == null)
                    continue;
                int currentPage = 0;
                log("Processing Twitter query '" + currentQuery.getQuery() + "'");
                while (currentQuery != null) {
                    if (forceStop()) {
                        log("Aborting...");
                        break;
                    }
                    currentPage++;
                    hlog("Requesting search result page " + currentPage + (pages == 0 ? "" : " of " + pages));

                    QueryResult result = twitter.search(currentQuery);

                    Topic twitterSearchQueryType = getTwitterSearchQueryType(tm);
                    if (twitterSearchQueryType != null) {
                        twitterSearchTopic.setData(twitterSearchQueryType,
                                TMBox.getLangTopic(twitterSearchTopic, DEFAULT_LANG), currentQuery.getQuery());
                    }

                    ArrayList tweets = (ArrayList) result.getTweets();
                    for (Object tweet : tweets) {
                        if (tweet != null && tweet instanceof Status) {
                            Status t = (Status) tweet;
                            Topic topic = reifyTweet(t, tm);
                            topic.addType(twitterSearchTopic);
                        }
                    }

                    try {
                        Thread.currentThread().sleep(SLEEP_TIME_BETWEEN_SEARCHES);
                    } catch (Exception e) {
                        // ...WAKE UP...
                    }

                    if (pages == 0 || currentPage < pages) {
                        currentQuery = result.nextQuery();
                    } else {
                        currentQuery = null;
                    }
                }
                log("Number of processed search result pages is " + currentPage);
            }
        }
    } catch (TopicMapException tme) {
        log("A topic map exception " + tme.getMessage() + " occurred while searching Twitter messages.");
        tme.printStackTrace();
    } catch (TwitterException te) {
        log("A Twitter exception " + te.getMessage() + " occurred while searching messages.");
        te.printStackTrace();
    }
    ;
}

From source file:sentimentanalysis.Twitter.GetTweets.java

public static void main(String args[]) {

    Twitter4JConfig t4jConfig = new Twitter4JConfig();
    ConfigurationBuilder cb = t4jConfig.getConfigurationBuilder();

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();// ww  w. j  a  v  a  2s.co  m
    String keyword = "Trump";

    ArrayList<Post> TweetResultList = new ArrayList<Post>();
    int count = 0;
    try {

        Query query = new Query(keyword + "+exclude:retweets+lang:en").until("2016-11-19");
        QueryResult result;

        do {
            result = twitter.search(query);
            ArrayList<Status> tweets = (ArrayList<Status>) result.getTweets();

            for (Status tweet : tweets) {
                count++;

                String user = tweet.getUser().getScreenName();
                String content = tweet.getText();
                Date time = tweet.getCreatedAt();
                System.out.println(time.getTime());
                String tweet_url = "https://twitter.com/" + tweet.getUser().getScreenName() + "/status/"
                        + tweet.getId();
                System.out.println(tweet.getLang());
                Post tr = new Post(user, content, tweet_url, new java.sql.Date(time.getTime()));
                TweetResultList.add(tr);

                //                    System.out.println("[user]@" + tweet.getUser().getScreenName() 
                //                        + "[/user][tweet]" + tweet.getText()+"[/tweet][link]"+tweet_url+"[/link]");
            }

        } while (((query = result.nextQuery()) != null) && (count < 500));

        try {
            SaveToDB.savePosts(TweetResultList);
        } catch (SQLException ex) {
            java.util.logging.Logger.getLogger(GetTweets.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (TwitterException te) {
        te.printStackTrace();
    }

}

From source file:sentinets.ImportTweets.java

License:Open Source License

private List<Status> getTweets(String queryStr, int countOfTweets) {
    Query query = new Query(queryStr);
    query.setCount(countOfTweets);/*from ww  w  . ja va 2  s.co m*/
    query.setLang("en");
    QueryResult result = null;
    List<Status> tweets = new ArrayList<Status>();
    do {
        try {
            result = twitter.search(query);
        } catch (TwitterException e) {
            e.printStackTrace();
            e.printStackTrace();
            System.out.println("Failed to search tweets: " + e.getMessage());

        }
        tweets.addAll(result.getTweets());
    } while ((query = result.nextQuery()) != null && tweets.size() <= countOfTweets);
    return tweets;
}