Example usage for twitter4j Query setLocale

List of usage examples for twitter4j Query setLocale

Introduction

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

Prototype

public void setLocale(String locale) 

Source Link

Document

Specify the language of the query you are sending (only ja is currently effective).

Usage

From source file:ch.schrimpf.core.TwitterCrawler.java

License:Open Source License

/**
 * @param queryString describes keywords and filters
 * @return an initialized Query/*from   w  w w.j  av a2s .com*/
 */
private Query initQuery(String queryString) {
    Query query = new Query(queryString);
    try {
        Properties prop = new Properties();
        prop.load(new FileInputStream("easyTwitterCrawler.properties"));
        query.setCount(Integer.parseInt(prop.getProperty("queryLimit")));
        query.setLocale(prop.getProperty("locale"));
        query.setLang(prop.getProperty("lang"));
        GeoLocation location = new GeoLocation(Double.parseDouble(prop.getProperty("latitude")),
                Double.parseDouble(prop.getProperty("longitude")));
        double radius = Double.parseDouble(prop.getProperty("radius"));
        query.setGeoCode(location, radius, Query.KILOMETERS);
    } catch (IOException e) {
        // Properties could not be load
        query.setCount(DEFAULT_QUERY_LIMIT);
        query.setLocale(DEFAULT_LOCALE);
        query.setLang(DEFAULT_LANG);
        query.setGeoCode(DEFAULT_GEO_LOCATION, DEFAULT_RADIUS, Query.KILOMETERS);
    }
    return query;
}

From source file:es.portizsan.twitrector.tasks.TweetSearchTask.java

License:Open Source License

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
    long before = System.currentTimeMillis() - (1000 * 60 * 15);
    try {/*from   w w w . ja v  a2  s . co m*/
        List<Twitrector> trl = new TwitrectorService().getTwitrectors();
        if (trl == null || trl.isEmpty()) {
            logger.log(Level.WARNING, "No Twitrectors found!!!!!");
            return;
        }
        for (Twitrector tr : trl) {
            logger.info("Searching for :" + tr.getQuery());
            String search = tr.getQuery();
            Twitter twitter = new TwitterService().getTwitterInstance();
            Query query = new Query(search);
            query.setLocale("es");
            query.setCount(100);
            if (tr.getLocation() != null) {
                GeoLocation location = new GeoLocation(tr.getLocation().getLatitude(),
                        tr.getLocation().getLongitude());
                Unit unit = Unit.valueOf(tr.getLocation().getUnit().name());
                query.setGeoCode(location, tr.getLocation().getRadius(), unit);
            }
            QueryResult result;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    if (tweet.getCreatedAt().getTime() < before)
                        continue;
                    Queue queue = QueueFactory.getQueue("default");
                    queue.add(TaskOptions.Builder.withUrl("/tasks/tweetReply")
                            .param("statusId", String.valueOf(tweet.getId()))
                            .param("message", "@" + tweet.getUser().getScreenName() + " "
                                    + String.valueOf(tr.getResponse())));

                    logger.info("@" + tweet.getUser().getScreenName() + " - " + tweet.getText());
                }
            } while ((query = result.nextQuery()) != null);
        }
    } catch (TwitterException te) {
        logger.log(Level.WARNING, "Failed to search tweets: ", te);
    }
}

From source file:mashup.MashTweetManager.java

public static ArrayList<String> getTweets(String topic) throws IOException {

    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true).setOAuthAccessToken(Common.AccessToken)
            .setOAuthAccessTokenSecret(Common.AccessTokenSecret).setOAuthConsumerKey(Common.ConsumerKey)
            .setOAuthConsumerSecret(Common.ConsumerSecret);

    TwitterFactory tf = new TwitterFactory(cb.build());
    Twitter twitter = tf.getInstance();//from w ww  .  j  a  v  a  2  s.c o m

    //Twitter twitter = new TwitterFactory().getInstance();

    //  twitter.setOAuthAccessToken(null);

    ArrayList<String> tweetList = new ArrayList<>();

    try {
        Query query = new Query(topic.toLowerCase().trim());

        query.setCount(100);
        query.setLocale("en");
        query.setLang("en");

        QueryResult result = null;

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

            for (Status tweet : tweets) {
                String data = tweet.getText().replaceAll("[^\\p{L}\\p{Z}]", "");

                HinghlishStopWords.removeStopWords(data.trim());
                // Remove Special... Characters 
                // Remove stop words 
                tweetList.add(tweet.getText().replaceAll("[^\\p{L}\\p{Z}]", ""));

            }

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

From source file:org.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Returns tweets that match a specified query.
 * <p/>/*from   w  w w. j  av  a2  s  .  co  m*/
 * This method calls http://search.twitter.com/search.json
 * <p/>
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:search}
 *
 * @param query The search query.
 * @param lang Restricts tweets to the given language, given by an <a href="http://en.wikipedia.org/wiki/ISO_639-1">ISO 639-1 code</a>
 * @param locale Specify the language of the query you are sending (only ja is currently effective). This is intended for language-specific clients and the default should work in the majority of cases.
 * @param maxId If specified, returns tweets with status ids less than the given id
 * @param since If specified, returns tweets since the given date. Date should be formatted as YYYY-MM-DD
 * @param sinceId Returns tweets with status ids greater than the given id.
 * @param geocode A {@link String} containing the latitude and longitude separated by ','. Used to get the tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile
 * @param radius The radius to be used in the geocode -ONLY VALID IF A GEOCODE IS GIVEN-
 * @param unit The unit of measurement of the given radius. Can be 'mi' or 'km'. Miles by default.
 * @param until If specified, returns tweets with generated before the given date. Date should be formatted as YYYY-MM-DD
 * @param resultType If specified, returns tweets included popular or real time or both in the responce. Both by default. Can be 'mixed', 'popular' or 'recent'.
 * @return the {@link QueryResult}
 * @throws TwitterException when Twitter service or network is unavailable
 */
@Processor
public QueryResult search(String query, @Optional String lang, @Optional String locale, @Optional Long maxId,
        @Optional String since, @Optional Long sinceId, @Optional String geocode, @Optional String radius,
        @Default(value = Query.MILES) @Optional String unit, @Optional String until,
        @Optional String resultType) throws TwitterException {
    final Query q = new Query(query);

    if (lang != null) {
        q.setLang(lang);
    }
    if (locale != null) {
        q.setLocale(locale);
    }
    if (maxId != null && maxId.longValue() != 0) {
        q.setMaxId(maxId.longValue());
    }

    if (since != null) {
        q.setSince(since);
    }
    if (sinceId != null && sinceId.longValue() != 0) {
        q.setSinceId(sinceId.longValue());
    }
    if (geocode != null) {
        final String[] geocodeSplit = StringUtils.split(geocode, ',');
        final double latitude = Double.parseDouble(StringUtils.replace(geocodeSplit[0], " ", ""));
        final double longitude = Double.parseDouble(StringUtils.replace(geocodeSplit[1], " ", ""));
        q.setGeoCode(new GeoLocation(latitude, longitude), Double.parseDouble(radius), unit);
    }
    if (until != null) {
        q.setUntil(until);
    }
    if (resultType != null) {
        q.setResultType(resultType);
    }
    return twitter.search(q);
}

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 a 2  s  .  c o m*/
    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: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);//from  ww  w.j av  a  2  s .  com
    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;
}