Example usage for twitter4j GeoLocation GeoLocation

List of usage examples for twitter4j GeoLocation GeoLocation

Introduction

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

Prototype

public GeoLocation(double latitude, double longitude) 

Source Link

Document

Creates a GeoLocation instance

Usage

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();
    }/*  w  w w  .  j  a  v  a  2 s .com*/
    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   w w  w.  ja 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

private GeoLocation solveGeoLocation() {
    String latstr = latTextField.getText().trim();
    String longstr = longTextField.getText().trim();
    if (latstr.length() > 0 && longstr.length() > 0) {
        try {/* w  w w .  j av a 2 s  .com*/
            double lat = Double.parseDouble(latstr);
            double lon = Double.parseDouble(longstr);
            return new GeoLocation(lat, lon);
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:org.wso2.carbon.connector.twitter.TwitterSearchPlaces.java

License:Open Source License

@Override
public void connect(MessageContext messageContext) throws ConnectException {
    // TODO Auto-generated method stub
    if (log.isDebugEnabled()) {
        log.info("executing twitter search places");
    }/* w ww. j a va 2 s .  c o  m*/
    try {
        String latitude = TwitterUtils.lookupTemplateParamater(messageContext, SEARCH_BY_LATITUDE);
        String longitude = TwitterUtils.lookupTemplateParamater(messageContext, SEARCH_LONGITUDE);
        String ip = TwitterUtils.lookupTemplateParamater(messageContext, SEARCH_IP);
        GeoQuery query = new GeoQuery(
                new GeoLocation(Double.parseDouble(latitude), Double.parseDouble(longitude)));
        Twitter twitter = new TwitterClientLoader(messageContext).loadApiClient();
        OMElement element = this.performSearch(twitter, query);
        if (log.isDebugEnabled()) {
            log.info("executing prparing soap envolope" + element.toString());
        }
        super.preparePayload(messageContext, element);
    } catch (TwitterException te) {
        log.error("Failed to search twitter : " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    } catch (Exception te) {
        log.error("Failed to search generic: " + te.getMessage(), te);
        TwitterUtils.storeErrorResponseStatus(messageContext, te);
    }
}

From source file:project.mum.TwitterTrend.java

public List getTrends(double longi, double lati) throws TwitterException {
    List availableTrends = new ArrayList<String>();

    ConfigurationBuilder cf = new ConfigurationBuilder();
    cf.setDebugEnabled(true).setOAuthConsumerKey("TBFU8jBXiIOEde0cnSglw2m7B")
            .setOAuthConsumerSecret("c0tJVVvGgpY2rI1Ol5qmxzMpB1MiBx8PGlLNPG7TYAAVXwYVvL")
            .setOAuthAccessToken("1148852892-OR8mM62nOH4WPJf991X5bCp4zVKT2EU57fBmjWQ")
            .setOAuthAccessTokenSecret("zpXLqUxlkHZT58RDbGEPLnXVB3Kpwp7d8Z4CKb4X4UJW6");
    TwitterFactory tf = new TwitterFactory(cf.build());
    twitter4j.Twitter twitter = tf.getInstance();
    ResponseList<Location> locations;
    List<MyTrend> myTrend = new ArrayList<MyTrend>();
    MyTrend myTwitterTrend;//from   ww  w  .  j  a v a  2s .c o m
    GeoLocation geo = new GeoLocation(longi, lati);
    locations = twitter.getClosestTrends(geo);
    Trends trends = twitter.getPlaceTrends(locations.get(0).getWoeid());
    int count = 0;
    for (Trend trend : trends.getTrends()) {
        if (count < 5) {
            myTwitterTrend = new MyTrend(trend.getName(), trend.getURL());
            myTrend.add(myTwitterTrend);
            count++;
            availableTrends.add(trend.getName());
        }
    }
    System.out.println(" available Trends :" + availableTrends);
    return myTrend;
}

From source file:twitterrest.GeoSearch.java

License:Apache License

public static void main(String[] args) throws TwitterException {
    // ?//w ww.ja  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();

    // ?????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");
    }/* w w w .ja 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:wap.twitter.controller.TrendsServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("Trending====================Post");
    response.setContentType("text/json;charset=UTF-8");
    TwitterUtility tu = new TwitterUtility();
    String lat = request.getParameter("lat");
    String lng = request.getParameter("lng");
    if (lat != null && lng != null) {
        try {//w  w  w.j  a v a2  s . c o  m
            String jsn = (new Gson())
                    .toJson(tu.getTrends(new GeoLocation(Double.parseDouble(lat), Double.parseDouble(lng))));
            System.out.println(jsn);
            response.getWriter().write(jsn);
        } catch (TwitterException ex) {
            Logger.getLogger(TrendsServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:webServices.RestServiceImpl.java

@GET
@Path("/findTwittsRest")
@Produces({ MediaType.TEXT_PLAIN })/*from  w  ww . ja  v a2  s.  c o 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;
}