javatwitterspring-socialtwitter-streaming-apispring-social-twitter

How to get location based tweets using Spring social with Twitter Streaming API?


I need to live feed the tweets based on geolocation. By Twitter API documentation I understand we can search based on geolocaion.

But is it possible to stream based on geolocaion? and i use spring social twitter for API integration.

           List<StreamListener> listeners = new ArrayList<StreamListener>();
           StreamListener streamListener = new StreamListener() {               
            @Override
            public void onWarning(StreamWarningEvent warningEvent) {}

            @Override
            public void onTweet(Tweet tweet) {}

            @Override
            public void onLimit(int numberOfLimitedTweets) {}

            @Override
            public void onDelete(StreamDeleteEvent deleteEvent) {}
        };
        listeners.add(streamListener);      
        //to-do geolocation based stream filter
        twitter.streamingOperations().filter("tesla", listeners);
        Thread.sleep(10000);

And I see Twitter streaming API also have a location parameter for request. But how do i implement it with Spring Social Twitter.

Thanks


Solution

  • I have been trying this and finally got the streaming tweets working. I proceeded with this tutorial - https://spring.io/guides/gs/accessing-twitter.

    visiting http://localhost:8080/stream/10_000 will stream tweets from San Francisco region(hardcoded as of now) for 10 secs in the console and display those tweets in webpage after 10 sec.

    In the Controller Class add a @RequestMapping method something like this: HelloController.java

    @RequestMapping("/stream/{time}")
    public String streamTweet(@PathVariable int time, Model model) throws InterruptedException{
        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
            return "redirect:/connect/twitter";
        }
        Model returnedmodel = streamService.streamApi(model, time);
        model = returnedmodel;
    
        return "stream";
    }
    

    StreamService.java

    @Service
    public class StreamService {
    
        private final Logger log = LoggerFactory.getLogger(StreamService.class);
    
        @Autowired
        private Twitter twitter;
    
        public Model streamApi(Model model, int time) throws InterruptedException{
    
            List<Tweet> tweets = new ArrayList<>();
    
            List<StreamListener> listeners = new ArrayList<StreamListener>();
            StreamListener streamListener = new StreamListener() {
    
                @Override
                public void onWarning(StreamWarningEvent warningEvent) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void onTweet(Tweet tweet) {
                    System.out.println(tweet.getUser().getName() + " : " + tweet.getText());
                    log.info("User '{}', Tweeted : {}", tweet.getUser().getName() , tweet.getText());
                    tweets.add(tweet);
                    model.addAttribute("tweets", tweets);
                }
    
                @Override
                public void onLimit(int numberOfLimitedTweets) {
                    // TODO Auto-generated method stub
    
                }
    
                @Override
                public void onDelete(StreamDeleteEvent deleteEvent) {
                    // TODO Auto-generated method stub
    
                }
            };
    
            listeners.add(streamListener);
            //This sets the GeoCode (-122.75,36.8,-121.75,37.8) of San Francisco(South-West and North-East) region as given in below twitter docs
            //https://dev.twitter.com/streaming/overview/request-parameters#locations
            Float west=-122.75f;
            Float south=36.8f;
            Float east=-121.75f;
            Float north = 37.8f;
    
            FilterStreamParameters filterStreamParameters = new FilterStreamParameters();
            filterStreamParameters.addLocation(west, south, east, north);
    
            Stream userStream = twitter.streamingOperations().filter(filterStreamParameters, listeners);
            Thread.sleep(time);
            userStream.close();
            return model;
        }
    }
    

    stream.html

    <html>
        <head>
            <title>Hello Twitter Stream</title>
        </head>
        <body>                  
            <h4>The Twitter Stream:</h4>`enter code here`
            <ul>
                <li th:each="tweet:${tweets}" 
                    th:text="${tweet.text} + ' tweeted by - ' + ${tweet.user.name} 
                        + ' from ' + ${tweet.user.location} 
                        + ' @ ' + ${tweet.createdAt}"> 
                        Tweet
                </li>
            </ul>
        </body>
    </html>
    

    PS: I know you don't wanna do something like this (i.e. show tweets after waiting for X secs, I just did this to make this working)

    Btw, if you have any ideas how can I use this stream to display tweets realtime, (with or without using websockets) please share. Thanks.