Hey #APIFriday-ers! If you have been following along with SAPPHIRE, you know that the SAP API Business Hub got an awesome refresh that came with a bunch of new content, like Machine Learning and Concur APIs and services.We’ve also got some cool business services like sentiment analysis and text analytics!

So this week I’ve got a little challenge in store for you. Ever wonder what people are saying about your event, company, or blog series on social media? By connecting with Twitter, we can see what they are saying and if it’s good or bad. How do you find out the sentiment? By using SAP’s Sentiment Analysis Business Service available from the SAP HANA Text Analysis Fact Extraction toolkit!  Next week I will be showing you how to use the Sentiment Analysis API, but first I want to see if you can figure it out. I’ll get you started with how to pull in tweets about an event like SAPPHIRE NOW and leave it open to you to see if you can analyze those tweets. Don’t have time or can’t figure it out? No worries! The solution will be available next #APIFriday!

To get started, you’ll need a Twitter account. Sign up here. You’ll also need to create an App on the My Apps portion of Twitter Developers. You can get to My Apps here. Once you log in to Twitter Apps, click Create New App.

Provide your application details. For the Website field, I used my Web IDE url as that is where I am doing most of my development. Feel free to use your own hosted site or wherever you plan on developing. Additionally, I did some testing in Postman to make sure the Twitter API was giving me the information I wanted. If you want to do Postman testing, you’ll want to add the Postman callback url to the Callback URL field. You can add it later if you are not sure. Once you have filled out all the information, click Create you Twitter application.

Once you created your app, you are going to want to generate an Access Token for yourself. Click on the App and go to the Access Token and Permissions tab. Generate an access token. There should be a button towards the bottom of the page. Once you have your access token, there are 4 main fields to take note of that will be important for the OAuth flow. Twitter supports OAuth 1.0.

The 4 fields you will need are the Consumer Key, the Consumer Secret, the Access Token, and the Access Token Secret.

Now we are ready to implement the OAuth 1.0 flow in our application. Head over to Web IDE or whatever IDE you choose to use for your development.

Create a new blank UI5 project to work with. We’ll be creating a Twitter Tweet wall so we want a blank canvas. In the main controller is where we’ll implement the Twitter call. Let’s do some setup first. Create an onInit() function first. Here we are going to define our default model and starting hashtag to search. We’ll also create a placeholder model for our tweets call twitterResults.

onInit: function(){
  var event ={
    "eventName": "SAPPHIRENOW"
  };
  var searchTerm = new sap.ui.model.json.JSONModel();
  searchTerm.setData(event);
  sap.ui.getCore().byId("__xmlview0").setModel(searchTerm);

  var twitterResult = new sap.ui.model.json.JSONModel();
  this.getView().setModel(twitterResult, "twitterResult");

  //this is the function we are going to define in the next steps
  this.callTwitter();
}

For the Twitter setup, I am going to send you over to ‘s blog about SAPUI5 and Twitter as he’s explanation of the OAuth flow and how to implement it in UI5 is the best I have found. Create a new function called callTwitter() and add your OAuth code there. We’ll make a couple tweaks, but go ahead and follow along with his blog post up until you get to Getting the data. At that point, we are going to deviate.

Some pointers:

In Step 6, Andy refers to the CryptoJS algorithms. I have found that they are no longer hosted at the URL provided. Instead, I download the proper libraries, created a JS folder under my webapp folder, and upload the libraries to the JS folder. In my index.html file, I loaded the libraries.

<script src="js/hmac-sha1.js"></script>
<script src="js/enc-base64-min.js"></script>

You can then skip the require or include script code snippets in your app. You will need the last code snippet as this creates the proper signature for OAuth 1.0.

Once you have the OAuth flow set up, there are a couple changes we need to make and a couple gaps to fill in.

As part of Step 2, we called a function called makeid(); however, we haven’t defined that function yet. Outside of the callTwitter() function, let’s create this new function. It will return a 10 digit number.

makeid: function(){
	return Math.floor(Math.random() * 899999 + 100000);	
}

Also from step 2, we define our query variable. For our purposes, we are going to query on a text variable that is a hashtag that will come from a model. Let’s update the query variable to match below where our query is coming from the eventName defined in our default model.

var eventQ = sap.ui.getCore().byId("__xmlview0").getModel().oData.eventName;
var query = "q=" + encodeURIComponent(eventQ);

If you want, you can remove the variables count, language, and callback as we will not be using them.

This means in Step 3, our searchOption is a little different. We are only using the query portion of the search options.

var searchOption = query;

So then in Step 4, we can also update our parametersString.

var parametersString = oauth_parameters + query ;

The final change to make is to Step 7 when we construct the URL. We can remove the callback and language portions.

var URL = BaseURL + "?" + searchOption + "&" + oauth_parameters + "oauth_signature=" + oauth_signature;

At this point, your callTwitter() function should look like so:

Once your OAuth flow is set up, we can actually make the Twitter call. We’re going to use AJAX for our call. Remember how to set up an AJAX GET request? Give it a shot! The URL you’re using is the URL variable you have constructed.

You’re AJAX should look a little something like this. We’re doing a GET request and we want to allow for CORS. When we get results, we’ll bind them to the twitterResult model.

$.ajax({
  type: 'GET',
  url: URL,
  crossDomain: true,
  async: true,
  header: {
    "Access-Control-Allow-Origin": '*'
  }
}).done(function(results) {
  if (results) {
        var twitterResult = new sap.ui.model.json.JSONModel();
        twitterResult.setData(results);
        sap.ui.getCore().byId("__xmlview0").setModel(twitterResult, "twitterResult");
    }
});

The last thing to do is actually display the tweets in your view! We’ve got them in our twitterResult model, so let’s head over to the main view.

In the view, I created a Grid Layout of Object List Items to create the “wall” feel. We’ll use our tweets as our aggregator. In between the content tags, let’s add our grid.

<l:Grid defaultSpan="L4 M6 S6" class="sapUiSmallMarginTop" id="list"
  content="{ path: 'twitterResult>/statuses', sorter: { path: 'accountID', descending: false }, groupHeaderFactory: '.createGroupHeader' }">
  <l:content>
    <ObjectListItem icon="{twitterResult>user/profile_image_url}"
      intro="{twitterResult>user/name} - {twitterResult>created_at} - {twitterResult>user/location}" 
      title="{twitterResult>text}" 
      type="{= ${device>/system/phone} ? 'Active' : 'Inactive'}">
    </ObjectListItem>
  </l:content>
</l:Grid>

Don’t forget to include the layout (l) namesapce in the View opening tag!

xmlns:l="sap.ui.layout"

We can make the title dynamic for the page based on the tag.

<Page title="{i18n>title}{/eventName}">

In the i18n properties file, change the title property to be “Tweets about #” or something similar.

title=Tweets from #

Make sure you SAVE ALL YOUR CHANGES and run the application! You should have a nice wall of tweets from SAPPHIRE!

I’ll post a couple Tech Tips on how to make your tweets auto refresh and adding in a pop-up dialog box to change the event searched, but now you can add tweets to your app!

Are you ready to analyze them? Check out the Sentiment Analysis API and give it your best shot! My solution will be posted next week as part of my #APIFriday series, but it’s not the only solution. What do you guys think; want me to host my code on Github and you can fork it to share your solution? Let me know and we can make these coding challenges a lot more fun 🙂

To report this post you need to login first.

2 Comments

You must be Logged on to comment or reply to a post.

  1. Kumar Jayant

    Hi Meredith,

    Thanks for writing the blog. Started following the steps and writing the code. There seems to be some problem with cross origin

    However, the GET does seem to retrieve results. Just that the response coming as fail is not letting the result be bound to the UI5 control.

     

    Any guesses where things would have gone wrong? Website in the Twitter app is something like https://appname-serverid.dispatcher.hana.ondemand.com

    Thanks in advance,

    Jayant

    (0) 

Leave a Reply