Example usage for twitter4j Query setLang

List of usage examples for twitter4j Query setLang

Introduction

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

Prototype

public void setLang(String lang) 

Source Link

Document

restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>

Usage

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);
    if (until.length() > 0)
        q.setUntil(until);/*from ww  w .ja  va 2 s  .  c  o m*/
    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: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.  ja  v a  2 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: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));
    }//from   ww w .j  av  a  2  s  . com
    if (lang != null) {
        queryObject.setLang(lang);
    }
    return queryObject;
}

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);//w w w.j av a  2s  .co  m
    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;
}

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);/* ww w .  java 2  s .c o 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;
}

From source file:t.twitter.TTwitterModule.java

License:Open Source License

@Kroll.method
public void search(HashMap args) {
    KrollDict arg = new KrollDict(args);
    Query query = new Query(arg.getString("query"));
    query.setLang(arg.optString("lang", ""));
    query.setCount(arg.optInt("count", 20));
    if (arg.optString("since", "") != "") {
        query.setSince(arg.getString("since"));
    }// w w w.  j  a  v a  2s .com
    desc = arg.optBoolean("descending", false);
    success = (KrollFunction) arg.get("success");
    lastID = Long.parseLong(arg.optString("lastID", "-1"));
    twitter.search(query);
}

From source file:tweetcrawling.TweetCrawler.java

public void getTweets(TwitterConfiguration tc_) throws IOException, InterruptedException {

    try {/*www. j  av a 2s.  c  o  m*/

        for (String query_ : Queries) {

            // Ngambil tweet dari tiap page lalu disimpan di Statuses
            int maxTweetCrawled = 3240; // This is the number of the latest tweets that we can crawl, specified by Twitter

            Query query = new Query(query_);
            query.setLang("id");
            QueryResult result;
            do {
                rateLimitHandler(tc_, "/search/tweets"); // Check rate limit first
                //System.out.println("kanya sini");
                result = tc_.getTwitter().search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    ArrayList<String> ValToWrite = getValueToWrite(tweet);
                    writeValue(ValToWrite, OutputFile);
                    System.out.println(
                            "@" + tweet.getUser().getScreenName() + " - " + tweet.getText().replace("\n", " "));
                }
                addStatuses(tweets);

            } while ((query = result.nextQuery()) != null);

            //printTweets(OutputFile); // Printing out crawling result per page of this keywords
            //emptyStatuses(); // Empty out the current attribute Statuses so that it can be used for other keywords    

        }

    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to get timeline: " + te.getMessage());
        if (te.exceededRateLimitation()) {
            System.out.println("Rate limit status: " + te.getRateLimitStatus());
        }
        System.exit(-1);
    }

}

From source file:tweetdownloader.cnr_stable.version.TweetDownload.java

/**
 * this method return an ArrayList of dataOfTweets
 * @param allMyTweets//from  w w w. j a  v  a 2  s .  co m
 * @return allMyTweet
 */
public ArrayList<dataOfTweet> downloadMyTweet(ArrayList<dataOfTweet> allMyTweets) {
    {
        try {
            Map<String, RateLimitStatus> rateLimitStatus = twitter.getRateLimitStatus("search");
            RateLimitStatus searchTweetsRateLimit = rateLimitStatus.get("/search/tweets");
            for (int queryNumber = 0; queryNumber < MAX_QUERIES; queryNumber++) {
                dataOfTweet tweet = new dataOfTweet();

                //System.out.printf("\n\n!!! Starting loop %d\n\n", queryNumber);
                if (searchTweetsRateLimit.getRemaining() == 0) {
                    try {
                        //System.out.printf("!!! Sleeping for %d seconds due to rate limits\n", searchTweetsRateLimit.getSecondsUntilReset());
                        Thread.sleep((searchTweetsRateLimit.getSecondsUntilReset() + 2) * 1000l);
                    } catch (InterruptedException ex) {
                        java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE,
                                null, ex);
                    }
                }
                Query q = new Query(SEARCH_TERM);
                q.setCount(TWEETS_PER_QUERY);
                q.setLang("it");

                if (maxID != -1) {
                    q.setMaxId(maxID - 1);
                }

                QueryResult r = twitter.search(q);

                if (r.getTweets().isEmpty()) {
                    break;
                }
                for (Status s : r.getTweets()) {

                    totalTweets++;
                    if (maxID == -1 || s.getId() < maxID) {
                        maxID = s.getId();
                    }
                    if (s.isRetweeted() == false) {

                        tweet.setUsername(s.getUser().getScreenName());
                        tweet.setCreatedAt(s.getCreatedAt().toString());
                        tweet.setTweetText(s.getText());

                        if (s.getGeoLocation() != null) {
                            tweet.setLat(s.getGeoLocation().getLatitude());
                            tweet.setLongi(s.getGeoLocation().getLongitude());
                        }
                    }
                }
                allMyTweets.add(tweet);
            }
        } catch (TwitterException ex) {
            java.util.logging.Logger.getLogger(TweetDownload.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return allMyTweets;
}

From source file:tweets_stock_price_prediction.TweetsManager.java

public ArrayList<String> getTweets(String topic, String fromDate, String toDate) {

    //Twitter twitter = new TwitterFactory().getInstance();
    System.out.println("*** TWITTER QUERY: " + topic);
    ArrayList<String> tweetList = new ArrayList<String>();
    try {/*from   www .j  a v  a  2  s . c  o m*/
        Query query = new Query(topic);
        query.setLang("en");
        //query.setCount(count);
        query.setSince(fromDate);
        query.setUntil(toDate);
        QueryResult result;
        do {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
                //System.out.print("LANGUAGE " + tweet.getLang() + "\n\n");
                //if (tweet.getLang().equals("en")) {
                tweetList.add(tweet.getText());
                //}
            }
        } while ((query = result.nextQuery()) != null);
    } catch (TwitterException te) {
        te.printStackTrace();
        System.out.println("Failed to search tweets: " + te.getMessage());
    }

    System.out.println("************ TWEET LIST: " + tweetList.size());
    return tweetList;
}

From source file:twitterrest.SearchTweet.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    //?//w  w  w  .  j  a v  a 2 s.  c o  m
    Configuration configuration = new ConfigurationBuilder().setOAuthConsumerKey(CONSUMER_KEY)
            .setOAuthConsumerSecret(CONSUMER_SECRET).setOAuthAccessToken(ACCESS_TOKEN)
            .setOAuthAccessTokenSecret(ACCESS_TOKEN_SECRET).build();
    Twitter twitter = new TwitterFactory(configuration).getInstance();
    Query query = new Query();
    try {
        File file = new File("./file/tweets.txt");
        PrintWriter pw;
        //???
        pw = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));

        // ???
        query.setQuery("?");
        query.setLang("ja");
        // 1????Tweet?100?
        query.setCount(100);
        //?????????
        //query.setSince("2013-06-13");
        //query.setUntil("2013-06-17");

        // 150015
        for (int i = 1; i <= 15; i++) {
            // 
            QueryResult result = twitter.search(query);
            System.out.println(": " + result.getTweets().size());
            System.out.println(" : " + new Integer(i).toString());

            // ???
            for (Status tweet : result.getTweets()) {
                // 
                String str = tweet.getText();
                System.out.println(str);
                //
                System.out.println(tweet.getUser());
                //
                System.out.println(tweet.getCreatedAt());
                // ??URL?   
                StringTokenizer sta = new StringTokenizer(str, " ");
                //?
                while (sta.hasMoreTokens()) {
                    String wk = sta.nextToken();
                    if (wk.indexOf("#") == -1 && wk.indexOf("http") == -1 && wk.indexOf("RT") == -1
                            && wk.indexOf("@") == -1) {
                        pw.println(wk);
                    }
                }
                String u = tweet.getUser().getName();
                pw.println(u);
            }
            if (result.hasNext()) {
                query = result.nextQuery();
            } else {
                break;
            }
        }
        pw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}