Example usage for twitter4j Query setCount

List of usage examples for twitter4j Query setCount

Introduction

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

Prototype

public void setCount(int count) 

Source Link

Document

sets the number of tweets to return per page, up to a max of 100

Usage

From source file:org.codice.ddf.catalog.twitter.source.TwitterSource.java

License:Open Source License

@Override
public SourceResponse query(QueryRequest request) throws UnsupportedQueryException {
    Twitter instance = twitterFactory.getInstance();
    try {/* w w w.  ja va  2s  .co  m*/
        instance.getOAuth2Token();
    } catch (TwitterException e) {
        throw new UnsupportedQueryException("Unable to get OAuth2 token.", e);
    }
    TwitterFilterVisitor visitor = new TwitterFilterVisitor();
    request.getQuery().accept(visitor, null);
    Query query = new Query();
    query.setCount(request.getQuery().getPageSize());
    if (visitor.hasSpatial()) {
        GeoLocation geoLocation = new GeoLocation(visitor.getLatitude(), visitor.getLongitude());
        query.setGeoCode(geoLocation, visitor.getRadius(), Query.Unit.km);
    }
    if (visitor.getContextualSearch() != null) {
        query.setQuery(visitor.getContextualSearch().getSearchPhrase());
    }
    if (visitor.getTemporalSearch() != null) {
        Calendar.Builder builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getStartDate());
        Calendar calendar = builder.build();
        query.setSince(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));

        builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getEndDate());
        calendar = builder.build();
        query.setUntil(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));
    }

    QueryResult queryResult;
    try {
        queryResult = instance.search().search(query);
    } catch (TwitterException e) {
        throw new UnsupportedQueryException(e);
    }
    List<Result> resultList = new ArrayList<>(queryResult.getCount());
    resultList.addAll(queryResult.getTweets().stream().map(status -> new ResultImpl(getMetacard(status)))
            .collect(Collectors.toList()));
    return new SourceResponseImpl(request, resultList);
}

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

private void cariText(JSONArray returnVals, Twitter twitter, String topic) throws ParseException {
    try {//w w w.  j a v a  2s  .  c o m
        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.kuali.mobility.conference.controllers.ConferenceController.java

License:Open Source License

@RequestMapping(value = "twitter-search", method = RequestMethod.GET)
public ResponseEntity<String> twitterSearch(@RequestParam(value = "term", required = true) String searchParam,
        @RequestParam(value = "since", required = false) String sinceParam, HttpServletRequest request) {

    Twitter twitter = TwitterFactory.getSingleton();
    Query query = new Query(searchParam.isEmpty() ? "#kualidays" : searchParam);
    QueryResult result = null;/*from  w ww  .  j a  va2 s  .  c  o  m*/
    query.setSince(!sinceParam.isEmpty() ? sinceParam : "2014-01-01");
    query.setCount(100);
    query.setResultType(Query.MIXED);
    String json = "";
    List<String> tweetList = new ArrayList<String>();

    try {
        result = twitter.search(query);
    } catch (TwitterException e) {
        System.err.println("Caught 'twitterSearch' IOException: " + e.getMessage());
    }

    String tweetInfo = "";
    for (Status status : result.getTweets()) {
        tweetInfo = "{";
        tweetInfo += "\"id\" : \"" + status.getId() + "\", ";
        tweetInfo += "\"avatar\" : \"" + status.getUser().getProfileImageURL() + "\", ";
        tweetInfo += "\"tweetedOn\" : \"" + status.getCreatedAt() + "\", ";
        tweetInfo += "\"tweetedOnParsed\" : \"" + status.getCreatedAt().getTime() + "\", ";
        tweetInfo += "\"screenname\" : \"" + status.getUser().getScreenName() + "\", ";
        tweetInfo += "\"status\" : \""
                + StringEscapeUtils.escapeHtml(status.getText().replaceAll("(\\r|\\n)", "")) + "\", ";
        tweetInfo += "\"truncated\" : \"" + (status.isTruncated() ? "true" : "false") + "\",";
        tweetInfo += "\"retweeted\" : \"" + (status.isRetweet() ? "true" : "false") + "\"";
        tweetInfo += "}";

        tweetList.add(tweetInfo);
    }

    json = "[" + StringUtils.arrayToDelimitedString(tweetList.toArray(), ",") + "]";

    return new ResponseEntity<String>(json, HttpStatus.OK);
}

From source file:org.n52.twitter.dao.TwitterAbstractDAO.java

License:Open Source License

/**
 * @throws TwitterException - when Twitter service or network is unavailable
 * @throws DecodingException //from   ww w . java  2s .  c om
 */
protected Collection<TwitterMessage> executeApiRequest(Query query) throws TwitterException, DecodingException {
    LinkedList<TwitterMessage> tweets = new LinkedList<>();
    long lastID = Long.MAX_VALUE;
    int requestCount = 0;

    query.setResultType(ResultType.mixed);

    while (tweets.size() < MAX_TWEETS_TO_HARVEST) {
        if (MAX_TWEETS_TO_HARVEST - tweets.size() > TWEETS_TO_LOAD_PER_API_REQUEST) {
            query.setCount(TWEETS_TO_LOAD_PER_API_REQUEST);
        } else {
            query.setCount(MAX_TWEETS_TO_HARVEST - tweets.size());
        }
        try {
            QueryResult result = twitter.search(query);
            requestCount++;
            if (result.getTweets().isEmpty()) {
                break;
            }
            for (Status tweet : result.getTweets()) {
                TwitterMessage message = TwitterMessage.create(tweet);
                if (message != null) {
                    tweets.add(message);
                }
                if (tweet.getId() < lastID) {
                    lastID = tweet.getId();
                }
            }
            query.setMaxId(lastID - 1);
            LOGGER.debug("Progress: " + tweets.size() + "/" + MAX_TWEETS_TO_HARVEST + "(Requests: "
                    + requestCount + ")");
        } catch (TwitterException e) {
            LOGGER.error(e.getErrorMessage(), e);
            throw e;
        }
    }

    LOGGER.debug("Result count :" + tweets.size());

    return tweets;
}

From source file:org.sociotech.communitymashup.source.twitter.TwitterSourceService.java

License:Open Source License

/**
 * Searches for the query defined in the configuration and adds the results.
 *//*from  w  w w .  j a  va 2s.co  m*/
private void search() {
    // get query from configuration
    String query = source.getPropertyValue(TwitterProperties.SEARCH_PROPERTY);

    if (query == null || query.isEmpty()) {
        return;
    }

    QueryResult searchResult = null;

    try {
        Query twitterQuery = new Query(query);
        // set requested number of tweets
        twitterQuery.setCount(getNumberOfSearchTweets());

        // add possible geo location parameter
        addSearchGeoLocation(twitterQuery);

        // if defined set since id
        String sinceId = source.getPropertyValue(TwitterProperties.SEARCH_SINCE_ID_PROPERTY);
        if (sinceId != null && !sinceId.isEmpty()) {
            long sinceIdVal = new Long(sinceId);
            twitterQuery.setSinceId(sinceIdVal);
        }
        searchResult = twitterAPI.search(twitterQuery);
    } catch (TwitterException e) {
        log("Could not search for " + query + "(" + e.getMessage() + ")", LogService.LOG_WARNING);
        return;
    }

    if (searchResult == null) {
        return;
    }

    String sinceId = parseSinceId(searchResult);

    if (sinceId != null) {
        // set it in configuration
        source.addProperty(TwitterProperties.SEARCH_SINCE_ID_PROPERTY, sinceId);
    }

    List<Status> tweets = searchResult.getTweets();

    log("Got " + tweets.size() + " tweets for search " + query, LogService.LOG_DEBUG);

    // add all tweets
    addTweetList(tweets);
}

From source file:Origin.Mypage.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {
    response.setContentType("text/html;charset=UTF-8");
    /* TODO output your page here. You may use following sample code. */
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);/*from   w  ww. ja  v a2 s .c o m*/
    cb.setOAuthConsumerKey(CONSUMER_KEY);
    cb.setOAuthConsumerSecret(CONSUMER_SECRET);
    cb.setOAuthAccessToken(ACCESS_TOKEN);
    cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    User user = twitter.verifyCredentials();
    request.setCharacterEncoding("UTF-8");
    HttpSession hs = request.getSession();
    UserData ud = (UserData) hs.getAttribute("ud");
    String search = ud.getLine() + "?";
    //String search= request.getParameter("searchtweet");
    Query query = new Query();
    query.setCount(100);
    query.setQuery(search);
    QueryResult queryresult = null;
    try {
        queryresult = twitter.search(query);
    } catch (TwitterException e1) {
        e1.printStackTrace();
    }
    ArrayList<String> userID = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        userID.add(tweet.getUser().getScreenName());
    }
    ArrayList<String> profileimg = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        profileimg.add(tweet.getUser().getBiggerProfileImageURL());
    }
    ArrayList<String> username = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        username.add(tweet.getUser().getName() + "<br>" + "@" + tweet.getUser().getScreenName());
    }
    ArrayList<String> usernameURL = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        username.add(tweet.getUser().getURL());
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");

    ArrayList<String> resulttweet = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        resulttweet.add(tweet.getText() + "<br>" + sdf.format(tweet.getCreatedAt()));
    }
    request.setAttribute("search", search);
    request.setAttribute("userID", userID);
    request.setAttribute("profileimg", profileimg);
    request.setAttribute("username", username);
    request.setAttribute("resulttweet", resulttweet);
    request.setAttribute("usernameURL", usernameURL);
    request.getRequestDispatcher("/mypage.jsp").forward(request, response);
}

From source file:Origin.Searchtweet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, TwitterException {
    response.setContentType("text/html;charset=UTF-8");
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true);/* www  .  j a va  2  s . co m*/
    cb.setOAuthConsumerKey(CONSUMER_KEY);
    cb.setOAuthConsumerSecret(CONSUMER_SECRET);
    cb.setOAuthAccessToken(ACCESS_TOKEN);
    cb.setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET);
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();
    User user = twitter.verifyCredentials();
    request.setCharacterEncoding("UTF-8");
    String search = "?" + request.getParameter("searchtweet");
    //String search= request.getParameter("searchtweet");
    Query query = new Query();
    query.setCount(100);
    query.setQuery(search);
    QueryResult queryresult = null;
    try {
        queryresult = twitter.search(query);
    } catch (TwitterException e1) {
        e1.printStackTrace();
    }
    ArrayList<String> userID = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        userID.add(tweet.getUser().getScreenName());
    }
    ArrayList<String> profileimg = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        profileimg.add(tweet.getUser().getBiggerProfileImageURL());
    }
    ArrayList<String> username = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        username.add(tweet.getUser().getName() + "<br>" + "@" + tweet.getUser().getScreenName());
    }
    ArrayList<String> usernameURL = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        username.add(tweet.getUser().getURL());
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");

    ArrayList<String> resulttweet = new ArrayList<>();
    for (Status tweet : queryresult.getTweets()) {
        resulttweet.add(tweet.getText() + "<br>" + sdf.format(tweet.getCreatedAt()));
    }
    request.setAttribute("search", search);
    request.setAttribute("userID", userID);
    request.setAttribute("profileimg", profileimg);
    request.setAttribute("username", username);
    request.setAttribute("resulttweet", resulttweet);
    request.setAttribute("usernameURL", usernameURL);
    request.getRequestDispatcher("/searchtweet.jsp").forward(request, response);
}

From source file:ru.mail.sphere.java_hw5_vasilyev.twitteraccessor.Accessor.java

private static Query buildSearchQuery(String query, Date since, Date until, String lang, int querySize) {
    Query queryObject = new Query(query);
    queryObject.setCount(querySize <= MAX_QUERY_SIZE ? querySize : MAX_QUERY_SIZE);
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    queryObject.setSince(dateFormat.format(since));
    if (until != null) {
        queryObject.setUntil(dateFormat.format(until));
    }//  w  ww .  j a v a2 s  .co  m
    if (lang != null) {
        queryObject.setLang(lang);
    }
    return queryObject;
}

From source file:samples.TwitterSentiment.java

private static String[] get_twits(Date tempdate, String querystr) {

    ArrayList<String> res = new ArrayList<String>();
    try {// w w  w  .j  a v a 2 s.co m
        twitter4j.Twitter twitter = getTwitter();

        Query query = new Query(querystr);
        query.setCount(5000);
        QueryResult result = twitter.search(query);
        for (Status status : result.getTweets()) {
            //System.out.println("@" + status.getUser().getScreenName() + ":" + status.getText());
            res.add("@" + status.getUser().getScreenName() + ":" + status.getText());
        }
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterSentiment.class.getName()).log(Level.SEVERE, null, ex);
    }

    return res.toArray(new String[] {});
}

From source file:search.TwitterSearchBean.java

@Override
public List<Tweet> search(final String keyword) throws TweetsNotFound, TwitterException {
    Query query = new Query(keyword + " -filter:retweets -filter:links -filter:replies -filter:images");
    query.setCount(20);
    query.setLocale("en");
    query.setLang("en");
    QueryResult queryResult = twitter.search(query);
    List<Status> tweetsStatus = queryResult.getTweets();
    if (tweetsStatus.isEmpty())
        throw new TweetsNotFound();
    Collection<Tweet> tweets = mapper.transform(tweetsStatus);
    return (List<Tweet>) tweets;
}