Example usage for twitter4j Query setGeoCode

List of usage examples for twitter4j Query setGeoCode

Introduction

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

Prototype

public void setGeoCode(GeoLocation location, double radius, Unit unit) 

Source Link

Document

returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile

Usage

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  a v  a  2s .c  o 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.n52.twitter.dao.TwitterSearchDAO.java

License:Open Source License

@Override
public Collection<TwitterMessage> search(double latitude, double longitude, int distanceMeters,
        DateTime fromDate, DateTime toDate) throws TwitterException, DecodingException {
    Query searchQuery = new Query();
    searchQuery.setGeoCode(new GeoLocation(latitude, longitude), distanceMeters / 1000, DEFAULT_UNIT);
    if (toDate != null) {
        searchQuery.setUntil(toDate.toString("YYYY-MM-dd"));
    }/*from  w  w w.  j  a va  2 s .c  o m*/
    if (fromDate != null) {
        searchQuery.setSince(fromDate.toString("YYYY-MM-dd"));
    }
    return executeApiRequest(searchQuery);
}

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

License:Open Source License

@Override
public Collection<TwitterMessage> search(String... tags) throws TwitterException, DecodingException {
    if (tags.length == 0) {
        return Collections.emptyList();
    }//from   www.  ja v a  2s  . c o m
    StringBuffer tagsBuffer = new StringBuffer();
    for (String tag : tags) {
        tag = tag.trim();
        tagsBuffer.append(tag).append(" OR ").append("#").append(tag).append(" OR ");
    }
    tagsBuffer = tagsBuffer.replace(tagsBuffer.length() - 4, tagsBuffer.length(), "");
    LOGGER.debug("Created search string: '{}'", tagsBuffer.toString());
    Query searchQuery = new Query(tagsBuffer.toString());
    // 40074 is circumference of the earth
    // TODO doesn't map the whole
    searchQuery.setGeoCode(new GeoLocation(0.0, 0.0), 40074 / 2, Unit.km);
    return executeApiRequest(searchQuery);
}

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

License:Open Source License

/**
 * Adds geolocation parameters to the given twitter query if they are defined in the
 * configuration.//from   ww  w.j a va 2  s.c  o m
 * 
 * @param twitterQuery Twitter query
 */
private void addSearchGeoLocation(Query twitterQuery) {
    String lat = source.getPropertyValue(TwitterProperties.SEARCH_GEO_LATITUDE_PROPERTY);
    String lon = source.getPropertyValue(TwitterProperties.SEARCH_GEO_LONGITUDE_PROPERTY);

    if (lat == null || lon == null) {
        // no geo location set
        return;
    }

    String radius = source.getPropertyValueElseDefault(TwitterProperties.SEARCH_GEO_RADIUS_PROPERTY,
            TwitterProperties.SEARCH_GEO_RADIUS_DEFAULT);
    String unit = source.getPropertyValueElseDefault(TwitterProperties.SEARCH_GEO_RADIUS_UNIT_PROPERTY,
            TwitterProperties.SEARCH_GEO_RADIUS_UNIT_DEFAULT);

    double latVal = 0.0;
    double lonVal = 0.0;
    double radiusVal = 0.0;

    // try to parse the set properties
    try {
        latVal = new Double(lat);
        lonVal = new Double(lon);
        radiusVal = new Double(radius);
    } catch (Exception e) {
        log("Could not parse configured search geo coordinates. (" + e.getMessage() + ")",
                LogService.LOG_WARNING);
    }

    // add geo location to twitter query
    twitterQuery.setGeoCode(new GeoLocation(latVal, lonVal), radiusVal, unit);
}

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);//from   w w  w .jav a2 s.  co  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:twitterrest.GeoSearch.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    // ?/* w ww  . j av  a 2 s  .  co 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();

    // ?????10kmIP??????      
    GeoLocation geo = new GeoLocation(35.69384, 139.703549);
    query.setGeoCode(geo, 10.0, Query.KILOMETERS);

    // 
    QueryResult result = twitter.search(query);

    // ???Tweet??placegeoLocation??????
    for (Status tweet : result.getTweets()) {
        System.out.println(tweet.getText());
        System.out.println(tweet.getPlace() + " : " + tweet.getGeoLocation());
    }
}

From source file:uk.ac.susx.tag.method51.twitter.params.QueryParams.java

License:Apache License

public Query buildQuery() throws SQLException {
    List<String> keywords = getKeywords();

    if (keywords.size() == 0 && getLocation().size() == 0) {
        throw new RuntimeException("No keywords or locations provided");
    }/*  ww  w.  j  a  va 2  s. c o  m*/

    final String q;

    if (keywords.size() > 1) {
        q = "\"" + StringUtils.join(keywords, "\" OR \"") + "\"";
    } else {
        q = keywords.get(0);
    }

    //LOG.info("Searching keywords: {}", q);
    //LOG.info("Query length: {}", q.length());

    Query query = new Query(q);
    query.setCount(100);
    query.setResultType(Query.RECENT);

    if (getAcceptedLanguages().size() > 0) {
        query.setLang(StringUtils.join(getAcceptedLanguages(), ","));
    }

    if (getUntilId() != null) {
        query.setMaxId(getUntilId());
    }

    if (getSinceId() != null) {
        query.setSinceId(getSinceId());

    } else if (getSinceMaxId()) {
        try (Connection con = dbParams.get().buildConnection()) {
            long maxId = Util.getMaxID(con, getMysqlTweetOutputTable());
            query.setSinceId(maxId);
            LOG.info("Determined {} as max id, searching since that.", maxId);
        }
    }

    if (getSinceId() == null && getSinceDate() != null) {
        long approxSinceId = Util.getMinSnowflakeId(getSinceDate());
        query.setSinceId(approxSinceId);
        LOG.info("Determined min Snowflake ID {}", approxSinceId);
    }

    if (getUntilId() == null && getUntilDate() != null) {
        long approxUntilId = Util.getMaxSnowflakeId(getUntilDate());
        query.setMaxId(approxUntilId);
        LOG.info("Determined max Snowflake ID {}", approxUntilId);
    }

    if (getLocation().size() == 1) {
        try {
            String[] geo = getLocation().get(0).split("\\|");

            query.setGeoCode(new GeoLocation(Double.parseDouble(geo[0]), Double.parseDouble(geo[1])),
                    Double.parseDouble(geo[2]), Query.KILOMETERS);

        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("invalid location param " + getLocation().get(0), e);
        }
    }

    return query;
}

From source file:webServices.RestServiceImpl.java

@GET
@Path("/findTwittsRest")
@Produces({ MediaType.TEXT_PLAIN })/*from  w  w w.  j a v a2s  .  co  m*/
public String twitterSearchRest(@QueryParam("keys") String searchKeys, @QueryParam("sinceId") long sinceId,
        @QueryParam("maxId") long maxId, @QueryParam("update") boolean update,
        @QueryParam("location") String location) {

    final Vector<String> results = new Vector<String>();
    String output = "";
    long higherStatusId = Long.MIN_VALUE;
    long lowerStatusId = Long.MAX_VALUE;

    Query searchQuery = new Query(searchKeys);
    searchQuery.setCount(50);
    searchQuery.setResultType(Query.ResultType.recent);

    if (sinceId != 0) {
        if (update) {
            searchQuery.setSinceId(sinceId);
        }
        higherStatusId = sinceId;
    }
    if (maxId != 0) {
        if (!update) {
            searchQuery.setMaxId(maxId);
        }
        lowerStatusId = maxId;
    }
    if (location != null) {
        double lat = Double.parseDouble(location.substring(0, location.indexOf(",")));
        double lon = Double.parseDouble(location.substring(location.indexOf(",") + 1, location.length()));

        searchQuery.setGeoCode(new GeoLocation(lat, lon), 10, Query.KILOMETERS);
    }

    try {
        QueryResult qResult = twitter.search(searchQuery);

        for (Status status : qResult.getTweets()) {
            //System.out.println(Long.toString(status.getId())+"  ***  "+Long.toString(status.getUser().getId())+"  ***  "+status.isRetweet()+"  ***  "+status.isRetweeted());

            higherStatusId = Math.max(status.getId(), higherStatusId);
            lowerStatusId = Math.min(status.getId(), lowerStatusId);

            if (!status.isRetweet()) {
                if (status.getGeoLocation() != null) {
                    System.out.println(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                    results.add(Long.toString(status.getId()) + "@"
                            + Double.toString(status.getGeoLocation().getLatitude()) + ","
                            + Double.toString(status.getGeoLocation().getLongitude()));
                } else {
                    results.add(Long.toString(status.getId()) + "@null");
                }
            }
        }

    } catch (TwitterException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    TwitterResults resultsObj = new TwitterResults(results.toString(), higherStatusId, lowerStatusId);
    ObjectMapper mapper = new ObjectMapper();
    try {
        output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(resultsObj);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return output;
}