Example usage for twitter4j Query count

List of usage examples for twitter4j Query count

Introduction

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

Prototype

int count

To view the source code for twitter4j Query count.

Click Source Link

Usage

From source file:co.uk.socialticker.ticker.TickerActivity.java

License:Open Source License

/**
 * Test code to try and retrieve some data from twitter in a search!
 * @throws TwitterException /*from w  w w  .  j  a va2  s .c o  m*/
 * */
public JSONArray doSearch(View v) throws TwitterException {

    if (mApiClient != null || debugOn) {
        // The factory instance is re-useable and thread safe.
        //get the hashtag - check to make sure if returned value is set to something with a length
        JSONArray jsA = new JSONArray();
        String qHash = p.getString(KEY_CAST_HASHTAG, "");
        Log.d(TAG, "Hash to search: " + qHash);
        if (qHash.length() == 0) {
            Toast.makeText(this, "The hashtag looks like it is not setup. May want to fix that",
                    Toast.LENGTH_LONG).show();
        } else {
            try {
                ConfigurationBuilder builder = new ConfigurationBuilder();
                builder.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
                builder.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);

                // Access Token 
                String access_token = mSharedPreferences.getString(PREF_KEY_OAUTH_TOKEN, "");
                // Access Token Secret
                String access_token_secret = mSharedPreferences.getString(PREF_KEY_OAUTH_SECRET, "");

                AccessToken accessToken = new AccessToken(access_token, access_token_secret);
                Twitter twitter = new TwitterFactory(builder.build()).getInstance(accessToken);
                //Query query = new Query("#MOTD2014");
                Query query = new Query(qHash);
                query.count(TWEET_COUNT);
                QueryResult result = twitter.search(query);
                for (twitter4j.Status status : result.getTweets()) {

                    MediaEntity[] me = status.getMediaEntities();
                    String meUrl = "";
                    if (me.length > 0) {
                        Log.d(TAG, "me[0] : " + me[0].getMediaURL());
                        //meUrl = me[0].getDisplayURL(); //sjort URl = useless.
                        meUrl = me[0].getMediaURL();
                    }

                    JSONObject jso = tweetJSON(status.getUser().getScreenName(), status.getUser().getName()
                    //                        , status.getUser().getOriginalProfileImageURL() //Whatever the size was it was uploaded in
                    //                        , status.getUser().getProfileImageURL() // 48x48
                            , status.getUser().getBiggerProfileImageURL() // 73x73
                            , status.getText(), status.getCreatedAt().toString(), status.getFavoriteCount(),
                            status.getRetweetCount(), meUrl);
                    jsA.put(jso);
                }

            } catch (TwitterException e) {
                // Error in updating status
                Log.d("Twitter Search Error", e.getMessage());
                Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }
        ;
        return jsA;
    } else {
        Toast.makeText(this, "You do not seem to be connected to a cast device...", Toast.LENGTH_LONG).show();
        return null;
    }
}

From source file:com.example.leonid.twitterreader.Twitter.TwitterGetTweets.java

License:Apache License

@Override
protected List<CreateTweet> doInBackground(String... params) {
    mTweetsInfo = new ArrayList<>();
    List<String> texts = new ArrayList<>();
    List<String> titles = new ArrayList<>();
    List<String> images = new ArrayList<>();
    List<String> date = new ArrayList<>();
    if (!isCancelled()) {
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(CONSUMER_KEY).setOAuthConsumerSecret(CONSUMER_SECRET)
                .setOAuthAccessToken(ACCESS_KEY).setOAuthAccessTokenSecret(ACCESS_SECRET);
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();
        //query search result
        Query query = new Query(params[0]);
        //how much tweets need to be displayed(max 200)
        query.count(200);
        try {// w  w w  .  j a v a2  s .  c  o m
            mResult = twitter.search(query);
            for (twitter4j.Status status : mResult.getTweets()) {
                if (!isCancelled()) {
                    texts.add(status.getText());
                    titles.add(status.getUser().getName());
                    images.add(status.getUser().getBiggerProfileImageURL());
                    String cleanDate = status.getCreatedAt().toString();
                    date.add(cleanDate.substring(0, cleanDate.length() - 15) + " "
                            + cleanDate.substring(cleanDate.length() - 4));
                }
            }
        } catch (TwitterException e) {
            Log.e("exeption", e.toString());
        }
        //loop teuth results and create array list for list view
        for (int i = 0; i < texts.size(); i++) {
            mTweetsInfo.add(new CreateTweet(titles.get(i), images.get(i), texts.get(i), date.get(i)));
        }

    }
    return mTweetsInfo;
}

From source file:com.learnncode.twitter.async.HashtagTweetFetchAsyncTask.java

License:Apache License

@Override
protected List<twitter4j.Status> doInBackground(Object... params) {

    List<twitter4j.Status> list = new ArrayList<twitter4j.Status>();
    if (AppUtilities.IsNetworkAvailable(mContext)) {

        try {//from   w w  w  .j  a  v a  2  s  .  c  o  m
            Twitter twitter;
            if (AppSettings.isTwitterAuthenticationDone(mContext)) {
                twitter = TwitterHelper.getTwitterInstance(mContext);

            } else {
                twitter = TwitterHelper.getTwitterInstanceWithoutAuthentication(mContext);
            }
            Query query = new Query(hashtag);
            query.count(10);
            if (lastSeenId != 0) {
                query.setMaxId(lastSeenId);
            }
            QueryResult qr = twitter.search(query);
            List<twitter4j.Status> qrTweets = qr.getTweets();

            for (twitter4j.Status t : qrTweets) {
                list.add(t);
            }

        } catch (Exception e) {
            System.err.println();
        }
    }
    if (lastSeenId != 0) {
        iHashTagList.setTweetList(list, true);
    } else {
        iHashTagList.setTweetList(list, false);
    }

    return list;
}

From source file:com.thesmartweb.swebrank.TwitterAnalysis.java

License:Apache License

/**
 * Method to get tweets regarding a string 
 * @param query_string the string to search for
 * @param config_path the directory with the twitter api key
 * @return the tweets in a string/* w  w w  . ja  v  a  2s  . c  o m*/
 */
public String perform(String query_string, String config_path) {
    try {
        List<String> twitterkeys = GetKeys(config_path);
        //configuration builder in order to set the keys of twitter
        ConfigurationBuilder cb = new ConfigurationBuilder();
        String consumerkey = twitterkeys.get(0);
        String consumersecret = twitterkeys.get(1);
        String accesstoken = twitterkeys.get(2);
        String accesstokensecret = twitterkeys.get(3);
        cb.setDebugEnabled(true).setOAuthConsumerKey(consumerkey).setOAuthConsumerSecret(consumersecret)
                .setOAuthAccessToken(accesstoken).setOAuthAccessTokenSecret(accesstokensecret);
        TwitterFactory tf = new TwitterFactory(cb.build());
        AccessToken acc = new AccessToken(accesstoken, accesstokensecret);

        Twitter twitter = tf.getInstance(acc);

        //query the twitter
        Query query = new Query(query_string);
        int rpp = 100;
        query.count(rpp);
        query.setQuery(query_string);

        //----------get the tweets------------
        QueryResult result = twitter.search(query);
        List<Status> tweets = result.getTweets();

        RateLimitStatus rls = result.getRateLimitStatus();

        String tweet_txt = "";
        for (Status tweet : tweets) {
            tweet_txt = tweet_txt + " " + tweet.getText();
        }
        DataManipulation txtpro = new DataManipulation();
        Stopwords st = new Stopwords();
        tweet_txt = txtpro.removeChars(tweet_txt);
        tweet_txt = st.stop(tweet_txt);
        tweet_txt = txtpro.removeChars(tweet_txt);
        return tweet_txt;
    } catch (TwitterException ex) {
        String tweet_txt = "";
        Logger.getLogger(TwitterAnalysis.class.getName()).log(Level.SEVERE, null, ex);
        return tweet_txt = "fail";
    }
}

From source file:controllers.modules.CorpusModule.java

License:Open Source License

public static Result update(UUID corpus) {
    OpinionCorpus corpusObj = null;/*from w  w  w . j a  va  2 s.  co  m*/
    if (corpus != null) {
        corpusObj = fetchResource(corpus, OpinionCorpus.class);
    }
    OpinionCorpusFactory corpusFactory = null;

    MultipartFormData formData = request().body().asMultipartFormData();
    if (formData != null) {
        // if we have a multi-part form with a file.
        if (formData.getFiles() != null) {
            // get either the file named "file" or the first one.
            FilePart filePart = ObjectUtils.defaultIfNull(formData.getFile("file"),
                    Iterables.getFirst(formData.getFiles(), null));
            if (filePart != null) {
                corpusFactory = (OpinionCorpusFactory) new OpinionCorpusFactory().setFile(filePart.getFile())
                        .setFormat(FilenameUtils.getExtension(filePart.getFilename()));
            }
        }
    } else {
        // otherwise try as a json body.
        JsonNode json = request().body().asJson();
        if (json != null) {
            OpinionCorpusFactoryModel optionsVM = Json.fromJson(json, OpinionCorpusFactoryModel.class);
            if (optionsVM != null) {
                corpusFactory = optionsVM.toFactory();
            } else {
                throw new IllegalArgumentException();
            }

            if (optionsVM.grabbers != null) {
                if (optionsVM.grabbers.twitter != null) {
                    if (StringUtils.isNotBlank(optionsVM.grabbers.twitter.query)) {
                        TwitterFactory tFactory = new TwitterFactory();
                        Twitter twitter = tFactory.getInstance();
                        twitter.setOAuthConsumer(
                                Play.application().configuration().getString("twitter4j.oauth.consumerKey"),
                                Play.application().configuration().getString("twitter4j.oauth.consumerSecret"));
                        twitter.setOAuthAccessToken(new AccessToken(
                                Play.application().configuration().getString("twitter4j.oauth.accessToken"),
                                Play.application().configuration()
                                        .getString("twitter4j.oauth.accessTokenSecret")));

                        Query query = new Query(optionsVM.grabbers.twitter.query);
                        query.count(ObjectUtils.defaultIfNull(optionsVM.grabbers.twitter.limit, 10));
                        query.resultType(Query.RECENT);
                        if (StringUtils.isNotEmpty(corpusFactory.getLanguage())) {
                            query.lang(corpusFactory.getLanguage());
                        } else if (corpusObj != null) {
                            query.lang(corpusObj.getLanguage());
                        }

                        QueryResult qr;
                        try {
                            qr = twitter.search(query);
                        } catch (TwitterException e) {
                            throw new IllegalArgumentException();
                        }

                        StringBuilder tweets = new StringBuilder();
                        for (twitter4j.Status status : qr.getTweets()) {
                            // quote for csv, normalize space, and remove higher unicode characters. 
                            String text = StringEscapeUtils.escapeCsv(StringUtils
                                    .normalizeSpace(status.getText().replaceAll("[^\\u0000-\uFFFF]", "")));
                            tweets.append(text + System.lineSeparator());
                        }

                        corpusFactory.setContent(tweets.toString());
                        corpusFactory.setFormat("txt");
                    }
                }
            }
        } else {
            // if not json, then just create empty.
            corpusFactory = new OpinionCorpusFactory();
        }
    }

    if (corpusFactory == null) {
        throw new IllegalArgumentException();
    }

    if (corpus == null && StringUtils.isEmpty(corpusFactory.getTitle())) {
        corpusFactory.setTitle("Untitled corpus");
    }

    corpusFactory.setOwnerId(SessionedAction.getUsername(ctx())).setExistingId(corpus).setEm(em());

    DocumentCorpusModel corpusVM = null;
    corpusObj = corpusFactory.create();
    if (!em().contains(corpusObj)) {
        em().persist(corpusObj);

        corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
        corpusVM.populateSize(em(), corpusObj);
        return created(corpusVM.asJson());
    }

    for (PersistentObject obj : corpusObj.getDocuments()) {
        if (em().contains(obj)) {
            em().merge(obj);
        } else {
            em().persist(obj);
        }
    }
    em().merge(corpusObj);

    corpusVM = (DocumentCorpusModel) createViewModel(corpusObj);
    corpusVM.populateSize(em(), corpusObj);
    return ok(corpusVM.asJson());
}

From source file:org.botlibre.sense.twitter.Twitter.java

License:Open Source License

/**
 * Learn responses from the tweet search.
 *///from   w ww  .j a  v a2 s.  co m
public void learnSearch(String tweetSearch, int maxSearch, boolean processTweets, boolean processReplies) {
    log("Learning from tweet search", Level.INFO, tweetSearch);
    try {
        Network memory = getBot().memory().newMemory();
        int count = 0;
        this.errors = 0;
        Set<Long> processed = new HashSet<Long>();
        Query query = new Query(tweetSearch);
        query.count(100);
        SearchResource search = getConnection().search();
        QueryResult result = search.search(query);
        List<Status> tweets = result.getTweets();
        if (tweets != null) {
            log("Processing search results", Level.INFO, tweets.size(), tweetSearch);
            for (Status tweet : tweets) {
                if (count > maxSearch) {
                    log("Max search results processed", Level.INFO, maxSearch);
                    break;
                }
                if (!processed.contains(tweet.getId())) {
                    log("Processing search result", Level.INFO, tweet.getUser().getScreenName(), tweetSearch,
                            tweet.getText());
                    processed.add(tweet.getId());
                    learnTweet(tweet, processTweets, processReplies, memory);
                    count++;
                }
            }
            memory.save();
        }
        // Search only returns 7 days, search for users as well.
        TextStream stream = new TextStream(tweetSearch);
        while (!stream.atEnd()) {
            stream.skipToAll("from:", true);
            if (stream.atEnd()) {
                break;
            }
            String user = stream.nextWord();
            String arg[] = new String[1];
            arg[0] = user;
            ResponseList<User> users = getConnection().lookupUsers(arg);
            if (!users.isEmpty()) {
                long id = users.get(0).getId();
                boolean more = true;
                int page = 1;
                while (more) {
                    Paging pageing = new Paging(page);
                    ResponseList<Status> timeline = getConnection().getUserTimeline(id, pageing);
                    if ((timeline == null) || (timeline.size() < 20)) {
                        more = false;
                    }
                    page++;
                    if ((timeline == null) || timeline.isEmpty()) {
                        more = false;
                        break;
                    }
                    log("Processing user timeline", Level.INFO, user, timeline.size());
                    for (int index = timeline.size() - 1; index >= 0; index--) {
                        if (count >= maxSearch) {
                            more = false;
                            break;
                        }
                        Status tweet = timeline.get(index);
                        if (!processed.contains(tweet.getId())) {
                            log("Processing user timeline result", Level.INFO, tweet.getUser().getScreenName(),
                                    tweet.getText());
                            processed.add(tweet.getId());
                            learnTweet(tweet, processTweets, processReplies, memory);
                            count++;
                        }
                    }
                    memory.save();
                }
                if (count >= maxSearch) {
                    log("Max search results processed", Level.INFO, maxSearch);
                    break;
                }
            }
        }
    } catch (Exception exception) {
        log(exception);
    }
}

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

License:Open Source License

public Query[] getSearchQuery() {
    String query = queryTextField.getText();
    String lang = langTextField.getText().trim();
    String until = untilTextField.getText().trim();
    String since = sinceTextField.getText().trim();
    GeoLocation geol = solveGeoLocation();
    double distance = solveDistance();
    ArrayList<Query> queries = new ArrayList();

    Query q = new Query(query);

    if (lang.length() > 0)
        q.setLang(lang);//ww  w  . ja v a  2s  . c o m
    if (until.length() > 0)
        q.setUntil(until);
    if (since.length() > 0)
        q.setSince(since);
    if (geol != null)
        q.setGeoCode(geol, distance, Query.KILOMETERS);

    q.count(100);

    queries.add(q);

    return queries.toArray(new Query[] {});
}

From source file:summarizer.NewApplication.java

private void HashtagSearchButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HashtagSearchButtonActionPerformed
    // TODO add your handling code here:
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthConsumerKey("uEeExq1FHARMvAGTJAY0dGxPh")
            .setOAuthConsumerSecret("jMcofTKFsayd4bpA6HFNlgkMfiveoS3ffRSCy9FCSs9pWYqdAD")
            .setOAuthAccessToken("2443437752-PrbVsDrQCxthX3T7lV3dtHs3FCXFXfBBHsdNrOS")
            .setOAuthAccessTokenSecret("MbauBu7R6vUUKqFD9ogK7VTIfce4nmvewYsgYqBOQ2ZbC");
    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();/*from  ww  w  .j av  a 2s  .  c o m*/

    String hashtag;
    hashtag = HashtagTextField.getText();
    Query query = new Query(hashtag);
    query.count(100);
    if (TwitterComboBox.getSelectedIndex() == 0) {
        query.resultType(Query.ResultType.mixed);
    } else if (TwitterComboBox.getSelectedIndex() == 0) {
        query.resultType(Query.ResultType.recent);
    } else {
        query.resultType(Query.ResultType.popular);
    }
    QueryResult result = null;
    try {
        result = twitter.search(query);
    } catch (TwitterException ex) {
        Logger.getLogger(NewApplication.class.getName()).log(Level.SEVERE, null, ex);
    }
    String alltweets = "", temp = "";

    for (Status status : result.getTweets()) {
        temp = status.getText();
        temp = temp.replaceAll("[\\t\\n\\r]", " ");
        if (!"".equals(temp)) {
            if ("RT".equals(temp.substring(0, 2))) {
                temp = temp.split(":", 2)[1];
            }
            alltweets += (temp + "\n");
        }
    }
    InputTextArea.setText(alltweets);
}

From source file:tweetmining.MiningFunctions.java

/**
 * This method mines data from youw twitter account based on the query string that you pass by
 * parameters./* w w w.j av  a2 s . com*/
 * @param query Query you want to place.
 * @throws FileNotFoundException
 * @throws TwitterException 
 */
public void MineFromQuery(String query) throws FileNotFoundException, TwitterException {
    Query q = new Query(query);
    QueryResult r;
    q.count(100);

    do {
        r = twitter.search(q);
        List<Status> statuses = r.getTweets();
        for (Status st : statuses) {
            GeoLocation loc = st.getGeoLocation();
            if (loc != null) {
                System.out.println("Loc not null");
                Double lat = loc.getLatitude();
                Double lon = loc.getLongitude();
                pw.println(lat.toString() + ";" + lon.toString() + ";" + st.getUser().getName());
            }
        }
        q = r.nextQuery();
    } while (r.hasNext());
}

From source file:TwitterAnalytics.TwitterAPI.java

public void getTweets(List<String> keywords) throws TwitterException {
    statusCache.clear();/*from   www .  ja  v  a  2  s.  c o  m*/

    Query query = makeQuery(keywords);
    query.count(maxQuery);
    QueryResult res = twitter.search(query);
    statusCache = res.getTweets();
}