Developing zero.suggest.demo with the IBM WebSphere sMash application builder

来源:百度文库 编辑:神马文学网 时间:2024/04/30 12:32:37
Project Zero
About
Community
Documentation
Download
Developer‘s Guide
Developing a data-to-Web application (zero.suggest.demo)
Developing zero.suggest.demo with the IBM WebSphere sMash application builder

Topics:
Developing zero.suggest.demo with the IBM WebSphere sMash command-line interface
|
NONE
Modules:
Developer Web tools
|
Employee demo
Developing zero.suggest.demo with the IBM WebSphere sMash application builder
This tutorial provides an introduction to the Zero ResourceModel (ZRM) and the JavaScript library, including developing zero.suggest.demo with the WebSphere sMash application builder.
The following concepts are presented in this tutorial:
the automatic creation of databases from resource model definitions
the initialization of database tables with JSON documents
the RESTful API that allows clients to list, filter, retrieve, create, update, and delete data with ZRM, and
the use of Dojo-based widgets that allow client programmers to expose ZRM data with a few lines of JavaScript.
The sample application used for this tutorial will allow users to submit suggestions and vote for the product code name.Users will be able to authenticate with a simple ID and password combination and then see all of thecurrent name proposals, as well as the number of votes each has received. For the sake of brevity, we will not implementrestrictions on how many times a user can vote; our main goal is to show how to store data with ZRM and then exposeit on the client side with Dojo‘s data store and grid concepts.
Creating the Server-Side Code
Create a new IBM® WebSphere® sMash application, named for example zero.suggest.demo. With your web browser pointed to the WebSphere sMash Application Builder (http://localhost:8070), click Create Application > New and enter zero.suggest.demo for the application name. Be sure to note the directory you selected for saving the application. Click Create, Click on the zero.suggest.demo and you will be brought to the all files view.
Create a resource model definition. We will define one resource type, called suggestions, that will map to one database table; each suggestion will have a product name, a submitter name, and the number of votes it has received. You can create the resource model by clicking the New File link to create a file named /app/models/suggestions.json (creates a file relative to the application directory).
You will be prompted to add the zero.resource dependency, click Add to add the zero resource model support to your application.
Enter the following content in the edit area:
{
"fields": {
"suggestion": {
"type": "string",
"max_length": 128
},
"submitter": {
"type": "string",
"max_length": 64
},
"votes": {
"type": "integer"
}
}
}
Each field in the suggestions type has an associated data type (string, integer, etc.) and, in the case of strings, a length. ZRM will use this definition file to create the database table definition and execute the proper SQL CREATE statement for it.
Add sample data. We can populate the suggestions table with some default or sample data using another JSON document. Create a file named /app/models/fixtures/initial_data.json
Enter the following content in the edit area:
[
{
"type": "suggestions",
"fields": {
"suggestion": "WebSphere Zero",
"submitter": "dan",
"votes": 14
}
},
{
"type": "suggestions",
"fields": {
"suggestion": "WebSphere2.0",
"submitter": "bob",
"votes": 25
}
},
{
"type": "suggestions",
"fields": {
"suggestion": "WebSphere X",
"submitter": "sue",
"votes": 18
}
}
]
As you can see, each item in the JSON array is an instance of the suggestions type, and each has values for the three fields in that type. In a later section, we will create the security rules for our application and create some sample user accounts to match the submitter names shown here.
Enable the REST API for the ZRM-based resource. Without this step, ZRM will build and maintain your database, but you will not be able to read and write the data over HTTP (GET, POST, etc.). create a file named /app/resources/suggestions.groovy
Enter the following content in the edit area:
ZRM.delegate()
This one line of code will enable all of the LCRUD operations (list, create, retrieve, update, and delete) over HTTP for both collection and member URIs (/suggestions and /suggestions/{id}, respectively).
Tell ZRM to create and populate your database. Click the Console tab, Click Command Prompt and in the command box type the following command and click Enter
zero model sync
When the model sync command has finished, the suggestions database will be created and populated with the initial data we provided earlier.
Test the REST API. We have not added security or a user interface, but we can still do some initial tests to ensure that things are working so far.
Note: Make sure you stop any existing WebSphere sMash applications that are running on the default port of 8080 before attempting to start the zero.suggest.demo, which also uses port 8080 by default.
Start the zero.suggest.demo application by clicking the Run link at the top right of the screen and then point your favorite web browser tohttp://localhost:8080/resources/suggestions; you should receive a JSON file that has the three suggestions we put in /app/models/fixtures/initial_data.json. Once you‘ve confirmed this, you can stop the application by clicking Stop.
Creating the voting application
Create the web interface for your ZRM data. The crux of our UI development will be a WebSphere sMash DataGrid widget and a ZRM-based data store. The ZRM data store will read and write data from our REST API.
The ZRM data store that will act as the backend for the DataGrid widget is part of a component named zero.dojo.
To get started on the web interface, create a file named public/secure/index.html, we will put in a secure directory which we will add authentication to later. Once the file is created the visual page editor will be displayed.
To create the Dojo data store using ZRMStore, click the Data tab, then click New > ZRMStore.
You will be prompted to add the zero.dojo dependency, click Add to add the zero dojo widgets to your application. (Note: if your application is still running at this point, you will need to stop and re-start your application by click Stop and clicking Start so the new dependency will be picked up)
click New > ZRMStore then Enter thestore for the variable name and / for the base URL and click Ok
To create the DataGrid widget, click the Create tab, and scroll down the pallet until you see the Zero section. Click and drag the DataGrid widget on to the canvas. The data grid will be rendered on the screen withs some sample column names and data.
Click the data grid to select it, then Right Click Properties. Fill in the properties dialog as shown here:

The store attribute hooks the grid widget to the data store; the query attribute has the /resources/suggestions URI that will be used by ZRMStore to perform LCRUD operations on the collection and member resources. Wrapping the ZRM data store in the DataGrid type will enable the Dojo grid widget to connect with it rather seamlessly.
You may now test your application by visiting thehttp://localhost:8080/secure URL, you should see the table rendered with the sample data we specified initial_data.json
Adding functions to the voting application
What we have so far allows us to load a grid (table) on a page with the latest suggestion and voting data, but it doesn‘t let the user make new suggestions or vote. To do those things, we will need to add some UI controls and respond to their actions with JavaScript.
We will first provide a way for users to vote. This action requires that the user first select (single-click) an item in the grid and then click the Vote button. Create a vote button by dragging the button widget from the palette on to the canvas. Select it and Right Click Properties and give the button a label like "Vote for selected".
Select the button again, Right Click Events. With the Click tab selected, click the + Icon and select Script. Enter the following Javascript code and click Ok:
var thegrid = dijit.byId("thegrid");
var rows = thegrid.grid.selection.getSelected();
if (rows.length != 1) {
alert("select one row!");
} else {
var item = thegrid.grid.model.getRow(rows[0]).__dojo_data_item;
thestore.setValue(item, "votes", ++item.votes);
thegrid.grid.selection.clear();
thestore.save({onComplete:function () {thegrid.onSaved();}, onError:function () {alert("error");}});
}
This code retrieves the current data selected by the user, increments the vote count, and saves the data on the server. In our simple scenario, we have not handled synchronization of vote counting or prevented users from voting multiple times.
We will now provide a way for users to add their own suggestion. Create a form by dragging the form widget on to the canvas, select the form and Right Click Properties set the id and name fields to newform.
Create a couple of text boxes one for the suggestion and one for the name of the submitter, by dragging the Text Box widget from the palette on to the form widget (placed previously on the canvas). Do so twice so you are left with 2 text boxes inside a form. Select text box, Right Click Properties set the name and id of one text box to Suggestion and the other to Submitter.
Add labels to the text boxes by scrolling down to the HTML section of the pallete and dragging the Label widget on to the canvas in front of the text box you want to label. Set the text of the label by Right clicking Properties and typing the in the Text value as:
Enter Suggestion
Enter Submitter Name
Create a submit button by dragging the button widget from the palette on to the canvas. Select it and right click Properties and give the button a label as "Submit".
Select the button again, right click Events. With the Click tab selected, click the + Icon and select Script. Enter the following javascript code and click Ok:
var newitem = {};
newitem.submitter = document.newform.submitter.value;
newitem.suggestion = document.newform.suggestion.value;
newitem.votes = 0;
var thegrid = dijit.byId("thegrid");
thegrid.grid.addRow(newitem);
thestore.save({onComplete:function () {thegrid.onSaved();}, onError:function () {alert("error");}});
Note: later when we add authentication we can hide the submitter field and use the authenticated user name.
Test the UI. Restart the WebSphere sMash application if you had previously stopped it, and then visithttp://localhost:8080/secure in your web browser. The initial load may take a few seconds, but will be more responsive on subsequent actions. Below is a screenshot of the page we‘ve built:

You can now experiment with the add and vote functions and watch the data update in the grid; to confirm that everything is really working, you can vote in the web interface and then read the updated suggestion data using the REST API (/resources/suggestions).
Adding User Authentication for Server-Side Code
Enable HTTP basic authentication for the REST API. This will ensure that only registered users can read and write our suggestion data, whether they use our web interface or their own HTTP client. You can limit use of the REST API to authenticated users by adding the following security rule definition to the config/zero.config file:
@include "security/rule.config" {
"authType": "Basic",
"conditions": "/request/path =~ /resources/.+",
"groups": ["ALL_AUTHENTICATED_USERS"]
}
The @include that starts this rule defines all of the default key-value pairs for a WebSphere sMash security rule; we then customize the rule as needed. The trigger that causes our rule to be enforced is a request URI that begins with /resources; this value is represented in WebSphere sMash‘s global context as /request/path, which explains the pattern-matching expression on the third line. The final line uses a special value (ALL_AUTHENTICATED_USERS) to limit usage to any registered user without dividing users into specialized groups.
Add sample users. By default, authentication is handled with a file-based service that reads and writes user account data to a file named config/zero.users. Below is a sample zero.users file that contains the three submitter names we saw in our sample data, each with the password set to mypassword:
dan:34819d7beeabb9260a5c854bc85b3e44:
bob:34819d7beeabb9260a5c854bc85b3e44:
sue:34819d7beeabb9260a5c854bc85b3e44:
You should reuse this zero.users file at first so that you can test the security settings and web interface. You can later add or remove user accounts using the WebSphere sMash CLI (type zero help users for more information).
Enable form-based authentication for the web interface. The REST API is protected by basic authentication, but we will need something slightly different for the web interface implemented under public. Add the following stanzas to the config/zero.config file:
@include "security/rule.config" {
"authType": "Form",
"conditions": "/request/path =~ /secure(/.*)?",
"groups": ["ALL_AUTHENTICATED_USERS"]
}
@include "security/form.config" {
"formLoginPage": "/index.html"
}
The first stanza is similar to the security rule that enabled basic authentication: it says that all request URIs that start with /secure will be protected by an HTML login form. We will put all user interface elements that are protected under the public/secure directory to match this rule. The only non-protected element we will have is described in the second stanza, where we define the login page that will be used for all clients that need to authenticate.
Re-test the REST API. Restart the zero.suggest.demo application and try to reload thehttp://localhost:8080/resources/suggestions URL. You should not be able to read the JSON data until you have entered one of our user names (dan, bob, or sue) with the password mypassword.
Provide the login form. You should create a file directly under the application‘s virtual root: public/index.html, when using the IDE use the source tab hand code the form, or you may use the widgets to create the form yourself (see the zero.suggest.demo as completed by the author). This file should contain the default login form used for WebSphere sMash applications; note the names of the ID and password input fields and do not change them:













User Name
Password





The zeroUserName and zeroPassword names are standard names used by WebSphere sMash Core to process login forms without any additional programming or configuration by the user. Also notice the hidden field named postLoginTargetURI, which tells WebSphere sMash Core to which page the user should be sent after he is authenticated. In our case, we are going to the root of the secure area, public/secure/index.html.
We will now change the /public/secure/index.html to use the authenticated user name, but first let us create a simple groovy script to provide the user name. Create a new file called /public/secure/getuserid.groovy and add the following code:
def onGET() {
def userid = request.subject.remoteUser[]
request.view = ‘JSON‘
request.json.output = [userid: userid]
render()
}
This simple script will return the logged in user id in a JSON response we can use in the index.html.
Now open the /public/secure/index.html by clicking it in the recent files list. In visual page editor, when no widgets are selected the page is selected. So click on the canvas to unselect any selected widget and select the page. Right Click Events, in the Load tab click the + icon and select Service Call. This will create an onLoad event which will call a service (the groovy script we just created). Enter getuserid.groovy for the URL, JSON for Type, and GET for Method. Then click the + icon to the right of Result, and enter userid for Name, select String and for Target enter submitter.value and click Ok.
Now we have created a service call to the getuserid.groovy script and wired the result of that service invocation to set the value of the submitter text box. All that is left to do now is hide the submitter text box and remove the labelEnter Submitter Name we created for the submitter text box.
Select the submitter text box, right click Styles in display select none and click Ok.
Finally, select the Enter Submitter Name label and right click the delete button. You are now finished with the application coding. Test the UI. Restart the WebSphere sMash application if you had previously stopped it, and then visithttp://localhost:8080/secure in your web browser.
You will prompted for your user name and password, Enter User Name(bob, dan, sue) and Password (mypassword)
Below is the screen shot once you logged in
Conclusion
This tutorial showed how to model a resource type using ZRM, createa database to represent it, and expose the data with a RESTful API. Wewere then able to read and write that data from a web browser with afew lines of JavaScript thanks to the Dojo Toolkit and WebSpheresMash‘s own ZRMStore class. The ease with which we can model a resource type and connect to it from a client allows anyone to buildquick prototypes that serve as the foundation for a complete application.
If you wish to see the zero.suggest.demo application as completed by the author, you can get it from the WebSphere sMash Application Builder byselecting Create Application > Copy From Repository and entering zero:zero.suggest.demo. The IDE willcopy the latest version of zero.suggest.demo to your machine and resolve its dependencies, at which point you can readthrough its files, modify them, and run the application.
Copyright 2008 ©IBM Corporation.

Version 1.0.0.1.20312

360doc_1