use apache derby in your openlaszlo applications, part 1

25
Use Apache Derby in your OpenLaszlo applications, Part 1: Supplying data using Derby Skill Level: Intermediate Tyler Anderson ([email protected]) Freelance Writer Stexar Corp. 21 Mar 2006 Since OpenLaszlo's open source announcement, many developers have been using OpenLaszlo to create user-friendly, rich Internet applications. Many of these applications require a database solution to have dynamic data fed to them. Because OpenLaszlo runs on Apache Tomcat by default, which in turn supports Java™Server Pages (JSP) and servlets (Java technology), Apache Derby is an excellent database to use. It can be embedded in such applications, and Derby is written in pure Java code. This tutorial uses an example of an online grocery store to illustrate the power of using OpenLaszlo with Apache Derby. Section 1. Before you start Learn how rich user interfaces (UIs) built with OpenLaszlo can use Apache Derby as their back-end database. The OpenLaszlo LZX markup language can use scripts written in several different languages to source the data used within OpenLaszlo applications. This tutorial focuses on the use of JSP, a standard Java-based scripting language supported by the out-of-the-box distribution of the OpenLaszlo application server. You'll test the system on the standard OpenLaszlo environment that includes OpenLaszlo running on Apache Tomcat with the Derby database being accessed via the Derby Network Server. About this series This two-part tutorial series documents the steps of how to build an OpenLaszlo application with Apache Derby as the back-end database. You use an example application -- an online grocery store that home consumers can connect to and order items from -- which exemplifies the strengths of using Derby in such a situation. The grocery store's employees can look up existing orders and modify stock. Derby is Supplying data using Derby © Copyright IBM Corporation 1994, 2007. All rights reserved. Page 1 of 25

Upload: vrbala

Post on 11-Apr-2015

500 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Use Apache Derby in your OpenLaszloapplications, Part 1: Supplying data using DerbySkill Level: Intermediate

Tyler Anderson ([email protected])Freelance WriterStexar Corp.

21 Mar 2006

Since OpenLaszlo's open source announcement, many developers have been usingOpenLaszlo to create user-friendly, rich Internet applications. Many of theseapplications require a database solution to have dynamic data fed to them. BecauseOpenLaszlo runs on Apache Tomcat by default, which in turn supports Java™ServerPages (JSP) and servlets (Java technology), Apache Derby is an excellent databaseto use. It can be embedded in such applications, and Derby is written in pure Javacode. This tutorial uses an example of an online grocery store to illustrate the powerof using OpenLaszlo with Apache Derby.

Section 1. Before you start

Learn how rich user interfaces (UIs) built with OpenLaszlo can use Apache Derby astheir back-end database. The OpenLaszlo LZX markup language can use scriptswritten in several different languages to source the data used within OpenLaszloapplications. This tutorial focuses on the use of JSP, a standard Java-basedscripting language supported by the out-of-the-box distribution of the OpenLaszloapplication server. You'll test the system on the standard OpenLaszlo environmentthat includes OpenLaszlo running on Apache Tomcat with the Derby database beingaccessed via the Derby Network Server.

About this series

This two-part tutorial series documents the steps of how to build an OpenLaszloapplication with Apache Derby as the back-end database. You use an exampleapplication -- an online grocery store that home consumers can connect to and orderitems from -- which exemplifies the strengths of using Derby in such a situation. Thegrocery store's employees can look up existing orders and modify stock. Derby is

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 1 of 25

Page 2: Use Apache Derby in Your OpenLaszlo Applications, Part 1

important here, because it's used to supply items for display to home consumersbrowsing the online grocery store and to update the stock count of purchased items.When the Derby database is updated with more stock or more items, the results arereflected in the online storefront built using OpenLaszlo.

This first installment focuses on reading a Derby database to feed data into anOpenLaszlo application. Part 2 extends the example application by adding amanager's interface into the storefront that enables an online store's employees toupdate the stock of items and add or remove items. Ultimately, you'll learn how toinsert, update, and delete from the Derby database using the OpenLaszlo LZXmarkup language. Then you can deploy the OpenLaszlo Web application on ApacheTomcat, completing the example.

About this tutorial

This tutorial chronicles the steps needed to create an example grocery application inOpenLaszlo and connect it to the Derby database to retrieve data. The exampleapplication is a UI for a simple online grocery store that allows users to browse anonline storefront whose data is supplied by a Derby database. Home consumersorder items they want to purchase and are told when their groceries will be deliveredto their doors.

Prerequisites

You need the following tools to complete this tutorial:

OpenLaszlo -- This tutorial uses the latest version of OpenLaszlo, version 3.1.Download OpenLaszlo 3.1, and get installation instructions for your operatingsystem.

Apache Derby -- Download Apache Derby, ensuring that the .jar files you receiveare added to your CLASSPATH.

IBM DB2® drivers -- Download IBM Cloudscape™ (IBM DB2 JDBC UniversalDriver, for Cloudscape/Derby) to connect to Derby. Make sure to add the drivers toyour CLASSPATH.

Java SDK -- OpenLaszlo, Apache Derby, and the DB2 drivers require the Javaplatform. This tutorial uses Java 1.4.2_09; however, any version later than thisshould suffice. Download the Java SDK from Sun Microsystems.

System requirements

This tutorial was written on a Microsoft® Windows® operating system, but thedifferences should be minimal, if any, if you're using a different operating system,such as Linux®.

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 2 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 3: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Section 2. Overview

This section gives a high-level overview of OpenLaszlo. It introduces you to theexample application you'll create in this tutorial and to where the Derby database fitsinto the application.

OpenLaszlo

Want to know what the latest and greatest in developing dynamic Web applicationsis? You've come to the right place. It all comes down to one word: OpenLaszlo.Laszlo Systems developed Laszlo as a startup, and because it's easy to use, muchlike Java programming using a markup language, and dynamic, like Ajax, LaszloSystems announced that their language would go open source. Thus, OpenLaszloemerged, and it has been taking off ever since.

Ajax, Flash, and OpenLaszlo

If you love the effects of programming in Ajax, then you'll love OpenLaszlo.OpenLaszlo gracefully abstracts away from the programmer the complications ofprogramming in Ajax. Not only that, but it incorporates the visual effects of Flash bycompiling OpenLaszlo application files down to Flash application files. You then getFlash and Ajax in an all-in-one bundle: OpenLaszlo.

Example grocery application

This tutorial introduces you to the wonderful world of easy Flash and Ajax through anexample grocery application. This example application is composed of a simpleonline storefront that has a dropdown box of all the available items in the store.Users can browse items in the store by selecting various items in the dropdown box.After the user has selected an item, the description and price asynchronously updateand display for that item. Clicking the Order button submits an order byasynchronously updating a label that displays back to the user that an order hasbeen successfully placed and the date the order will arrive at the user's door (seeFigure 1).

Figure 1. The example grocery application

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 3 of 25

Page 4: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Where Derby comes in

Apache Derby enters the example as an open source pure Java database thatsupplies the items of the online grocery store. The example application ultimatelygets the items it displays to the user in the combo box by querying the Derbydatabase via a script written in JSP.

Dynamic data and Derby

Derby helps make the application dynamic without having to modify the coreapplication. Instead, the script queries the Derby database (the contents of whichcan change with inserts, updates, and deletes at any time) and outputs XMLreadable by the OpenLaszlo application.

Section 3. The OpenLaszlo application server: Set up

Take a look at installing and testing the OpenLaszlo application server, which isimportant considering how it compiles LZX applications into Flash when they are

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 4 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 5: Use Apache Derby in Your OpenLaszlo Applications, Part 1

called by a browser.

Install the server

On Windows, installing the server is as simple as double-clicking the .exe file youdownloaded in Prerequisites. You'll find instructions for other operating systems inthe same Prerequisites section.

Also, start the server as shown in the instructions. You'll use the server throughoutthis tutorial in developing and testing your own OpenLaszlo application. In the nextsection you learn what an .lzx file is.

LZX files

The OpenLaszlo language is written in .lzx files. The language is written in its ownform of XML. You can use it to create buttons, text boxes, labels, and to specifyclasses, methods, and even inheritance, like Java code. Such enhancements to thelanguage make OpenLaszlo flexible and scalable.

In this tutorial, you write an OpenLaszlo application by naming your files with the .lzxextension. This tells the server to treat the file as an OpenLaszlo application file.

Next, you get a solid introduction -- using the Laszlo Explorer -- to several keyfeatures of OpenLaszlo.

Laszlo in 10 minutes

With the server up and running, you'll get a little familiar with Laszlo files and thevarious things you can do using OpenLaszlo.

The installation comes with a handy demo tool that allows you to look at andexperiment with basic OpenLaszlo features in real time. It shows you the sourcecode, which you're allowed to modify, and you can view the updated results inanother window.

The tool is called Laszlo Explorer. You can view it in your server by following the linkhttp://127.0.0.1:8080/lps-3.1/laszlo-explorer/index.jsp (see Figure 2). Click theLaszlo in 10 minutes panel on the left side. Now click the various subpanels, andexperiment with the language by modifying parts of the XML in the middle panel.Update the panel on the right, the output, by clicking the Update button below thepanel displaying all the XML.

Figure 2. Experimenting using Laszlo in 10 minutes

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 5 of 25

Page 6: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Now let's bring Derby into the equation.

Section 4. Derby: Set up

First, set up the Derby database, and get the DB2 .jar files in the right place forApache Tomcat.

Set up the OpenLaszlo application server for Derby

Because you'll be using the IBM DB2 JDBC Universal Drivers for this application,you need to copy them to the correct location for Tomcat so your application can useit in the connection process.

You should have already downloaded the drivers and added them to yourCLASSPATH. Next you need to copy them to Apache Tomcat's lib (library) directory:<OpenLaszloServer-install-dir>/Server/tomcat-5.0.24/common/lib.

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 6 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 7: Use Apache Derby in Your OpenLaszlo Applications, Part 1

This allows you to connect to the database via the Derby Network Server, which iscovered next.

Create the database

The database contains a table -- shoppingitems -- that stores the information onvarious items in your online grocery store. Before you create the database, however,start the Network Server by opening a console and type the following:

java org.apache.derby.drda.NetworkServerControl startIf you've added the Derby .jar files to your CLASSPATH successfully, the servershould come back by saying that it's ready to accept connections on port 1527.

Next you need to create the SHOPPING database. First, start up Derby's ij tool bytyping the following in a new console:

java org.apache.derby.tools.ijYou should now be at the ij prompt. There, create the database by typing:

connect'jdbc:derby:net://localhost:1527/SHOPPING;create=true:user=shopuser;password=shoppass;';You've just created the SHOPPING database with user, shopuser, and password,shoppass.

Create and initialize the shoppingitems table

In this panel, you create the shoppingitems table and initialize it by adding a fewitems to it. At the same console window you've been using, create theshoppingitems table by typing the following, as shown in Listing 1.

Listing 1. Creating the shoppingitems table

create table shoppingitems(itemid integer not null generated always as identity

(start with 1, increment by 1),name varchar(50),description varchar(255),price integer);

With the table created, add a few records to test your application. Type the following,as shown in Listing 2.

Listing 2. Initializing the shoppingitems table

insert into shoppingitems (name, description, price) values('Bread','Yummy whole wheat bread',3),('Tomato Soup','Expensive tomato soup',10),('Super Watermelon','This is a magical super watermelon. It can feed amillion families because of its mystical powers, hence the large

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 7 of 25

Page 8: Use Apache Derby in Your OpenLaszlo Applications, Part 1

price. Who would not want such a melon?',23498);

The table is now initialized, preparing the database for use by the OpenLaszloapplication you create next.

Section 5. Introducing OpenLaszlo

You can do several things in OpenLaszlo. This section gives a brief overview of themost common tags that you'll use.

Basic syntax and Hello World

As mentioned previously, the OpenLaszlo language is written in XML format with the.lzx extension. Every viewable .lzx file starts and ends with<canvas>...</canvas> tags. The simplest tag that displays anything is the<text> tag. Create your first OpenLaszlo Hello World application by creating aHelloWorld.lzx file and storing it in the following location:<OpenLaszloServer-install-dir>/Server/lps-3.1/my-apps/HelloWorld.lzx. Define it asfollows:

<canvas><text>Hello World</text></canvas>This creates a simple Flash object that displays the text Hello World (see Figure3).

Figure 3. Hello World

Notice that if you right-click the displayed text, you can see the options that appearfor Flash objects. The text is nonselectable, and images would also be

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 8 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 9: Use Apache Derby in Your OpenLaszlo Applications, Part 1

nonselectable if they were present. Thus, through Flash and OpenLaszlo, content ismore secure, because it can't be directly saved to hard drives.

Now learn more about other common tags that OpenLaszlo uses.

Standard tags

You use several tags in this tutorial. They are listed and described here:

Tag Description

splash While the Flash of your compiled Laszlo objectloads, the contents of this tag specify what isshown. If empty, a progress bar is displayed;otherwise, you can fill it with contents that getshown to users while the rest of the Flash objectloads.

dataset This tag can be used to specify data that yourproject will use for display, calculation, or anyother instances for which you might want to use adataset. In this tutorial, you use a dataset tospecify in your application which grocery storeitems are available and on sale to users. Thereare also several different ways to use datasets.You can either fill in the XML inline with the .lzxfile, source another file containing XML, orsource a script whose ultimate result is data inXML format.

simplelayout This defines the automatic layout of objects youdefine, meaning you can choose to have objectsthat you define automatically laid out along the xor y axis. For example, <simplelayoutaxis="x"> and <simplelayout axis="y">.The alternative is to choose the exact x and ylocation at which each object will be placed,which is rather tedious busywork. However, itmight be a nice option when the simplelayoutjust isn't enough.

script You can specify JavaScript functions within<script>...</script> tags. These functionsdo the automatic updating of various attributes inthe objects displayed by your OpenLaszloapplication. This tutorial uses JavaScriptfunctions to display when a successful order hasbeen placed and to update the description andprice fields when a new item has been selectedin the combo box.

form A <form>...</form> tag contains objects thata regular form holds in HTML. The next few itemsin the list are examples of such objects.

view These tags specify the bounding box, or view, ofobjects that a set of <view x="50"height="100">...</view> tags contain. In anutshell, they force the contained objects to a

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 9 of 25

Page 10: Use Apache Derby in Your OpenLaszlo Applications, Part 1

box specified by a width and height, and text orother data cannot overlap or be displayed out ofthe view's boundaries. However, you can usemethods to asynchronously change the widthand height of a view. The example above startsat pixel x and has a height of 100. Because thewidth is unspecified, it becomes the width of thecontained objects. You use this tag a few times inthis tutorial.

text The most common tag, it's like a label andcannot be edited via the UI. However, you canasynchronously modify the displayed text throughJavaScript.

combobox This tag displays several options in a dropdownmenu. The next item, a textlistitem,specifies what items are shown in the dropdownmenu.

textlistitem This object specifies what items to display in acombobox. You can list several of them within<combobox>...</combobox> tags. Thistutorial uses one of them and specifies that thedata be obtained from a dataset, whose dataultimately comes from the Derby database.

button A button is used to submit data to the system.Essentially, it calls a JavaScript method, passingin data from the form, and processes it. Thistutorial simply checks to make sure the data isvalid and that an item has been chosen, anddisplays back to the user on an empty label thatan order has been successfully placed.

menuseparator The menuseparator tag creates a framed lookto your UIs. It can help organize the layout of apage.

Next you learn about the methods and events.

Methods and events

Most objects fire events when clicked or selected. In this tutorial, you make use ofthe events from the textlistitem and the button objects. Take a look at somesample code embedded within <script>...</script> tags in Listing 3. Create afile, sample.lzx, and store it in the same location as your HelloWorld.lzx file.

Listing 3. Sample JavaScript embedded in an OpenLaszlo application

<canvas><script>

var ct = 0;function count(itemid) {ct = ct + 1;this.label.setText(ct);

}

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 10 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 11: Use Apache Derby in Your OpenLaszlo Applications, Part 1

</script>

<simplelayout axis="y"/><text id="label" width="20" height="17">0</text><button text="Submit" isdefault="true" onclick="count();"/>

</canvas>

The output of the application is that each time you click the Submit button, the labelkeeps track of how many times it has been pressed (see Figure 4).

Figure 4. Counting button presses

The thing that makes the user experience so rich is how its current virtual machine isthe JavaScript run time in Flash. This is similar to Ajax; however, it's much slickerhere in the Flash environment.

Next see how you can use datasets.

Datasets

Datasets allow you to feed data into your application, so let's look at how to embed adataset into the OpenLaszlo application. Later in the tutorial you'll read in an XMLfile, query a Derby database using JSP, form the result in XML, and then read thatinto the OpenLaszlo application. Look at the simple case first. Create another file,sample2.lzx, and define it, as shown in Listing 4.

Listing 4. Using datasets

<canvas><dataset name="dset">

<employee><name>John Smith</name><phone>555-555-5555</phone>

</employee><employee>

<name>Jane Smith</name><phone>555-555-5555</phone>

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 11 of 25

Page 12: Use Apache Derby in Your OpenLaszlo Applications, Part 1

</employee></dataset>

<combobox defaulttext="Choose an item ..." height="17" width="150"><textlistitem datapath="dset:/employee"

text="$path{'name/text()'}"/></combobox>

</canvas>

In the <dataset ..> tag, the name gets declared as dset. Notice that it's alsoused to specify the datapath for data in the textlistitem shown within thecombobox. View the file in the Web browser, and click the combobox. You'll get a listof things to click, as shown in Figure 5.

Figure 5. Feeding combobox data using a dataset

Now let's move on to the example application!

Section 6. The example application

In this section, you create a frame-based layout with the title on top and the grocerystore's order form underneath for the example grocery application.

Frames and including library files

You can create a framed-look page using the menuseparator tag. Create a file,index.lzx file, and define it, as shown in Listing 5.

Notice the title is simply text with a font size of 20. You can also change the font andstyle of the text. (See Resources later in this tutorial for helpful links and for the LZXreference manual.) Also, notice how you include another file. This is known as alibrary file, which you define next. Library files help to keep the code clean so that

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 12 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 13: Use Apache Derby in Your OpenLaszlo Applications, Part 1

you don't have to have everything in one file, as most, if not all, programminglanguages try to do.

Listing 5. Main index.lzx page

<canvas><text fontsize="20">Online Grocery Shopping Application</text><menuseparator width="600" height="6"/><splash/><include href="shopping.lzx"/>

</canvas>

Next you begin defining the shopping.lzx file.

The title frame

To view the current display of the index.lzx page, create a file, shopping.lzx, anddefine it, as shown in Listing 6.

Listing 6. Defining shopping.lzx file

<library>...

<simplelayout axis="y"/>

<script>...

</script>

<form>...

</form></library>

The simplelayout tag specifies that the auto-layout of your online shopping formwill display objects along the y-axis from top to bottom. Your JavaScript functions willgo in the <script>... </script> tags, and you'll define the form within the<form>...</form> tags.

Now look at the output of viewing the index.lzx file, as shown in Figure 6.

Figure 6. Sample browser output

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 13 of 25

Page 14: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Next you set up the dataset so that the combobox you'll create later will have data tofeed.

Set up the dataset

This dataset will contain the items for your online grocery store. Continue definingthe shopping.lzx file, as shown in Listing 7.

Listing 7. Defining the dataset

<library>...

<dataset name="dset"request="true" type="http"src="example.xml"/>

<simplelayout axis="y"/>...

The name field specifies the name of the dataset. You'll see how it's referenced laterin the tutorial. The request="true" field specifies that the dataset will make arequest to the source when it initializes. The type="http" field specifies that thefile be treated as a URL and not as a flat file. The src field specifies where to query,query.jsp in this case.

Next you define the example.xml file.

Build a dataset from XML

Here you build a dataset in XML that contains the example data you'll use to feedthe dataset. Create a file, example.xml, and define it, as shown in Listing 8.

Listing 8. Defining the example.xml file

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 14 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 15: Use Apache Derby in Your OpenLaszlo Applications, Part 1

<shopping><item>

<id>1</id><name>Bread</name><description>Yummy whole wheat bread</description><price>3</price>

</item><item>

<id>2</id><name>Tomato Soup</name><description>Expensive tomato soup</description><price>10</price>

</item><item>

<id>3</id><name>Super Watermelon</name><description>This is a magical super watermelon. It can feed a millionfamilies because of its mystical powers, hence the large price. Who would notwant such a melon?</description>

<price>23498</price></item>

</shopping>

Here's the XML file that sources the data into your OpenLaszlo application server.The value of the <id> tags need to be in order, because they're used in the eventhandling for the combobox, next.

Create the order form

The order form allows users that browse your Web site to view each of the items inyour store. Continue defining the shopping.lzx, as shown in Listing 9.

Listing 9. The simple shopping order form

...<form>

<simplelayout axis="y"/>

<view x="50" height="30"><text text="Shop Online" fontstyle="bold" fontsize="16"

width="150" height="30" id="shopLabel"/></view>

<view x="80" height="25"><text x="0" text="Item:" fontstyle="bold" width="100"/>

<combobox x="100" yoffset="17" defaulttext="Choose an item ..."width="240" editable="false" id="item" height="17">

<textlistitem datapath="dset:/shopping/item"text="$path{'name/text()'}" id="itemid"value="$path{'id/text()'}"onselect="getData(this.getValue())"/>

</combobox></view>

...

Notice that the form tag specifies its own simple layout along the y axis. Also noticethat there are several <view> tags. View tags give much more control over thelayout of the objects in your UI. The most interesting objects above are the objectsfrom the combobox down.

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 15 of 25

Page 16: Use Apache Derby in Your OpenLaszlo Applications, Part 1

The combobox specifies a default text when nothing is initially selected. Thetextlistitem references the dset dataset you created earlier. The text of eachtextlistitem item is taken from the name/text() of each item element(dset:shopping/item), as specified in the datapath field. Basically, each<name> child of an <item> is listed in the combobox. The value field is taken fromthe id/text() of each item element, which are numbered sequentially from 1 tothe number of <item> tags in the dataset. The value field helps match theselected record in the combobox with the record in the dataset, so that you can fill inthe description and price text boxes (see Listing 10). Finally, notice that whenan item in the combobox is selected, the onselect event fires off the getData()function, passing in the sequential number value of the chosen item in the dropdownmenu.

Listing 10. Defining text labels and button

...</combobox></view>

<view x="80" height="100"><text text="Description:" fontstyle="bold" width="100"

height="100"/><text id="description" x="100" width="240" height="100"

text="$path{'description/text()'}" multiline="true"/></view>

<view x="80" height="25"><text text="Price:" fontstyle="bold" width="100"

height="17"/><text id="price" x="100" width="240" height="17"

text="$path{'price/text()'}"/></view>

<view x="80" height="25"><text id="order" width="340" height="17" multiline="true"/></view>

<view x="80" height="25"><button text="Order" isdefault="true" x="282"

onclick="submitOrder();"/></view>

</form>...

Notice that the datapath values for the description and price <text> boxesare not defined. They'll get defined via JavaScript next. However, the text values aredefined. This means that whatever the dataset becomes, the description text boxwill pull out the value of the <description> element (description/text()).The same goes for the price <text> box.

The order label is empty and gets defined next via JavaScript through thesubmitOrder() function. Last, the button is defined, and when pressed, theonclick event fires off the submitOrder() function.

View the current sample output, as shown in Figure 7.

Figure 7. The simple grocery shopping form

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 16 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 17: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Next you dive into the JavaScript that defines the functions introduced in this panel.

Dynamic OpenLaszlo: JavaScript

This panel defines the JavaScript used to asynchronously update text boxes in theform. Continue defining the shopping.lzx, as shown in Listing 11.

Listing 11. Defining the JavaScript

...<script>

function getData(itemid) {datapath = 'dset:/shopping/item[' + itemid + ']'this.description.setDatapath(datapath);this.price.setDatapath(datapath);this.order.setText('');Debug.write(datapath);

}

function submitOrder() {this.order.setText('Thank you for your order! It will arrive in 1 to 2

hours.');}

</script>...

Remember that when an item in the combobox is chosen, the getData() function

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 17 of 25

Page 18: Use Apache Derby in Your OpenLaszlo Applications, Part 1

is called, passing in the sequential position number of the chosen item in thecombobox. Therefore, if the first item was chosen, a 1 would get passed to thismethod (the name of which is bread, as specified by the dataset in example.xmlfrom the Build a dataset from XML section). The datapath gets built, as shown inboldface above, being equal to dset:/shopping/item[1]. This selects the firstitem element from the dset dataset found in the example.xml file. Next, thedatapath of the description and price text boxes get set to this new value,and their displayed text becomes Yummy whole wheat bread and 3, respectively(see Figure 8).

Figure 8. Selecting an item

When the Order button gets clicked, the submitOrder() function gets called withno arguments passed as parameters. The result is that the order label gets set toThank you for your order! It will arrive in 1 to 2 hours (seeFigure 9).

Figure 9. Ordering an item

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 18 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 19: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Next, learn how to use Derby to feed your dataset.

Section 7. Tie in Derby

In this section, you use Derby -- instead of the currently defined example.xml file --as the dataset .

OpenLaszlo and scripts

Because OpenLaszlo allows scripts to be used as the source of the datasource,anything can be done to formulate a dataset. Not only that, but in your code you cancall any database. The crux is that the resulting data has to be formed into XML.You'll see how this works next.

Build a dataset using Derby as the datasource

Now you're going to define a script that connects to and queries the Derby database.Create a file, query.jsp, and define it, as shown in Listing 12.

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 19 of 25

Page 20: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Listing 12. Connecting to and querying the SHOPPING database

<%@ page import='java.io.*' %><%@ page import='java.util.*' %><%@ page import='java.sql.*' %><%@ page import='com.ibm.db2.jcc.DB2Driver' %><%

Driver driver = null;...

driver = (Driver)(DB2Driver.class).newInstance();

...Properties prop = new Properties();prop.put("user", "shopuser");

prop.put("password", "shoppass");Connection conn = driver.

connect("jdbc:derby:net://localhost:1527/SHOPPING;",prop);

String sql = "select * from shoppingitems";PreparedStatement statement = conn.prepareStatement(sql);

ResultSet results = statement.executeQuery();...

First you import the necessary classes, shown in the first four lines. Next, you createa driver instance of the DB2 JDBC Universal Driver, and then you set up theproperties and create a connection to the SHOPPING database. Last, you create aquery, select * from shoppingitems and execute it. The results of the queryare now stored in the results variable.

Next you output these in XML format, which is readable by your OpenLaszloapplication.

Write the XML

Now that you have the records from the shoppingitems table in the SHOPPINGdatabase, it's time to create the XML. Continue defining the query.jsp file, as shownin Listing 13.

Listing 13. Writing the query results to XML

...ResultSet results = statement.executeQuery();

String name, desc, price;int id = 1;

out.write("<shopping>\n");while(results.next()){

out.write(" <item>\n");name = results.getString("name");desc = results.getString("description");price = results.getString("price");out.write(" <id>" + id + "</id>\n");out.write(" <name>" + name + "</name>\n");out.write(" <description>" + desc + "</description>\n");out.write(" <price>" + price + "</price>\n");

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 20 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 21: Use Apache Derby in Your OpenLaszlo Applications, Part 1

out.write(" </item>\n");id++;

}out.write("</shopping>\n");

...

Here you create the root of the XML document, <shopping>, and an <item>element for each of the results in the query. Notice that the <id> tag is 1 for the firstresult, 2 for the second, and so on. This is used to match the value of the comboboxto the actual record in the dataset, as mentioned in the Create the order form panel.The name, description, and price values each get their own XML tags, and theXML document is completed when all the records have been looped through andwritten to XML. The last tag to be written (</shopping>) closes the XMLdocument.

Error handling

Now for a bit of error handling in handling the query just in case something goeswrong while writing or modifying the code. Continue defining the query.jsp file, asshown in Listing 14.

Listing 14. Handling errors

...try {

driver = (Driver)(DB2Driver.class).newInstance();

} catch(Exception e) {throw new IllegalArgumentException("Unable to load, " +

"instantiate, or register driver " + driver +": "+e.getMessage());

}

try {Properties prop = new Properties();

...out.write("</shopping>\n");

} catch(Throwable e) {e.printStackTrace();System.out.println(e.getMessage());System.out.println("Error executing query");out.write("error");

}%>

The additions here are marked in boldface. If the driver doesn't work, you'll knowfrom the first try-catch statement. If you experiment with SQL that doesn't workand you create an ill-formed query, you'll know from the last try-catch statement.This will help you debug your JSP script. (See Resources later in this tutorial formore on SQL and Derby.)

Next, test your script to see if the output is correct.

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 21 of 25

Page 22: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Test your script

Test your script before it goes live with your OpenLaszlo application. Open yourbrowser, and point it to your JSP script. See the example output, as shown in Listing15 (you may have to view the source to see the properly formatted XML).

Listing 15. Example query.jsp output

<shopping><item>

<id>1</id><name>Bread</name><description>Yummy whole wheat bread</description><price>3</price>

</item><item>

<id>2</id><name>Tomato Soup</name><description>Expensive tomato soup</description><price>10</price>

</item><item>

<id>3</id><name>Super Watermelon</name><description>This is a magical super watermelon. It can feeda million families because of its mystical powers, hence the largeprice. Who would not want such a melon?</description>

<price>23498</price></item>

</shopping>

The results are the same as the example.xml file. Good job! Next you modify theshopping.lzx file to have it source your JSP Derby script.

Modify the OpenLaszlo application

To modify your OpenLaszlo application to source your new JSP Derby script, ratherthan the static example.xml file, modify the <dataset> tag in your shopping.lzx tag,as follows:

<dataset name="dset"request="true" type="http"src="query.jsp"/>That's it! Your OpenLaszlo application will now source your new JSP script and getits data directly from the Derby database (see Figure 10).

Figure 10. Viewing the changes in the final application

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 22 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 23: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Thanks for following along!

Section 8. Summary

You're learning that you can use Apache Derby with more applications than youmight have realized! You've successfully accessed and read data from a Derbydatabase into your OpenLaszlo application. Come back and see Part 2 of this series,where you'll build a manager's interface into the online grocery store. Plus, you'lllearn how to write to the Derby database, including new orders, and add or edititems from your OpenLaszlo application. And finally, you'll deploy your fullOpenLaszlo application on Apache Tomcat.

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 23 of 25

Page 24: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Downloads

Description Name Size Download method

Part 1 source code derbylaszlo1source.zip3KB HTTP

Information about download methods

developerWorks® ibm.com/developerWorks

Supplying data using DerbyPage 24 of 25 © Copyright IBM Corporation 1994, 2007. All rights reserved.

Page 25: Use Apache Derby in Your OpenLaszlo Applications, Part 1

Resources

Learn

• Join the OpenLaszlo rave at laszlosystems.com and openlaszlo.org.

• Get instructions for installing OpenLaszlo.

• Refer to the OpenLaszlo LZX Reference Manual .

• Peruse additional OpenLaszlo documentation.

• Be sure to read this tutorial on building rich Internet applications(developerWorks, December 2005).

• Get documentation from the OpenLaszlo Wiki.

• Visit Dan Hopkin's Web site, an excellent OpenLaszlo resource (browse topicson left panel).

• View documentation on Apache Derby.

• Check out the SQL language reference from IBM for good SQL documentation.

• Check out the developerWorks Apache Derby project area for articles, tutorials,and other resources to help you get started with Derby today.

• Visit the Apache Derby Project Web site.

• Browse for books on these and other technical topics at the Safari bookstore.

Get products and technologies

• Try out the Eclipse IDE for OpenLaszlo.

• Download the Apache Derby 10.1.2.1 release.

Discuss

• Get involved in the developerWorks community by participating indeveloperWorks blogs.

About the author

Tyler AndersonTyler Anderson formerly worked for DPMG.com, an SEO company, for whom hewrote proprietary SEO software. He graduated with a degree in computer sciencefrom Brigham Young University in 2004 and has just graduated with a Master ofScience degree in Computer Engineering in December 2005, also from BrighamYoung University. He is currently an engineer for Stexar Corp., based in Beaverton,Oregon. You can reach Tyler at [email protected].

ibm.com/developerWorks developerWorks®

Supplying data using Derby© Copyright IBM Corporation 1994, 2007. All rights reserved. Page 25 of 25