Enough Hello Worlds, let's fetch tweets!

All right, the name of the book isn't "Mastering Hello Worlds", after all. With Spring, interrogating Twitter's API is really easy.

Registering your application

Before you start, you have to register your application in the Twitter developer console.

Go to https://apps.twitter.com and create a new application.

Give it the name you please. Under the website and Callback URL sections, just enter http://127.0.0.1:8080. This will allow you to test your application in development on your local machine.

Registering your application

Now, navigate to the keys, access the token, and copy the Consumer Key and the Consumer Secret. We will use this in a moment. Take a look at the following screenshot:

Registering your application

By default, our application has read only permissions. This will be enough for our application, but you can tweak it if you wish.

Setting up Spring Social Twitter

We will add the following dependency to our build.gradle file:

compile 'org.springframework.boot:spring-boot-starter-social-twitter'

Note

Spring Social is a set of projects providing access to the public APIs of various social networks. Out of the box, Spring Boot provides integration with Twitter, Facebook, and LinkedIn. Spring Social includes about 30 projects overall, which can be found at http://projects.spring.io/spring-social/.

Add the following two lines to the application.properties:

spring.social.twitter.appId= <Consumer Key>
spring.social.twitter.appSecret= <Consumer Secret>

These are the keys associated with the application we just created.

You will learn more about OAuth in Chapter 6, Securing Your Application. For now, we will just use those credentials to issue requests to Twitter's API on behalf of our application.

Accessing Twitter

We can now use Twitter in our controller. Let's change its name to TweetController as a variable to reflect its new responsibility in a better manner:

@Controller
public class HelloController {

    @Autowired
    private Twitter twitter;

    @RequestMapping("/")
    public String hello(@RequestParam(defaultValue = "masterSpringMVC4") String search, Model model) {
        SearchResults searchResults = twitter.searchOperations().search(search);
        String text = searchResults.getTweets().get(0).getText();
        model.addAttribute("message", text);
        return "resultPage";
    }
}

As you can see, the code searches for tweets matching the request parameter. If it all goes well, you will see the text of the first one being displayed on your screen:

Accessing Twitter

Of course, if the search doesn't yield any result, our clumsy code will fail with an ArrayOutOfBoundException. So, do not hesitate to tweet to solve the problem!

What if we wanted to display a list of tweets? Let's modify the resultPage.html file:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head lang="en">
    <meta charset="UTF-8"/>
    <title>Hello twitter</title>
</head>
<body>
    <ul>
        <li th:each="tweet : ${tweets}" th:text="${tweet}">Some tweet</li>
    </ul>
</body>
</html>

Note

The th:each is a tag defined in Thymeleaf that allows it to iterate over a collection and assign each value to a variable inside a loop.

We will need to change our controller as well:

@Controller
public class TweetController {

    @Autowired
    private Twitter twitter;

    @RequestMapping("/")
    public String hello(@RequestParam(defaultValue = "masterSpringMVC4") String search, Model model) {
        SearchResults searchResults = twitter.searchOperations().search(search);
        List<String> tweets =
                searchResults.getTweets()
                        .stream()
                        .map(Tweet::getText)
                        .collect(Collectors.toList());
        model.addAttribute("tweets", tweets);
        return "resultPage";
    }
}

Note that we are using Java 8 streams to collect only the messages from the tweets. The Tweet class contains many other attributes such as the sender, the retweet count, and so on. However, we will keep it simple for now, as shown in the following screenshot:

Accessing Twitter
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.24.180