Search in sources :

Example 6 with GeoLocation

use of twitter4j.GeoLocation in project druid by druid-io.

the class TwitterSpritzerFirehoseFactory method connect.

@Override
public Firehose connect(InputRowParser parser) throws IOException {
    final ConnectionLifeCycleListener connectionLifeCycleListener = new ConnectionLifeCycleListener() {

        @Override
        public void onConnect() {
            log.info("Connected_to_Twitter");
        }

        @Override
        public void onDisconnect() {
            log.info("Disconnect_from_Twitter");
        }

        /**
       * called before thread gets cleaned up
       */
        @Override
        public void onCleanUp() {
            log.info("Cleanup_twitter_stream");
        }
    };
    // ConnectionLifeCycleListener
    final TwitterStream twitterStream;
    final StatusListener statusListener;
    final int QUEUE_SIZE = 2000;
    /** This queue is used to move twitter events from the twitter4j thread to the druid ingest thread.   */
    final BlockingQueue<Status> queue = new ArrayBlockingQueue<Status>(QUEUE_SIZE);
    final long startMsec = System.currentTimeMillis();
    //
    //   set up Twitter Spritzer
    //
    twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addConnectionLifeCycleListener(connectionLifeCycleListener);
    statusListener = new StatusListener() {

        // This is what really gets called to deliver stuff from twitter4j
        @Override
        public void onStatus(Status status) {
            // time to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }
            try {
                boolean success = queue.offer(status, 15L, TimeUnit.SECONDS);
                if (!success) {
                    log.warn("queue too slow!");
                }
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }
        }

        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {
        //log.info("Got a status deletion notice id:" + statusDeletionNotice.getStatusId());
        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {
            // This notice will be sent each time a limited stream becomes unlimited.
            // If this number is high and or rapidly increasing, it is an indication that your predicate is too broad, and you should consider a predicate with higher selectivity.
            log.warn("Got track limitation notice:" + numberOfLimitedStatuses);
        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {
        //log.info("Got scrub_geo event userId:" + userId + " upToStatusId:" + upToStatusId);
        }

        @Override
        public void onException(Exception ex) {
            ex.printStackTrace();
        }

        @Override
        public void onStallWarning(StallWarning warning) {
            System.out.println("Got stall warning:" + warning);
        }
    };
    twitterStream.addListener(statusListener);
    // creates a generic StatusStream
    twitterStream.sample();
    log.info("returned from sample()");
    return new Firehose() {

        private final Runnable doNothingRunnable = new Runnable() {

            public void run() {
            }
        };

        private long rowCount = 0L;

        private boolean waitIfmax = (getMaxEventCount() < 0L);

        private final Map<String, Object> theMap = new TreeMap<>();

        // DIY json parsing // private final ObjectMapper omapper = new ObjectMapper();
        private boolean maxTimeReached() {
            if (getMaxRunMinutes() <= 0) {
                return false;
            } else {
                return (System.currentTimeMillis() - startMsec) / 60000L >= getMaxRunMinutes();
            }
        }

        private boolean maxCountReached() {
            return getMaxEventCount() >= 0 && rowCount >= getMaxEventCount();
        }

        @Override
        public boolean hasMore() {
            if (maxCountReached() || maxTimeReached()) {
                return waitIfmax;
            } else {
                return true;
            }
        }

        @Override
        public InputRow nextRow() {
            // Interrupted to stop?
            if (Thread.currentThread().isInterrupted()) {
                throw new RuntimeException("Interrupted, time to stop");
            }
            // all done?
            if (maxCountReached() || maxTimeReached()) {
                if (waitIfmax) {
                    // sleep a long time instead of terminating
                    try {
                        log.info("reached limit, sleeping a long time...");
                        Thread.sleep(2000000000L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException("InterruptedException", e);
                    }
                } else {
                // allow this event through, and the next hasMore() call will be false
                }
            }
            if (++rowCount % 1000 == 0) {
                log.info("nextRow() has returned %,d InputRows", rowCount);
            }
            Status status;
            try {
                status = queue.take();
            } catch (InterruptedException e) {
                throw new RuntimeException("InterruptedException", e);
            }
            theMap.clear();
            HashtagEntity[] hts = status.getHashtagEntities();
            String text = status.getText();
            theMap.put("text", (null == text) ? "" : text);
            theMap.put("htags", (hts.length > 0) ? Lists.transform(Arrays.asList(hts), new Function<HashtagEntity, String>() {

                @Nullable
                @Override
                public String apply(HashtagEntity input) {
                    return input.getText();
                }
            }) : ImmutableList.<String>of());
            long[] lcontrobutors = status.getContributors();
            List<String> contributors = new ArrayList<>();
            for (long contrib : lcontrobutors) {
                contributors.add(String.format("%d", contrib));
            }
            theMap.put("contributors", contributors);
            GeoLocation geoLocation = status.getGeoLocation();
            if (null != geoLocation) {
                double lat = status.getGeoLocation().getLatitude();
                double lon = status.getGeoLocation().getLongitude();
                theMap.put("lat", lat);
                theMap.put("lon", lon);
            } else {
                theMap.put("lat", null);
                theMap.put("lon", null);
            }
            if (status.getSource() != null) {
                Matcher m = sourcePattern.matcher(status.getSource());
                theMap.put("source", m.find() ? m.group(1) : status.getSource());
            }
            theMap.put("retweet", status.isRetweet());
            if (status.isRetweet()) {
                Status original = status.getRetweetedStatus();
                theMap.put("retweet_count", original.getRetweetCount());
                User originator = original.getUser();
                theMap.put("originator_screen_name", originator != null ? originator.getScreenName() : "");
                theMap.put("originator_follower_count", originator != null ? originator.getFollowersCount() : "");
                theMap.put("originator_friends_count", originator != null ? originator.getFriendsCount() : "");
                theMap.put("originator_verified", originator != null ? originator.isVerified() : "");
            }
            User user = status.getUser();
            final boolean hasUser = (null != user);
            theMap.put("follower_count", hasUser ? user.getFollowersCount() : 0);
            theMap.put("friends_count", hasUser ? user.getFriendsCount() : 0);
            theMap.put("lang", hasUser ? user.getLang() : "");
            // resolution in seconds, -1 if not available?
            theMap.put("utc_offset", hasUser ? user.getUtcOffset() : -1);
            theMap.put("statuses_count", hasUser ? user.getStatusesCount() : 0);
            theMap.put("user_id", hasUser ? String.format("%d", user.getId()) : "");
            theMap.put("screen_name", hasUser ? user.getScreenName() : "");
            theMap.put("location", hasUser ? user.getLocation() : "");
            theMap.put("verified", hasUser ? user.isVerified() : "");
            theMap.put("ts", status.getCreatedAt().getTime());
            List<String> dimensions = Lists.newArrayList(theMap.keySet());
            return new MapBasedInputRow(status.getCreatedAt().getTime(), dimensions, theMap);
        }

        @Override
        public Runnable commit() {
            // reuse the same object each time
            return doNothingRunnable;
        }

        @Override
        public void close() throws IOException {
            log.info("CLOSE twitterstream");
            // invokes twitterStream.cleanUp()
            twitterStream.shutdown();
        }
    };
}
Also used : User(twitter4j.User) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) TwitterStreamFactory(twitter4j.TwitterStreamFactory) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) StallWarning(twitter4j.StallWarning) ConnectionLifeCycleListener(twitter4j.ConnectionLifeCycleListener) HashtagEntity(twitter4j.HashtagEntity) MapBasedInputRow(io.druid.data.input.MapBasedInputRow) Status(twitter4j.Status) Firehose(io.druid.data.input.Firehose) IOException(java.io.IOException) TwitterStream(twitter4j.TwitterStream) StatusListener(twitter4j.StatusListener) StatusDeletionNotice(twitter4j.StatusDeletionNotice) GeoLocation(twitter4j.GeoLocation) Map(java.util.Map) TreeMap(java.util.TreeMap) Nullable(javax.annotation.Nullable)

Example 7 with GeoLocation

use of twitter4j.GeoLocation in project ddf by codice.

the class TwitterSource method query.

@Override
public SourceResponse query(QueryRequest request) throws UnsupportedQueryException {
    Twitter instance = twitterFactory.getInstance();
    try {
        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);
}
Also used : Query(twitter4j.Query) SourceResponseImpl(ddf.catalog.operation.impl.SourceResponseImpl) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) ConfigurationBuilder(twitter4j.conf.ConfigurationBuilder) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) Twitter(twitter4j.Twitter) ResultImpl(ddf.catalog.data.impl.ResultImpl) QueryResult(twitter4j.QueryResult) Result(ddf.catalog.data.Result) QueryResult(twitter4j.QueryResult) GeoLocation(twitter4j.GeoLocation) TwitterException(twitter4j.TwitterException)

Example 8 with GeoLocation

use of twitter4j.GeoLocation in project twicalico by moko256.

the class TrendsFragment method getGeoLocationSingle.

public Single<GeoLocation> getGeoLocationSingle() {
    return Single.create(subscriber -> {
        try {
            Geocoder geocoder = new Geocoder(getContext());
            Locale locale = Locale.getDefault();
            Address address = geocoder.getFromLocationName(locale.getDisplayCountry(), 1).get(0);
            if (address != null) {
                subscriber.onSuccess(new GeoLocation(address.getLatitude(), address.getLongitude()));
            } else {
                subscriber.onError(new Exception("Cannot use trends"));
            }
        } catch (IOException e) {
            subscriber.onError(e);
        }
    });
}
Also used : Locale(java.util.Locale) Address(android.location.Address) GeoLocation(twitter4j.GeoLocation) IOException(java.io.IOException) Geocoder(android.location.Geocoder) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException)

Example 9 with GeoLocation

use of twitter4j.GeoLocation in project Talon-for-Twitter by klinker24.

the class NearbyTweets method getTweets.

public void getTweets() {
    canRefresh = false;
    new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                Twitter twitter = Utils.getTwitter(context, DrawerActivity.settings);
                boolean manualLoc = sharedPrefs.getBoolean("manually_config_location", false);
                int i = 0;
                while (!connected && i < 5 && !manualLoc) {
                    try {
                        Thread.sleep(1500);
                    } catch (Exception e) {
                    }
                    i++;
                }
                double latitude = -1;
                double longitude = -1;
                if (manualLoc) {
                    // need to query yahoos api for the location...
                    double[] loc = getLocationFromYahoo(sharedPrefs.getInt("woeid", 2379574));
                    latitude = loc[0];
                    longitude = loc[1];
                } else {
                    // set it from the location client
                    Location location = mLastLocation;
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
                query = new Query();
                query.setGeoCode(new GeoLocation(latitude, longitude), 10, Query.MILES);
                QueryResult result = twitter.search(query);
                if (result.hasNext()) {
                    hasMore = true;
                    query = result.nextQuery();
                } else {
                    hasMore = false;
                }
                for (Status s : result.getTweets()) {
                    statuses.add(s);
                }
                ((Activity) context).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        adapter = new TimelineArrayAdapter(context, statuses);
                        listView.setAdapter(adapter);
                        listView.setVisibility(View.VISIBLE);
                        LinearLayout spinner = (LinearLayout) layout.findViewById(R.id.list_progress);
                        spinner.setVisibility(View.GONE);
                    }
                });
            } catch (Throwable e) {
                e.printStackTrace();
                ((Activity) context).runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Toast.makeText(context, getString(R.string.error), Toast.LENGTH_SHORT).show();
                        } catch (IllegalStateException e) {
                        // not attached to activity
                        }
                    }
                });
            }
            canRefresh = true;
        }
    }).start();
}
Also used : Status(twitter4j.Status) Query(twitter4j.Query) Twitter(twitter4j.Twitter) DrawerActivity(com.klinker.android.twitter.activities.drawer_activities.DrawerActivity) Activity(android.app.Activity) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) QueryResult(twitter4j.QueryResult) TimelineArrayAdapter(com.klinker.android.twitter.adapters.TimelineArrayAdapter) GeoLocation(twitter4j.GeoLocation) LinearLayout(android.widget.LinearLayout) GeoLocation(twitter4j.GeoLocation) Location(android.location.Location)

Aggregations

GeoLocation (twitter4j.GeoLocation)9 Twitter (twitter4j.Twitter)5 Location (android.location.Location)4 ArrayList (java.util.ArrayList)4 QueryResult (twitter4j.QueryResult)3 Status (twitter4j.Status)3 Activity (android.app.Activity)2 LinearLayout (android.widget.LinearLayout)2 IOException (java.io.IOException)2 Query (twitter4j.Query)2 TwitterException (twitter4j.TwitterException)2 Manifest (android.Manifest)1 ClipData (android.content.ClipData)1 Context (android.content.Context)1 Intent (android.content.Intent)1 Color (android.graphics.Color)1 Rect (android.graphics.Rect)1 Address (android.location.Address)1 Criteria (android.location.Criteria)1 Geocoder (android.location.Geocoder)1