Interpreting Spring Social Twitter Data with Watson Tone Analyzer

Share this post:

In this post, I’ll show you how to build a basic Spring app with Twitter login using Spring Social. Then we’ll use Watson Tone Analyzer to determine the dominant emotion from each of the tweets on the time of the logged-in user. The project we will create will be similar to the Accessing Twitter Data Spring guide, but with a few modifications.


Before you begin, you’ll need to have Java and Maven installed and configured on your PATH.

Registering the Application with Twitter

The first step is to register a new application with Twitter. Go to the Twitter Developer site and login or register for a Twitter account. Every Twitter account can be treated as a developer account.

After you are signed in to your Twitter account, click Create New App in the top-right corner. This should bring you to a page displaying all of your apps. Create a new app by clicking the Add a New App button. Complete the form for your new app, naming it whatever you choose. I will call my app “spring-social-tone-demo” but yours may be different. Set the Callback URL to http://localhost:8080/connect/twitter, as we will run our application locally for this example.

After you have finished creating your app, you should find a set of API credentials under Keys and Access Tokens; take note of these, as we will need them later. And with that, your Twitter app is now ready to connect with Spring Social!

Create Tone Analyzer Service

Next we’ll setup a Watson Tone Analyzer service on IBM Cloud. Navigate to the IBM Cloud catalog and find the Tone Analyzer service. Create an instance of this service; I will use the default settings for this demo.

After your service has been provisioned, you should be directed to its page. Click Service Credentials on the left sidebar. If a set of credentials has already been created, expand them to find your username and password. If you do not see a set of credentials on this page, click New Credentials and follow the prompts given.

Once you have found your credential set, take note of them, as we will need them for our Spring application.

Create Spring Social Application

Choose a directory for this project, and create a pom.xml file inside it with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""






Before we can connect to Twitter and the Watson Tone Analyzer service, we need to provide the API credentials you have been accumulating. Create an file with the following contents:********************


You should, of course, fill in the API Key and API Secret from your Twitter app as well as the credentials from your Watson Tone Analyzer service on IBM Cloud.

Next, let’s setup the Thymeleaf templates from the Spring guide. These files will provide the front end for our simple Spring Social application. For more information about these files, check out the Spring guide on Accessing Twitter Data.

<html xmlns:th="">
    <title>Hello Twitter</title>
    <h3>Connect to Twitter</h3>
    <span th:if="${social_provider_error}">Provider error (maybe you need to configure the app id and secret?)</span>
    <form action="/connect/twitter" method="POST">

You aren't connected to Twitter yet. Click the button to connect this application with your Twitter account.

<p><button type="submit">Connect to Twitter</button></p> </form> </body> </html>

    <title>Hello Twitter</title>
    <h3>Connected to Twitter</h3>

        You are now connected to your Twitter account.
        Click <a href="/">here</a> to see an analysis of your Twitter timeline.

<html xmlns:th="">
    <title>Hello Twitter</title>
    <h3>Hello, <span th:text="${}">Some User</span>!</h3>


tweet text

tone text

</body> </html>

Now we have a bunch of HTML files, so let’s setup a Controller to serve them. Create a with the following contents:

package application;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;

public class MainController {

    private Twitter twitter;
    private ConnectionRepository connectionRepository;
    ToneAnalyzer toneAnalyzer;

    public String helloTwitter(Model model) {
        if (connectionRepository.findPrimaryConnection(Twitter.class) == null) {
            return "redirect:/connect/twitter";


        List<Tweet> timeline = twitter.timelineOperations().getHomeTimeline();
        model.addAttribute("timeline", timeline);

        ArrayList<String> tones = new ArrayList<>();
        for(Tweet tweet : timeline){
        model.addAttribute("tones", tones);

        return "timeline";

    private String getDominantEmotion(String tweetText){
        ToneOptions options = new ToneOptions.Builder().text(tweetText).sentences(false).build();
        DocumentAnalysis documentAnalysis = toneAnalyzer.tone(options).execute().getDocumentTone();
        List<ToneScore> toneScores = documentAnalysis.getToneCategories().get(0).getTones();

        double maxScore = toneScores.get(0).getScore();
        String dominantTone = toneScores.get(0).getToneId();
        for(ToneScore toneScore : toneScores){
            if(toneScore.getScore() > maxScore){
                maxScore = toneScore.getScore();
                dominantTone = toneScore.getToneName();

        return dominantTone;

The Controller you just created will handle authentication into the Spring application via Twitter. If the user has not signed in, it redirects to the /connect/twitter page to allow Twitter signin. After the user has signed in with Twitter, the Controller accesses their timeline.

At this point, we add the Watson Tone Analyzer service. Given a list of Tweets, ToneAnalyzer perform a tone analysis on the text of each and find the emotion with the highest score. The logic involved in performing tone analysis and finding the dominant emotion takes place in the getDominantEmotion method.

Finally, the controller returns the timeline template, which will be populated with the data we just assembled.

You may have notice that we Autowired our reference to the ToneAnalyzer object for use in the Controller. Next let’s configure that behavior; create a file with the following contents:

package application;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

public class ToneAnalyzerConfig {

    String user;
    String pass;

    public ToneAnalyzer toneAnalyzer(){
        return new ToneAnalyzer("2017-09-01", user, pass);

In this file, we setup a Spring Bean for the ToneAnalyzer object. The credentials for the service you created are pulled from the file, where we previously put them.

Now let’s make the application executable. Create an with the following contents:

package application;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class Application {

    public static void main(String[] args) {, args);

That’s it! If you’ve followed along, you should have a Spring Social application that is ready to test.

Testing the Spring Social Application

We are going to test our application locally. Start the Spring Social app with the following command:

$ mvn spring-boot:run

Now open your web browser and navigate to localhost:8080. Click the Connect to Twitter button. You should be redirected to Twitter and asked to login, if you haven’t already logged in on your current browser. After logging into Twitter, your app will request some basic permissions needed to access your account. After accepting these permissions, you will be redirected back to localhost.

Now click the given link to see your timeline. After your timeline populates the screen, you should see a series of tweets, with an emotion from the Tone Analyzer below each one.


In this post, we created a Spring Social application that authenticates with Twitter. Then we determined the dominant emotion of the tweets from the timeline of the logged-in Twitter account, using the Tone Analyzer service on IBM Cloud.



via IBM Cloud Blog

November 8, 2017 at 12:45PM