IBM Worklight hands on lab: Advanced Worklight Techniques · 5 7. Worklight Studio will...
Transcript of IBM Worklight hands on lab: Advanced Worklight Techniques · 5 7. Worklight Studio will...
1
IBM Worklight hands on lab: Advanced Worklight Techniques
Table of contents
TABLE OF CONTENTS .................................................................................................................................................................. 1
INTRODUCTION .......................................................................................................................................................................... 1
ADAPTERS .................................................................................................................................................................................. 2
IMPLEMENTING ADAPTER INTO NEWS APP................................................................................................................................ 7
HOW TO USE AN ADAPTER .................................................................................................................................................................... 7
HOW TO GET ADAPTER RESULTS ............................................................................................................................................................. 8
JAVASCRIPT LOGGING ........................................................................................................................................................................... 8
BRINGING RESULTS TO USER ................................................................................................................................................................... 8
SKINS ........................................................................................................................................................................................ 11
Introduction Welcome to the second part of IBM Worklight lab. This part will show you how to prepare your applications for
communication with back-end systems and solve problem with various devices (with different screen sizes, user
input or HTML5 capability).
Lab will continue with development of an application News App created in first lab. Primary purpose of this lab isn’t
developing of demo application, but demonstration of how easily you can use Worklight features and implement
them into your own applications.
After completion of this lab you should have gained understanding of:
Use and implementation of Worklight Adapters
Purpose and usage of Worklight Application Skins
For full understanding of all steps you should possess basic knowledge of HTML, CSS and JavaScript. Familiarity with
the Eclipse platform and Firebug is a plus, but not required.
Firefox 13+ with Firebug 1.10+ http://www.mozilla.org/en-US/firefox/new/
http://getfirebug.com/
or
Chrome https://www.google.com/chrome
2
Adapters One of the most powerful tools in IBM Worklight portfolio is adapter. Nothing is more easy to use when you need to
integrate sophisticated systems with your application. Integration of web server, database or even complicated
systems through Cast Iron is very simple.
Main benefits of Adapters are:
Security – adapters offer control over the identity of the connected user. Adapter is a server side entity, so
no user can access adapter settings or source code. Application doesn’t receive any unsecure data.
Scalability – By using cache to store retrieved back-end data adapters reduce number of transactions
performed on back-end systems.
Transparency – Regardless of the adapter, data from back-end apps are exposed in a uniform manner.
Fast Development – Defined with simple XML, configured with JavaScript API.
Each Worklight adapter consists of:
XML file – describing connectivity options and adapter procedures
JavaScript file – containing the implementation of procedures declared in the XML file
XSL file (optional) – file(s) with transformation scheme for retrieved raw data
Data retrieved by an adapter can by returned raw or preprocessed by JS/XSL functions inside adapter. Output format
presented to the application is always a JSON object.
Let’s implement an adapter to enhance functionality of our News App:
1. First of all, open FirstWorklightProject in Eclipse IDE. Find blue Worklight icon on main Eclipse toolbar, click
and select Worklight Adapter from dropdown selection.
2. New Worklight Adapter dialog will pop-up. Select FirstWorklightProject, HTTP Adapter and write name of
our adapter “FeedReader”.
This adapter will download RSS feed from remote webserver in form of XML. Resulting JSON will be used later
in our application.
3
3. Worklight has automatically generated new folder /adapters/FeedReader. You can notice all three files
described on the beginning of this chapter – XML file with declaration of procedures and general info.
JavaScript file with implementation of procedures mentioned in XML file. And XSL file used for preprocessing
raw data returned from back-end services.
4. Now open the /adapters/FeedReader/FeedReader-impl.js file and notice, how prepared functions work. It’s
quite easy to understand. Most important part is input variable, which specifies several options of the
procedure. Most important ones are:
method: Mandatory, defines HTTP method used for request – “get” or “post”
returnedContentType: Type of HTTP content, overriding HTTP response mime type “css”, “csv”,
“html”, “javascript”, “json”, “plain”, “xml”, or any MIME-type
path: Mandatory, defines the path of the URL defining the HTTP service (first part of is defined in
Adapter XML file, path in this context is only last substring of whole path – for example
“api/getResult.php?id=3”).
All other properties can be found in Worklight Developer Reference Guide
(http://www.worklight.com/assets/pdf/Worklight%204.2.1%20Developer%20Reference%20Guide.pdf)
4
5. Now you can verify if procedures are working correctly by deploying them to the server and invoking them.
Right click on /adapters/FeedReader/FeedReader.xml file and select Run As > Invoke Worklight Procedure.
6. In newly opened window you can specify which procedure you want to test (in this case getStories
procedure from FeedReader adapter in FirstWorklightProject) and enter parameters divided by comma
(leave blank). Click Run and wait for the result.
5
7. Worklight Studio will automatically launch Firefox internet browser (if installed) and test your procedure. In
a few moments you should see the result and verify, if you’ve implemented the procedures correctly.
8. All deployed adapters can be inspected with Worklight Console – http://localhost:8080/console. When
clicked on Show details button, more details such as connectivity and procedures are revealed.
6
9. SELF-EXAMINATION: Create another adapter fetching remote RSS feed (of your choice) and verify its
functionality as shown in previous steps.
7
Implementing adapter into News App Right now you should have two prepared Adapters for future use. If not, please revise previous steps. Right now we
are going to use adapter as source of data, which will be displayed in the News Application.
1. Every time a new Worklight Application is created, Worklight Studio automatically creates a JavaScript file of
same name as application in <AppName>/common/js folder. In our case it is
NewsApp/common/js/NewsApp.js file. Please open it now.
2. As you can see, file is quite empty right now. Append following code:
function getNewsInit() { var invocationData = { adapter: "FeedReader", procedure: "getStoriesFiltered" }; var options = { onSuccess: loadFeedsSuccess, onFailure: loadFeedsFailure }; WL.Client.invokeProcedure(invocationData, options); }
How to use an Adapter
As you may see on the last line, Adapter procedure is invoked by WL.Client.invokeProcedure command. Parameters
are invocation data and options.
Invocation data consists of definition which Adapter and procedure is used. In this case it is FeedReader
adapter and getStoriesFiltered procedure. Invocation data variable may also contain array of parameters,
which are used during invoking of the procedure. It's a mandatory item, so in this case we won't specify any
parameters.
Options section contains specification of functions, which are launched after either successful or failed
adapter run.
Functions invoked after adapter successful or failed run differ in properties returned after (un)successful call.
Properties of a function invoked after successful procedure invocation:
status – the HTTP response status.
invocationResult – An object containing the data returned by the invoked procedure and also additional
information about the procedure run.
Properties of a function invoked after failed procedure invocation:
status – The HTTP response status.
errorCode – An error code returned as string. All error codes are defined in WL.ErrorCode object in
worklight.js.
8
errorMessage – Error message for developer use only. Not translated into user's language. Should not be
displayed to the end-user.
How to get Adapter results
Right now we are going to specify functions invoked after Adapter's procedure run. Insert following code at the
beginning of getNewsInit() function:
function loadFeedsSuccess(result) { console.log("Data sucesfully downloaded, HTTP " + result.status); if(result.invocationResult.Items.length > 0) { console.log("Server has returned " + result.invocationResult.Items.length + " item(s)"); displayRSSFeed(result.invocationResult.Items); } } function loadFeedsFailure(result) { console.log("Error while loading RSS feed: " + result.errorMessage); }
Important part is done on lines 4 and 6. Script checks, if adapter returned at least one result and subsequently
passes all returned data to function displayRSSFeed(), which will show received data to the user.
JavaScript logging
As you can see, most of the code is made of diagnostic reports
(console.log command). These reports can be viewed in JavaScript
console (Chrome browser contains built-in JS console and so does Firefox
with Firebug extension) by right clicking on page, selecting “Inspect
element” and opening a Console. This procedure in Chrome browser is
shown on next picture, usage in Firefox is very similar.
Bringing results to user
Finally it’s time to display obtained results from Adapter to the user. In this case we are going to use DoJo Object
Store component, which is a special data structure used in many DoJo components. Insert following code at the end
of /commons/js/NewsApp.js file:
function displayRSSFeed(rawData) { var store = new dojo.store.Memory({data:rawData, idProperty: "guid"}); require(["dijit/registry"], function(registry){ var newsList = registry.byId("newsList"); dojo.empty("newsList"); store.query(function(news){ var newsItem = dojox.mobile.ListItem({label:news.title}); newsList.addChild(newsItem); }); }); }
9
A brief explanation is in place:
1. We are using data provided by an Adapter to create an Object Store data structure. idProperty is unique
identifier of each item in store (line 2).
2. List newsList, which is supposed to display news to the user, is located (line 5).
3. All previous children elements of newsList are destroyed – including ListItem with “Work in progress…” label
(line 6)
4. Each item in store is iterated (line 8).
5. Creation of ListItem with current news name (line 9).
6. Newly created ListItem is subsequently added to newsList (line 10).
Almost there, now we need to start getNewsInit() function after Worklight is loaded. If you invoke an Adapter before
Worklight is loaded, it will result in an error. There is a special function called wlCommonInit(), which is launched
after Worklight initialization is complete. Insert getNewsInit(); into this function at the beginning of
/common/js/NewsApp.js file.
Almost last thing to do is set proper requirements in /common/NewsApp.html. Open this file and find DoJo require
section. Insert “dojo/store/Memory” – this statement tells DoJo, that you intent to use this element and it should be
ready for use.
10
Build and deploy whole application. After loading all the news it should look like this:
SELF-EXAMINATION: Try to work out how to make your ListItems with news clickable. User should be redirected to
news full version (supplied in news.link variable) after clicking on a news header.
HINT: Look at http://dojotoolkit.org/reference-guide/1.7/dojox/mobile/ListItem.html for useful information.
SOLUTION: Modify ListItem constructor to following appearance: var newsItem = dojox.mobile.ListItem({label:news.title, href:news.link});
11
Skins IBM Worklight has unique ability to support unlimited variance of devices. Worklight can offer user interface
specially built for target device. Typical use cases are:
Devices with different screen sizes, ratios and screen densities
Different input methods (touch screen x keyboard)
Devices with different level of HTML5 support
Skins are sub-variant of an environment. Skins are packed within a single executable file for devices with same OS.
Decision on which skin to use is done automatically at runtime. Decision logic can be fully customized and changed
during use of an application.
Probably most frequent case is when developer needs to achieve most effective display of information on phones
and tablet platform. For example on Android platform since version 3 developers may use Fragments to achieve
effective interface for both devices, but Worklight skin solution is much simpler and easier to implement.
Creating of a skin is very easy and can be done in few simple steps:
NOTE: Following Application Skin instructions may not be fully functional without Android SDK installed.
Functionality isn’t crucial for our sample application, so you can skip this section – but at least brief read-through is
recommended!
1. Verify, that you’ve already added Android as Worklight Environment – you should see android folder in
/apps/NewsApp. If not, add Android Environment by clicking Worklight icon in main Eclipse toolbar, select
Worklight Environment and select Android phones and tablets for current project (FirstWorklightProject).
12
2. If you’ve already added Android Environment, click again on Worklight icon in main Eclipse toolbar, click and
select Worklight Application Skin
3. In newly opened dialog, select FirstWorklightProject, NewsApp and Android phones and tablets. Set a
name for new Application Skin “android.phone”
4. Repeat step two and create new skin called “android.tablet”. Your Project Explorer should look like on
following picture:
13
5. Notice that both /NewsApp/android.phone and /NewsApp/android.tablet contains css, images and js
directories. Build priority (which resources are going to be used in first place) is determined by hierarchy in
/NewsApp/application-descriptor.xml file:
6. Build and deploy NewsApp by right-clicking /apps/NewsApp folder and select Run As > Build All and Deploy
14
7. Worklight will now warn you about empty android.phone and android.tablet folders, but don’t worry about
it for now. After successful deployment open FirstWorklightProjectNewsAppAndroid project and open
/assets/www/default/js/skinLoader.js file.
Notice the pre-defined functions and comments. You may notice how easy is to change app interface and/or
behavior based on OS version, screen resolution, device name, etc.