09

Server-Side Data Processing

API Design

API Processing

Optimizing API Requests

Summary

The Samsung SmartTV does not support server-side services, including database servers, or a standard connectivity model such as ODBC. Instead, Ajax-type server-side data handling is common using XML or the JSON API.

images

Figure 9-1. The Samsung SmartTV and Server-Side Data Request

Chapter 9 will cover data exchanging between a Samsung SmartTV and a server, including necessary API design, API data processing, and optimizing server-side requests.

API Design

The design of an application depends on how efficiently its data server responds to API requests on necessary data for the application. A well-designed application development project can significantly reduce its development schedule. For efficient API data exchanges, it is vital for a developer to familiarize oneself with the server API, and actively consult with the data provider.

Chapter 9 will use the previously developed Hands Frame application to explain the API design practice.

Designing API for a VOD Gallery

images

Figure 9-2. An Example VOD Gallery Application

The application shown in Figure 9-2 has a static menu list of titles in the left pane, and a focused menu item shows a list of VOD files for the item. To display meta information for the VOD files as shown above, an API concept can be designed as shown below.

Request Parameters

images

Table 9-1. Request Parameters for the VOD Gallery

Response Data Structure

images

images

Table 9-2. Data Structure of the VOD Gallery Response

The API structure is similar to a common bulletin board service's data structure. A titleid (unique ID for each VOD title) is used as the key value in a POST or GET request, and for receiving the corresponding data from the server.

XML Type Response with the Data Structure

An XML-type API Response with the above data structure is shown in the following example.

<vod>
    <titleId>001</titleId>
    <title>Hello! This is your SmartTV</title>
    <date>2013-01-23</date>
    <thumbnail><![CDATA[http://thumbnails.com/thumbnail.jpg]]></thumbnail>
    <vodURL><![CDATA[http://vod.com/vod.mp4]]></vodURL>
    <description>
     A SmartTV, sometimes referred to as a connected TV or hybrid TV (not to be confused with IPTV, Internet TV, or Web TV), describes a trend of integration of the Internet and Web 2.0 features into television sets and set-top boxes.
    </description>
    <state>true</state>
</vod>

JSON Type Response with the Data Structure

A JSON type API Response with the above data structure is shown in the following example.

{
    “titleId”:
    “001”,
    “title”: “Hello! This is your SmartTV”,
    “date”: “2013-01-23”,
    “thumbnail”: “http://thumbnails.com/thumbnail.jpg”,
    “vodURL”: “http://vod.com/vod.mp4”,
     “description”: “A SmartTV, sometimes referred to as a connected TV or hybrid TV (not to be confused with IPTV, Internet TV, or Web TV), describes a trend of integration of the Internet and Web 2.0 features into television sets and set-top boxes”,
    “state”: “true”
}

XML vs. JSON

It was already mentioned that most API services in the SmartTV are provided in either the XML or the JSON format, and occasionally in a plain-text format. Many developers prefer the JSON type. But that does not mean JSON is superior to other types. Each environment calls a different response type for more efficient processing. The JSON format is optimized for the web platform, easy to use, light-weight, and most of all, fits the object-oriented JavaScript model. On the other hand, the XML format is supported by many platforms, easily readable, and supplied with a wealth of reference information.

images

Table 9-3. JSON vs. XML

Efficient API Handling and Conclusion

A large portion of API design is up to the API provider's system environment. An application developer's API design is limited by available options by the API provider. Some API providers have severely limited options or even fixed-API structure only, rendering concept of the API design meaningless.

Even so, creating and managing an API structure table, as shown previously, can still save a huge amount of unnecessary communication with the service company. The table can be used during the entire development and debugging. It can also be shared with non-programmers: producers, designers, and clients—and allow them to quickly check if a desired function can be implemented.

API Processing

A data-request API is commonly processed in the following order.

  1. Receive an Ajax request.
  2. Obtain the requested data and format it as a predefined return-object variable.
  3. Return the variable through a DOM exchange.

A JavaScript library is often used to simplify the preceding Ajax request and DOM exchange. The jQuery (http://jquery.com/) library is used in this book.

Ajax Request

First, an Ajax request is implemented using the jQuery library.

jQuery.ajax(url, {
    type : ‘GET’,
    dataType :“xml”,
    data: param,
    timeout: 5000,
    success: function(res, status, xhr) {
        alert(‘res :’ + res);
        callback && callback(res);
    },
    error : function(xhr, status, error) {
        alert(‘error! : [Featured] ajax request URL : ’ + url);
    },
    complete : function() {
        alert(‘Complete! : [Featured] ajax request URL : ’ + url);
    }
});

The preceding example has only the bare minimum options. It configures URL for the API request to be sent, GET or POST option, response API type, and callback functions for success/error/complete cases. See the following code for packaging the request as a usable component.

var $request = function(url, param, callback) {
    jQuery.ajax(url, {
        type : ‘GET’,
        dataType : “xml”,
        data: param,
        timeout: 5000,
        success: function(res, status, xhr) {
            alert(‘res :’ + res);
            callback && callback(res);
        },
        error : function(xhr, status, error) {
            alert(‘error! : [Featured] ajax request URL : ’ + url);
        },
        complete : function() {
            alert(‘Complete! : [Featured] ajax request URL : ’ + url);
        }
    });
};

The $request() function can be called with parameters to make an Ajax request for an XML type data. The SmartTV does not have an exclusive Ajax format. Most programming practices, including native JavaScript and jQuery, can also be used for a SmartTV application.

Formatting Response Data

A SmartTV application generally has several element options, such as a menu, VOD playback, and text documents. A common API also has various options. It can have either JSON or XML data type. It can also have a response structure such as List, Map, or String. It is vital to format a response into a usable variable through a well-designed API request. See the following XML document.

<?xml version=“1.0” encoding=“UTF-8”?>
<API>
    <item>
        <itemId>001</itemId>
        <itemName>The 2011 SmartTV</itemName>
        <itemState>false</itemState>
    </item>
    <item>
        <itemId>002</itemId>
        <itemName>The 2012 SmartTV</itemName>
        <itemState>false</itemState>
    </item>
    <item>
        <itemId>003</itemId>
        <itemName>The 2013 SmartTV</itemName>
        <itemState>true</itemState>
    </item>

</API>

Include a callback function, success(), in the Ajax request, to reformat the preceding XML data.

jQuery.ajax(url, {
    type : ‘GET’,
    dataType : “xml”,
    success: function(res) {
        var result = jQuery(res).find(‘API > item’);
    }
});

The success() callback function uses jQuery find() to access the XML element. Then it stores a member array “item” from the root element “API” into the variable result.

jQuery.isArray(result);    // true

The jQuery isArray() can be used to confirm that the result is an array type variable. Let's see another example.

{
   “API”: {
     “item”: [
       {
         “itemId”: “001”,
         “itemName”: “2011SmartTV”,
         “itemState”: “false”
       },
       {
         “itemId”: “002”,
         “itemName”: “2012 SmartTV”,
         “itemState”: “false”
       },
       {
         “itemId”: “003”,
         “itemName”: “2013 SmartTV”,
         “itemState”: “true”
       }
     ]
  }
}

The preceding source code converts an XML result into a JSON type data.

jQuery ajax() can be supplied with different parameter values to format the response data.

jQuery.ajax(url, {
    type : ‘GET’,
    dataType : “json”,
    success: function(res) {
        var result = res.API.item;
    }
});

Optimizing API Requests

The Ajax request is a memory-intensive JavaScript process. Simultaneous Ajax requests from an application can cause device memory shortage that can result in a failed request or even halt the application.

Therefore, a developer needs to consider the preceding potential issue and be prepared for simultaneous multiple requests.

Minimize Number of API Requests

In a general web bulletin board, selecting a list item causes the application to make a new request for detailed data of the selected item using its key code. However, allowing this habit in the SmartTV application development and making a new request each time a scene changes may cause memory shortage. It is better to make a small number of comprehensive requests. See the following code for the API.

<?xml version=“1.0” encoding=“UTF-8”?>
<API>
    <item>
        <itemId>001</itemId>
        <itemName>The 2011 SmartTV</itemName>
    </item>
    <item>
        <itemId>002</itemId>
        <itemName>The 2012 SmartTV</itemName>
    </item>
    <item>
        <itemId>003</itemId>
        <itemName>The 2013 SmartTV</itemName>
    </item>

</API>

The preceding API requests a list of items. Each item's itemId key element is then used to make the next API request for an item's detailed information.

<?xml version=“1.0” encoding=“UTF-8”?>
<API>
    <item>
        <itemId>001</itemId>
        <itemName>The 2011 SmartTV</itemName>
        <itemState>false</itemState>
        <itemDate>2013-01-31</itemState>
        <itemTitle>false</itemState>
        <itemContent>Hello World</itemState>
    </item>
</API>

The preceding pattern is commonly used in standard web bulletin board development. Data requests completely rely on API design. And the preceding API design makes multiple API requests unavoidable. However, the next API design allows a single request to handle the preceding data access.

<?xml version=“1.0” encoding=“UTF-8”?>
<API>
    <item>
        <itemId>001</itemId>
        <itemName>The 2011 SmartTV</itemName>
        <itemState>false</itemState>
        <itemDate>2013-01-31</itemState>
        <itemTitle>false</itemState>
        <itemContent>Hello World</itemState>
    </item>
    <item>
        <itemId>002</itemId>
        <itemName>The 2012 SmartTV</itemName>
        <itemState>false</itemState>
        <itemDate>2013-01-31</itemState>
        <itemTitle>false</itemState>
        <itemContent>false</itemState>
    </item>
    <item>
        <itemId>003</itemId>
        <itemName>The 2013 SmartTV</itemName>
        <itemState>true</itemState>
        <itemDate>2013-01-31</itemState>
        <itemTitle>false</itemState>
        <itemContent>false</itemState>
    </item>
</API>

The first distributed API requests may help neat code management. But the preceding single request method is necessary for the application performance gain. The received response value can be stored within a DOM element, a Java Bean type object variable, or as an internal SmartTV file using the File API. The following code demonstrates storing response data in a DOM element.

jQuery.ajax(url, {
    type : ‘GET’,
    dataType : “json”,
    success: function(res) {
        var result = jQuery(res).find(‘API > item’);
        jQuery(‘#model’).eq(1).attr(‘itemDate’, result[1].find(‘> itemDate’).
text());
    }
});

Cache Optimization

Another technique of optimizing the API requests is using cache, which stores a result in a variable using a unique ID, and reuses the stored value the next time the same data is needed, instead of making a new request. This is highly useful in an application with frequent API requests. The following code declares a variable to store the results.

var cache = {};    // global variable

Then the Ajax result is paired with a unique ID and stored as a member property of the cache variable.

jQuery.ajax(url, {
    type : ‘GET’,
    dataType : “json”,
    success: function(res) {
        var result = jQuery(res);
        cache[‘0011AA’] = result;    // unique id = 0011AA
    }
});

The result variable holding the API response is stored under the cache variable. If another request for the same data is received, then the code uses the cached data without making a new server API request.

if (!cache[‘0011AA’]) {
    jQuery.ajax(url, {
        type : ‘GET’,
        dataType : “json”,
        success: function(res) {
            var result = jQuery(res);
            cache[‘0011AA’] = result;    // unique id = 0011AA
            callback(cache[‘0011AA’]);
        }
    });
} else {
    callback(cache[‘0011AA’]);
}

While the preceding code defines a static random ID, an ID management system needs to be implemented in a real application.

Cache optimization is a highly efficient technique that can eliminate many requests. However, it has its own limit on handling frequently updated data, since it reuses already stored data.

Summary

The Ajax request is the preferred method to access server-side data in a SmartTV application. The response data needs to be in an API structure such as XML or JSON. The resulting data needs to be formatted to suit the situation. The process also needs to be memory optimized to handle limited memory capacity of SmartTV devices.

..................Content has been hidden....................

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