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.codice.ddf.catalog.twitter.source.TwitterSource.java

License:Open Source License

@Override
public SourceResponse query(QueryRequest request) throws UnsupportedQueryException {
    Twitter instance = twitterFactory.getInstance();
    try {//w w w  . ja v  a2 s .c  o m
        instance.getOAuth2Token();
    } catch (TwitterException e) {
        throw new UnsupportedQueryException("Unable to get OAuth2 token.", e);
    }
    TwitterFilterVisitor visitor = new TwitterFilterVisitor();
    request.getQuery().accept(visitor, null);
    Query query = new Query();
    query.setCount(request.getQuery().getPageSize());
    if (visitor.hasSpatial()) {
        GeoLocation geoLocation = new GeoLocation(visitor.getLatitude(), visitor.getLongitude());
        query.setGeoCode(geoLocation, visitor.getRadius(), Query.Unit.km);
    }
    if (visitor.getContextualSearch() != null) {
        query.setQuery(visitor.getContextualSearch().getSearchPhrase());
    }
    if (visitor.getTemporalSearch() != null) {
        Calendar.Builder builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getStartDate());
        Calendar calendar = builder.build();
        query.setSince(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));

        builder = new Calendar.Builder();
        builder.setInstant(visitor.getTemporalSearch().getEndDate());
        calendar = builder.build();
        query.setUntil(calendar.get(Calendar.YEAR) + "-" + calendar.get(Calendar.MONTH) + "-"
                + calendar.get(Calendar.DAY_OF_MONTH));
    }

    QueryResult queryResult;
    try {
        queryResult = instance.search().search(query);
    } catch (TwitterException e) {
        throw new UnsupportedQueryException(e);
    }
    List<Result> resultList = new ArrayList<>(queryResult.getCount());
    resultList.addAll(queryResult.getTweets().stream().map(status -> new ResultImpl(getMetacard(status)))
            .collect(Collectors.toList()));
    return new SourceResponseImpl(request, resultList);
}

From source file:org.hornetq.integration.twitter.impl.OutgoingTweetsHandler.java

License:Apache License

public HandleStatus handle(final MessageReference ref) throws Exception {
    if (filter != null && !filter.match(ref.getMessage())) {
        return HandleStatus.NO_MATCH;
    }/*from w  w w . j ava  2  s. c  o m*/

    synchronized (this) {
        ref.handled();

        ServerMessage message = ref.getMessage();

        StatusUpdate status = new StatusUpdate(message.getBodyBuffer().readString());

        // set optional property

        if (message.containsProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID)) {
            status.setInReplyToStatusId(message.getLongProperty(TwitterConstants.KEY_IN_REPLY_TO_STATUS_ID));
        }

        if (message.containsProperty(TwitterConstants.KEY_GEO_LOCATION_LATITUDE)) {
            double geolat = message.getDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LATITUDE);
            double geolong = message.getDoubleProperty(TwitterConstants.KEY_GEO_LOCATION_LONGITUDE);
            status.setLocation(new GeoLocation(geolat, geolong));
        }

        if (message.containsProperty(TwitterConstants.KEY_PLACE_ID)) {
            status.setPlaceId(message.getStringProperty(TwitterConstants.KEY_PLACE_ID));
        }

        if (message.containsProperty(TwitterConstants.KEY_DISPLAY_COODINATES)) {
            status.setDisplayCoordinates(message.getBooleanProperty(TwitterConstants.KEY_DISPLAY_COODINATES));
        }

        // send to Twitter
        try {
            this.twitter.updateStatus(status);
        } catch (TwitterException e) {
            if (e.getStatusCode() == 403) {
                // duplicated message
                HornetQTwitterLogger.LOGGER.error403(connectorName);
                queue.acknowledge(ref);

                return HandleStatus.HANDLED;
            } else {
                throw e;
            }
        }

        queue.acknowledge(ref);
        HornetQTwitterLogger.LOGGER.debug(connectorName + ": forwarded to twitter: " + message.getMessageID());
        return HandleStatus.HANDLED;
    }
}

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

License:Open Source License

/**
 * Query the twitter search API using oAuth 2.0
 * @return/* ww  w .ja v a 2  s .  c o m*/
 */
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.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Returns tweets that match a specified query.
 * <p/>//from w w w  .  ja va2s .  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.mule.twitter.TwitterConnector.java

License:Open Source License

/**
 * Updates the authenticating user's status. A status update with text identical
 * to the authenticating user's text identical to the authenticating user's
 * current status will be ignored to prevent duplicates. <br>
 * This method calls http://api.twitter.com/1.1/statuses/update
 * <p/>/*from  w  ww .  j  a  va  2 s.  com*/
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:updateStatus}
 *
 * @param status    the text of your status update
 * @param inReplyTo The ID of an existing status that the update is in reply to.
 * @param latitude  The latitude of the location this tweet refers to. This parameter will be ignored unless it is
 *                  inside the range -90.0 to +90.0 (North is positive) inclusive.
 * @param longitude he longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to
 *                  +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range or if there not a
 *                  corresponding lat parameter.
 * @return the latest {@link Status}
 * @throws TwitterException when Twitter service or network is unavailable
 * @see <a href="http://dev.twitter.com/doc/post/statuses/update">POST
 *      statuses/update | dev.twitter.com</a>
 */
@Processor
public Status updateStatus(String status, @Default(value = "-1") @Optional long inReplyTo,
        @Placement(group = "Coordinates") @Optional Double latitude,
        @Placement(group = "Coordinates") @Optional Double longitude) throws TwitterException {
    StatusUpdate update = new StatusUpdate(status);
    if (inReplyTo > 0) {
        update.setInReplyToStatusId(inReplyTo);
    }
    if (latitude != null && longitude != null) {
        update.setLocation(new GeoLocation(latitude, longitude));
    }
    Status response = twitter.updateStatus(update);

    //Twitter4j doesn't throw exception when json reponse has 'error: Could not authenticate with OAuth'
    if (response.getId() == -1) {
        throw new TwitterException("Could not authenticate with OAuth\n");
    }

    return response;
}

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

License:Open Source License

private GeoQuery createQuery(Double latitude, Double longitude, String ip) {
    if (ip == null) {
        return new GeoQuery(new GeoLocation(latitude, longitude));
    }/* ww w  .  j  a  v  a2 s .  c o  m*/
    return new GeoQuery(ip);
}

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

License:Open Source License

/**
 * Creates a new place at the given latitude and longitude.
 * <p/>//from  w  ww.ja  va2  s.c o m
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:createPlace}
 *
 * @param placeName            The placeName a place is known as.
 * @param containedWithin The place_id within which the new place can be found.
 *                        Try and be as close as possible with the containing place. For
 *                        example, for a room in a building, set the contained_within as the
 *                        building place_id.
 * @param token           The token found in the response from geo/similar_places.
 * @param latitude        The latitude the place is located at.
 * @param longitude       The longitude the place is located at.
 * @param streetAddress   optional: This parameter searches for places which have
 *                        this given street address. There are other well-known, and
 *                        application specific attributes available. Custom attributes are
 *                        also permitted. Learn more about Place Attributes.
 * @return a new {@link Place}
 * @throws TwitterException when Twitter service or network is unavailable
 */
@Processor
public Place createPlace(String placeName, String containedWithin, String token,
        @Placement(group = "Coordinates") Double latitude, @Placement(group = "Coordinates") Double longitude,
        @Optional String streetAddress) throws TwitterException {
    return twitter.createPlace(placeName, containedWithin, token, new GeoLocation(latitude, longitude),
            streetAddress);
}

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

License:Open Source License

/**
 * Locates places near the given coordinates which are similar in name.
 * Conceptually you would use this method to get a list of known places to choose from first.
 * Then, if the desired place doesn't exist, make a request to POST geo/place to create a new one.
 * The token contained in the response is the token needed to be able to create a new place.
 * <p/>/*from www  .  ja v a2 s.  c  o  m*/
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:getSimilarPlaces}
 *
 *
 * @param latitude The latitude to search around. This parameter will be ignored unless it is inside the range
 *                 -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there
 *                 isn't a corresponding long parameter.
 * @param longitude The longitude to search around. The valid ranges for longitude is -180.0 to +180.0
 *                  (East is positive) inclusive. This parameter will be ignored if outside that range,
 *                  if it is not a number, if geo_enabled is disabled, or if there not
 *                  a corresponding lat parameter.
 * @param placeName      The name a place is known as.
 * @param containedWithin This is the place_id which you would like to restrict the search results to.
 *                        Setting this value means only places within the given place_id will be found.
 * @param streetAddress This parameter searches for places which have this given street address.
 *                      There are other well-known, and application specific attributes available.
 *                      Custom attributes are also permitted.
 * @return places
 * @throws TwitterException when Twitter service or network is unavailable
 */
@Processor
public SimilarPlaces getSimilarPlaces(@Placement(group = "Coordinates") Double latitude,
        @Placement(group = "Coordinates") Double longitude, String placeName, @Optional String containedWithin,
        @Optional String streetAddress) throws TwitterException {
    return twitter.getSimilarPlaces(new GeoLocation(latitude, longitude), placeName, containedWithin,
            streetAddress);
}

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

License:Open Source License

/**
 * Returns the locations that Twitter has trending topic information for, closest to a specified location.<br>
 * The response is an array of "locations" that encode the location's WOEID and some other human-readable information such as a canonical name and country the location belongs in.<br>
 * A WOEID is a <a href="http://developer.yahoo.com/geo/geoplanet/">Yahoo! Where On Earth ID</a>.
 * <br>This method calls http://api.twitter.com/1.1/trends/closest.json
 * /* w w w. j  av a  2 s.c o  m*/
 * {@sample.xml ../../../doc/twitter-connector.xml.sample twitter:getClosestTrends}
 * 
 * @param latitude  The latitude of the location this tweet refers to. This parameter will be ignored unless it is
 *                  inside the range -90.0 to +90.0 (North is positive) inclusive.
 * @param longitude he longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to
 *                  +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range or if there not a
 *                  corresponding lat parameter.
 * @return the locations
 * @throws TwitterException twitter4j.TwitterException when Twitter service or network is unavailable
 */
@Processor
public ResponseList<Location> getClosestTrends(double latitude, double longitude) throws TwitterException {
    return twitter.getClosestTrends(new GeoLocation(latitude, longitude));
}

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"));
    }// www. jav a 2s.c  o  m
    if (fromDate != null) {
        searchQuery.setSince(fromDate.toString("YYYY-MM-dd"));
    }
    return executeApiRequest(searchQuery);
}