Example usage for twitter4j Twitter search

List of usage examples for twitter4j Twitter search

Introduction

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

Prototype

QueryResult search(Query query) throws TwitterException;

Source Link

Document

Returns tweets that match a specified query.

Usage

From source file:org.mixare.utils.TwitterClient.java

License:Open Source License

/**
 * Query the twitter search API using oAuth 2.0
 * @return//  w ww.  j av a2  s  . com
 */
public static String queryData() {
    ConfigurationBuilder cb = new ConfigurationBuilder(); //to be configured in a properties...
    cb.setDebugEnabled(true).setOAuthConsumerKey("mt10dv6tTKacqlm14lw5w")
            .setOAuthConsumerSecret("4kRV1E1XIU3kj4JQj2R5LE1yct0RRaRl9sB5PpPrB0")
            .setOAuthAccessToken("390019380-IQ5VdvUKvxY9JOsTToEU8ElCabebc76H9X2g3QX4")
            .setOAuthAccessTokenSecret("ghJn4LTfDr7uHUCsbt6ycmpeVTwwpa3hZnXyEjyZvs");
    cb.setJSONStoreEnabled(true);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();

    Query query = new Query();
    query = query.geoCode(new GeoLocation(lat, lon), rad, Query.KILOMETERS);

    String jsonArrayAsString = "{\"results\":[";//start
    try {
        QueryResult result = twitter.search(query);
        int size = 0;
        for (Status status : result.getTweets()) {
            {
                if (status.getGeoLocation() != null) {
                    String jsonSingleObject = DataObjectFactory.getRawJSON(status);
                    if (size == 0)
                        jsonArrayAsString += jsonSingleObject;
                    else
                        jsonArrayAsString += "," + jsonSingleObject;
                    size++;
                }
            }
        }
        jsonArrayAsString += "]}";//close array
        return jsonArrayAsString;
    } catch (Exception e) {
        Log.e(Config.TAG, "Error querying twitter data :" + e);
        e.printStackTrace();
    }
    return null;
}

From source file:org.primefaces.examples.mobile.TwitterView.java

License:Open Source License

public void search() {
    try {/*w w w  .  j  a  v  a 2 s  .c  om*/
        Twitter twitter = TwitterFactory.getSingleton();
        Query query = new Query(keyword);
        tweets = twitter.search(query).getTweets();
    } catch (TwitterException exception) {
        FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "Please try again");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        RequestContext.getCurrentInstance().update("main:messages");
    }
}

From source file:org.rhq.plugins.twitter.FeedComponent.java

License:Open Source License

/**
 * Gather measurement data/*from  www . j  a  v a  2 s .  c  o  m*/
 *  @see org.rhq.core.pluginapi.measurement.MeasurementFacet#getValues(org.rhq.core.domain.measurement.MeasurementReport, java.util.Set)
 */
public void getValues(MeasurementReport report, Set<MeasurementScheduleRequest> metrics) throws Exception {

    for (MeasurementScheduleRequest req : metrics) {
        if (req.getName().equals("tweetCount")) {
            Twitter twitter = tFactory.getInstance();
            Paging paging = new Paging();

            MeasurementDataNumeric res;
            if (isSearch) {
                Query q = new Query(keyword);
                q.setSinceId(lastId);
                if (lastId == NOT_YET_SET)
                    q.setRpp(1);
                else
                    q.setRpp(20);
                QueryResult qr = twitter.search(q);
                List<Tweet> tweets = qr.getTweets();
                res = new MeasurementDataNumeric(req, (double) tweets.size());

                eventPoller.addTweets(tweets);
                if (tweets.size() > 0)
                    lastId = tweets.get(0).getId();
            } else {
                List<Status> statuses;
                if (lastId == NOT_YET_SET) {
                    paging.setCount(1);
                } else {
                    paging.setCount(100);
                }
                paging.setSinceId(lastId);
                statuses = twitter.getUserTimeline(keyword, paging);
                res = new MeasurementDataNumeric(req, (double) statuses.size());

                eventPoller.addStatuses(statuses);
                if (statuses.size() > 0)
                    lastId = statuses.get(0).getId();

            }
            report.addData(res);
        }
    }
}

From source file:org.richfaces.examples.tweetstream.dataserver.source.TwitterSourceLocal.java

License:Open Source License

@Override
public void fetchContent() {
    //Check if updating content is needed
    //If not skip because this can be called on every page load
    System.out.println("&&&&&&&&&&& fetchContent\n\n\n\n\n");
    if (false) {//from  w  ww. j a  v a2 s . c  o  m
        //      if (performSearch())
        {
            twitterAggregate = new TwitterAggregate();

            Twitter twitter = new TwitterFactory().getInstance();
            List<twitter4j.Tweet> t4jTweets = null;
            try {
                Query query = new Query(TRACK);
                QueryResult result = twitter.search(query);
                t4jTweets = result.getTweets();
                for (twitter4j.Tweet t4jTweet : t4jTweets) {
                    log.info("@" + t4jTweet.getFromUser() + " - " + t4jTweet.getText());

                    //Create a local tweet object from the t4j
                    Tweet tweet = new Tweet();
                    tweet.setText(t4jTweet.getText());
                    tweet.setId(t4jTweet.getFromUserId());
                    tweet.setProfileImageUrl(t4jTweet.getProfileImageUrl());
                    tweet.setScreenName(t4jTweet.getFromUser());
                    tweet.setHashTags(TwitterAggregateUtil.pullHashtags(t4jTweet.getText()));

                    twitterAggregate = TwitterAggregateUtil.updateTwitterAggregate(tweet, twitterAggregate);
                }
            } catch (TwitterException te) {
                te.printStackTrace();
                log.info("Failed to search tweets: " + te.getMessage());
            }
        }
    }

}

From source file:org.todoke.countsearch.Main.java

License:Apache License

static int search(String term, String date) {
    Callback callback = new Callback(new String[] { term });
    Twitter twitter = new TwitterFactory().getInstance();
    int count = 0;
    try {//  www. ja  v a 2  s .c  o m
        int page = 1;
        List<Tweet> tweets;
        do {
            Query query = new Query(term);
            query.rpp(100);
            query.until(date);
            query.setPage(page);
            QueryResult qs = twitter.search(query);
            tweets = qs.getTweets();
            boolean outOfRange = false;
            for (Tweet tweet : tweets) {

                try {
                    if (tweet.getCreatedAt().after(format.parse(date))) {
                        callback.increment(tweet.getText(), tweet.getCreatedAt());
                        count++;
                    } else {
                        //                        System.out.println(tweet.getCreatedAt());
                        outOfRange = true;
                    }
                } catch (ParseException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
            }
            if (outOfRange) {
                break;
            }
            page++;
        } while (tweets.size() != 0);
    } catch (TwitterException e) {
        e.printStackTrace();
        //            System.exit(-1);
    }
    return count;
}

From source file:org.xmlsh.twitter.search.java

License:BSD License

@Override
public int run(List<XValue> args) throws Exception {

    Options opts = new Options(sCOMMON_OPTS
            + ",q=query:,geo=geocode:,lang:,locale:,t=result_type:,until:,since_id:,max_id:,include_entities:,sanitize",
            SerializeOpts.getOptionDefs());
    opts.parse(args);/*from   w w w  . j  av a2  s .c om*/
    mSerializeOpts = this.getSerializeOpts(opts);
    final boolean bSanitize = opts.hasOpt("sanitize");

    args = opts.getRemainingArgs();

    try {

        Twitter twitter = new TwitterFactory().getInstance();
        Query query = new Query();

        if (opts.hasOpt("query"))
            query.setQuery(opts.getOptStringRequired("query"));

        if (opts.hasOpt("lang"))
            query.setLang(opts.getOptStringRequired("lang"));

        if (opts.hasOpt("locale"))
            query.setLocale(opts.getOptStringRequired("locale"));

        if (opts.hasOpt("result_type"))
            query.setResultType(opts.getOptStringRequired("result_type"));

        if (opts.hasOpt("until"))
            query.setUntil(opts.getOptStringRequired("until"));

        if (opts.hasOpt("since_id"))
            query.setSinceId(opts.getOptValue("since_id").toLong());
        if (opts.hasOpt("since"))
            query.setUntil(opts.getOptStringRequired("since"));

        if (opts.hasOpt("max_id"))
            query.setSinceId(opts.getOptValue("max_id").toLong());

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

        OutputPort out = this.getStdout();
        mWriter = new TwitterWriter(out.asXMLStreamWriter(mSerializeOpts), bSanitize);

        mWriter.startDocument();
        mWriter.startElement("twitter");
        mWriter.writeDefaultNamespace();

        for (Status t : tweets)
            mWriter.write(t);

        mWriter.endElement();
        mWriter.endDocument();
        mWriter.closeWriter();

        out.release();
    } finally {

    }
    return 0;

}

From source file:org.zoneproject.extractor.twitterreader.TwitterApi.java

License:Open Source License

public static ArrayList<Item> getFluxFromSearch(String search, String sourceUri) {
    ArrayList<Item> result = new ArrayList<Item>();
    try {//from w w  w  .ja  va  2  s. c om

        Twitter twitter = new TwitterFactory().getInstance();
        twitter.setOAuthConsumer(Config.getVar("Twitter-OAuth-customer"),
                Config.getVar("Twitter-OAuth-customerKey"));
        twitter.setOAuthAccessToken(new AccessToken(Config.getVar("Twitter-OAuth-access"),
                Config.getVar("Twitter-OAuth-accessKey")));

        Query query = new Query(search);
        QueryResult items = twitter.search(query);
        for (Status r : items.getTweets()) {
            result.add(TwitterApi.getItemFromStatus(r, sourceUri));
        }

        return result;
    } catch (TwitterException ex) {
        Logger.getLogger(TwitterApi.class.getName()).log(Level.WARNING, null, ex);
        return result;
    }
}

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 w w  .  ja  va2 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);//from   ww w . jav  a2s .c om
    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

public static Collection<Tweet> search(String query, Date since, Date until, String lang, int querySize) {
    Twitter twitter = new TwitterFactory(config).getInstance();
    Collection<Tweet> methodResult = new ArrayList<>();
    try {/*  w w w  .  j av a 2s .co m*/
        Accessor.meetRateLimits(twitter);
        Query queryObject = Accessor.buildSearchQuery(query, since, until, lang, querySize);
        QueryResult result = twitter.search(queryObject);
        List<Status> tweets = result.getTweets();
        for (Status tweet : tweets) {
            methodResult.add(Accessor.buildTweetFromStatus(tweet));
        }
    } catch (TwitterException te) {
        System.err.println(String.format("TwitterException occured: %s", te.getMessage()));
        System.err.println(Arrays.toString(te.getStackTrace()));
        System.err.println(Program.EXTERMINATUS);
    }
    return methodResult;
}