Está en la página 1de 870

Front cover

WebSphere Studio
Application Developer
Version 5 Programming Guide
Develop Java, Web, XML, database, EJB,
and Web services applications

Test with built-in and remote


servers

Deploy to WebSphere
Application Server

Ueli Wahli
Ian Brown
Fabio Ferraz
Maik Schumacher
Henrik Sjostrand

ibm.com/redbooks
International Technical Support Organization

WebSphere Studio Application Developer Version 5


Programming Guide

July 2003

SG24-6957-00
Note: Before using this information and the product it supports, read the information in
“Notices” on page xix.

First Edition (July 2003)

This edition applies to Version 5 of WebSphere Studio Application Developer and WebSphere
Application Server.

This book is a rewrite of the IBM Redbook, WebSphere Studio Application Developer
Programming Guide, SG24-6585, which was based on Version 4 of the products.

© Copyright International Business Machines Corporation 2003. All rights reserved.


Note to U.S. Government Users Restricted Rights -- Use, duplication or disclosure restricted by GSA ADP
Schedule Contract with IBM Corp.
Contents

Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
The team that wrote this redbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii
Become a published author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Comments welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv
Summary of changes from SG24-6585 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
July 2003, First Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv

Part 1. Introducing WebSphere Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 1. Introduction and concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Platform architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Workbench features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Plug-in based tooling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Role-oriented development with consistent look and feel . . . . . . . . . . . . . . . 7
Vertical and horizontal integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Open standards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Open team development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
File-based IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
WebSphere Studio products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
What is new in Application Developer Version 5 . . . . . . . . . . . . . . . . . . . . . . . 11
Migration from previous versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Web development tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Relational database tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
XML tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Java development tools (JDT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Web services development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
EJB development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Team collaboration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Debugging tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Performance profiling tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Server tools for testing and deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Plug-in development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Sample code in this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

© Copyright IBM Corp. 2003. All rights reserved. iii


EJBBANK database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Naming convention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Chapter 2. Setting up your Workbench and workspace preferences . . . . 21


Workbench basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Workspace basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Application Developer’s log files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Automatic builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
File associations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Local history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Perspectives preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Internet preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Java development preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Java classpath variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Appearance of Java elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Code formatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Compiler options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Java Editor settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Installed JREs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Javadoc documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Organize imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Chapter 3. Perspectives, views, and editors. . . . . . . . . . . . . . . . . . . . . . . . 47


Integrated development environment (IDE) . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Application Developer help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Perspectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Perspective layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Switching perspectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Specifying the default perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Organizing and customizing perspectives. . . . . . . . . . . . . . . . . . . . . . . . . . 54
Perspectives walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
J2EE perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Resource perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Web perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Java perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Java Browsing perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

iv WebSphere Studio Application Developer Version 5 Programming Guide


Java Type Hierarchy perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Server perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
XML perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
XSL Debug perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Data perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Debug perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Profiling perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Component Test perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
CVS Repository Exploring perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Install/Update perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Plug-in Development perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Chapter 4. Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
J2EE architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Web containers and EJB containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
EAR files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
WAR files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
JAR files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Projects and folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Application Developer’s project types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Simple project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Java project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Enterprise Application project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
EJB project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Application Client project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Server project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Creating a new project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Project properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Using templates to create application projects . . . . . . . . . . . . . . . . . . . . . . . . . 88
Running the Application Template Wizard . . . . . . . . . . . . . . . . . . . . . . . . . 88
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Part 2. Developing applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Chapter 5. Developing Java applications . . . . . . . . . . . . . . . . . . . . . . . . . . 93


Creating and working with a Java project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Creating a Java project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Creating Java packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Creating Java classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Running your programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Exporting code and running outside Application Developer . . . . . . . . . . . 106
Locating compile errors in your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

Contents v
Debugging your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Preparing a utility project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Banking model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Importing the implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Testing the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Programming assists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Pluggable JDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Java Scrapbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Code assist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Navigating through your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Import generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Tasks view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Code generation actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Smart compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Java search and working sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Bookmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Generating Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Using Ant to generate Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

Chapter 6. Developing database applications . . . . . . . . . . . . . . . . . . . . . 139


JDBC overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Data source versus direct connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Application Developer database operations . . . . . . . . . . . . . . . . . . . . . . . . . . 142
XMI and DDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Data perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
DB Servers view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Data Definition view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Navigator view. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Using the DB Servers view. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Creating a database connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Importing database objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Generate DDL and XML schema files. . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Creating database objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Create database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Create schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Create table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Create table with foreign key. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Define the database schema in a database system . . . . . . . . . . . . . . . . . 163

vi WebSphere Studio Application Developer Version 5 Programming Guide


Creating SQL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Using the SQL Statement Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Using SQL Query Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Accessing databases from a Java application . . . . . . . . . . . . . . . . . . . . . . . . 174
Access using the DriverManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Access using a data source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
J2EE client application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

Chapter 7. Developing Web applications . . . . . . . . . . . . . . . . . . . . . . . . . 179


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Sample application: RedBank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Facade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Application flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Creating a Web project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Adding the banking model as a utility JAR . . . . . . . . . . . . . . . . . . . . . . . . 188
Module dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Project properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Web project directory structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Importing existing resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Creating static Web resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Create a simple HTML page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Using the Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Using the CSS Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Creating dynamic Web resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Working with servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Working with JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Creating a server for testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Testing the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Working with filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Creating a filter in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 227
Editing the filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Working with listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Creating a listener in Application Developer . . . . . . . . . . . . . . . . . . . . . . . 233
Editing the listener. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Creating Web pages from a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Completing the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Tailoring the generated files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Running the generated application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

Contents vii
Chapter 8. Developing Web applications with database access . . . . . . 247
Accessing databases from a Web application . . . . . . . . . . . . . . . . . . . . . . . . 248
Creating a Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Generate Web pages from SQL queries . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Defining a data source in the server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Testing the database application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Accessing a database using DB Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Creating a JSP using DB Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Accessing a database using JSP taglib . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270

Chapter 9. Developing applications with stored procedures . . . . . . . . . 271


What is a stored procedure? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Creating a Java stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Importing the database definition into a Web project . . . . . . . . . . . . . . . . 272
Using the Stored Procedure Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Building the stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Executing the stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Accessing a Java stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Using a main program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Generate a JavaBean to access the stored procedure . . . . . . . . . . . . . . . 281
Using the JSP tag library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Generate JavaBean Web pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Creating a stored procedure with multiple statements . . . . . . . . . . . . . . . . . . 287
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292

Chapter 10. Developing Struts applications . . . . . . . . . . . . . . . . . . . . . . . 293


What is Struts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
MVC architectural pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Dependencies between MVC layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
MVC framework with Struts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Application Developer support for Struts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Developing a Web application using Struts . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Creating a Struts Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Copying the facade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Importing RedBank Web content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Updating ApplicationResources.properties . . . . . . . . . . . . . . . . . . . . . . . . 306
Creating the Struts Web diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Implementing the Struts Web diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Developing the form beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310

viii WebSphere Studio Application Developer Version 5 Programming Guide


Developing the JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Developing the actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Using the Struts configuration file editor . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Testing the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

Chapter 11. Developing XML applications . . . . . . . . . . . . . . . . . . . . . . . . 345


XML overview and technologies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
XML and XML processor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
DTD and XML schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Schema and style using XSLT and XSL . . . . . . . . . . . . . . . . . . . . . . . . . . 347
XML namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
XPath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Application Developer XML tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Tools demonstrated in this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Setting up your sample project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Creating a new XML file from scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Creating an XML schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
XML generators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Generating a DTD from XSD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Validate XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Generating an XML file from an XML schema . . . . . . . . . . . . . . . . . . . . . 359
Creating an XSL file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Transforming XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Debugging XSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Generating JavaBeans from DTD or XSD . . . . . . . . . . . . . . . . . . . . . . . . 371
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372

Chapter 12. Developing EJB applications. . . . . . . . . . . . . . . . . . . . . . . . . 373


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
EJB server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
EJB container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
EJB components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Sample Application: RedBank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Creating an EJB project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Data transfer objects and helper classes . . . . . . . . . . . . . . . . . . . . . . . . . 388
Implementing the model with entity beans . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Creating the entity beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Editing the entity beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Creating entity relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
Updating the TransRecord create method . . . . . . . . . . . . . . . . . . . . . . . . 404
Creating custom finders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406

Contents ix
Object-relational mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Implementing the session facade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Creating the session bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Creating an EJB reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
Editing the session bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Generating the deployed code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Completing the EJB deployment descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Changing the data source for EJB access . . . . . . . . . . . . . . . . . . . . . . . . 428
Testing the EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Universal test client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Adapting the Web applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Web project dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
EJB references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
Testing the Web interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440

Chapter 13. Developing Web services. . . . . . . . . . . . . . . . . . . . . . . . . . . . 441


The concept of a service-oriented architecture (SOA) . . . . . . . . . . . . . . . . . . 442
Web services approach for an SOA architecture . . . . . . . . . . . . . . . . . . . . . . 443
Web services tools in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 445
Bottom-up development of a Web service . . . . . . . . . . . . . . . . . . . . . . . . 445
Top-down development of a Web service . . . . . . . . . . . . . . . . . . . . . . . . . 445
Client development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Preparation for samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Creating a Web service from a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Creating the Web service using the Web Service wizard . . . . . . . . . . . . . 447
Generated files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Testing the Web service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Using the sample test application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Using the universal test client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
Creating a Web service client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Run the Web Service Client wizard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Creating a Web service from a session bean. . . . . . . . . . . . . . . . . . . . . . . . . 464
Implementing a real client application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467

Chapter 14. Developing GUI applications . . . . . . . . . . . . . . . . . . . . . . . . . 469


Introduction to the Visual Editor for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Sample GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Setting up your sample project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
Launching the Visual Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Create a visual class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473

x WebSphere Studio Application Developer Version 5 Programming Guide


Open an existing class with the Visual Editor . . . . . . . . . . . . . . . . . . . . . . 475
Visual Editor look and feel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
Customizing the appearance of the Visual Editor . . . . . . . . . . . . . . . . . . . . . 478
Changing the default Java Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
Working with the Visual Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
Resizing a JavaBean component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
Code synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
Add JavaBeans to a visual class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
Working with the Properties view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Working with the Java Beans view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
Extending the sample GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
Adding data to the JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Adding additional methods to the sample GUI . . . . . . . . . . . . . . . . . . . . . . . . 500
Writing event handling code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
Running and testing JavaBeans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
Running the sample GUI as a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . 505
Running the sample GUI as a Java application . . . . . . . . . . . . . . . . . . . . 507
Testing the sample GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
Running the sample outside of Application Developer . . . . . . . . . . . . . . . . . . 508
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

Part 3. Testing and debugging applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511

Chapter 15. Servers and server configurations . . . . . . . . . . . . . . . . . . . . 513


Server tools feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
Supported run-time environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
Creating server and server configuration automatically . . . . . . . . . . . . . . . . . 516
Creating server and server configuration manually . . . . . . . . . . . . . . . . . . . . 519
Creating a Server project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
Creating a remote server and file transfer mechanism . . . . . . . . . . . . . . . 520
Creating a server configuration manually . . . . . . . . . . . . . . . . . . . . . . . . . 527
Assigning a server configuration to a server . . . . . . . . . . . . . . . . . . . . . . . 530
Creating a server and server configuration together . . . . . . . . . . . . . . . . . . . 530
Assigning a project to a server configuration . . . . . . . . . . . . . . . . . . . . . . . . . 531
Configuring the data source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Starting and stopping servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
Changing the applications to run on a remote server. . . . . . . . . . . . . . . . . . . 538
Apache Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
TCP/IP Monitor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
Configuring the TCP/IP Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
Using the TCP/IP Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
Customizing server configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
Server page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544

Contents xi
Configuration page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
Applications page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
Administrative console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
Applying Fix Packs to the WebSphere test environment . . . . . . . . . . . . . . . . 549
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551

Chapter 16. Testing and debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553


Debugging a Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Setting breakpoints in a servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Setting breakpoints in a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
Testing the application with breakpoints enabled. . . . . . . . . . . . . . . . . . . . . . 557
Debug view with stack frames. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
Debug functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
Breakpoints view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
Watching variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
Inspecting variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
Evaluating an expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
Debugging a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Debugging on a remote WebSphere Application Server . . . . . . . . . . . . . . . . 566
Configuring the remote server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
Attaching to remote server in Application Developer . . . . . . . . . . . . . . . . 567
Connecting to the remote server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Debugging on the remote server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Disconnecting from the remote server . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572

Chapter 17. JUnit and component testing . . . . . . . . . . . . . . . . . . . . . . . . 573


What is JUnit? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Unit testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Why unit testing?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Benefits of a unit testing framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
Testing with JUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
TestCase class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
TestSuite class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
Creating the test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Importing the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Preparing for JUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Creating a test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
The setUp and tearDown methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
Test methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
Creating a TestSuite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
Running the test case. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
Testing the Web applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588

xii WebSphere Studio Application Developer Version 5 Programming Guide


Component testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
Creating a Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
Preparing a Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
Updating code of Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
Running a Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
Report test case results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Creating an HTTP test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603

Part 4. Deploying and profiling applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605

Chapter 18. Deploying enterprise applications . . . . . . . . . . . . . . . . . . . . 607


Enterprise application deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Importing the enterprise application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Working with deployment descriptors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
EJB deployment descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
Web deployment descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
Application client module deployment descriptor . . . . . . . . . . . . . . . . . . . 613
Building an application client module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
Exporting an enterprise application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
Configuring WebSphere Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . 617
Start the server and the administrative console . . . . . . . . . . . . . . . . . . . . 617
Configuring a server (optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
Configuring a JDBC driver and data source . . . . . . . . . . . . . . . . . . . . . . . 618
Save the configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
Installing an enterprise application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
Regenerating HTTP Server plug-in configuration . . . . . . . . . . . . . . . . . . . 627
Starting the enterprise application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Testing the applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
Remote debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Command line tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Batch commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Scripting tool: wsadmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Classpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632

Chapter 19. Building applications with Ant . . . . . . . . . . . . . . . . . . . . . . . 633


What is Ant? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
Sample demo project and application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Ant build files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Ant tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
Creating a simple build file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
Project definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
Global properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639

Contents xiii
Build targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
Running Ant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
Where is the output? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
Rerunning Ant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
Forced build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
Classpath problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
Building J2EE applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
Using or importing a J2EE project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
Ant J2EE build script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
Running Ant for J2EE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
Building Javadoc with Ant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
Running Ant outside of Application Developer . . . . . . . . . . . . . . . . . . . . . . . . 652
Preparation of the command file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
Running the command file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654

Chapter 20. Profiling applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655


Profiling architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
Profiling Java processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
Agent Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
Profiling an application in the WebSphere Test Environment . . . . . . . . . . 658
Attaching to a Java process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
Start monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
Performance analysis views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
Launch Java process for profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
Profiling remote processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
Performance analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
Package statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
Class method statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
Method statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
Method invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
Method execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
Execution flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
Sequence diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
Instance statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
Object references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
Some things to be aware of . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685

Part 5. Team programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687

Chapter 21. Version control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689


Local history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690

xiv WebSphere Studio Application Developer Version 5 Programming Guide


Comparing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
Replacing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
Restoring deleted files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
Team development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
Application Developer team support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
Terminology comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700

Chapter 22. Using Concurrent Versions System . . . . . . . . . . . . . . . . . . . 701


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
Installing CVS on the Windows platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
Creating a CVS repository on CVSNT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
Configuring CVS in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . 706
What is new in Application Developer Version 5?. . . . . . . . . . . . . . . . . . . 706
CVS preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
What changes could impact your work? . . . . . . . . . . . . . . . . . . . . . . . . . . 710
Ignoring resources from version control . . . . . . . . . . . . . . . . . . . . . . . . . . 711
Label decorations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
CVS console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
Development scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
Creating and sharing the project (step 1 - stade1) . . . . . . . . . . . . . . . . . . 714
Adding a shared project to the workspace (step 2 - stade2) . . . . . . . . . . . 719
Synchronizing with repository (step 3 - stade1) . . . . . . . . . . . . . . . . . . . . 722
Parallel development (step 4 - stade1 and stade2). . . . . . . . . . . . . . . . . . 723
Resolving conflicts (step 5 - stade1) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724
Versioning (step 6 - stade1) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 730
CVS resource history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
Branches in CVS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734
Merging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
Defining branch tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
Working with patches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
Creating a patch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
Applying a patch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
Disconnecting a project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746

Chapter 23. Using ClearCase . . . . . . . . . . . . . . . . . . . . . ....... ...... . 747


What is Rational ClearCase? . . . . . . . . . . . . . . . . . . . . . . . ....... ...... . 748
Basic ClearCase terminology . . . . . . . . . . . . . . . . . . . . . . . ....... ...... . 749
Installing ClearCase LT . . . . . . . . . . . . . . . . . . . . . . . . . . . ....... ...... . 749

Contents xv
Installing ClearCase LT Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
Installing the ClearCase LT client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
ClearCase integration with Application Developer . . . . . . . . . . . . . . . . . . . . . 752
ClearCase help in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 753
ClearCase preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
Using ClearCase with Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 754
Setting up ClearCase for a new project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
Creating a new VOB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
Creating new ClearCase project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
Joining a ClearCase project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
Creating a Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
Adding a project to ClearCase source control. . . . . . . . . . . . . . . . . . . . . . 762
Development scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
Developer 1 adds a servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
Developer 1 delivers work to the integration stream . . . . . . . . . . . . . . . . . 768
Developer 1 makes a baseline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
Developer 2 joins the project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
Developer 2 imports projects into Application Developer . . . . . . . . . . . . . 774
Developer 2 adds a new servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 776
Developer 2 delivers work to the integration stream . . . . . . . . . . . . . . . . . 778
Developer 2 makes a new baseline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
Developers synchronize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782

Part 6. Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783

Appendix A. Product installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785


Installing DB2 UDB. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Installing WebSphere Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Hardware prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Software prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Installation Application Server 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
Verifying the installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
Installing Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
Hardware prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
Software prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
Installing Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
Installing the Agent Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
Update Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
Using the Update Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
Manual update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798

Appendix B. Keyboard shortcuts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801


Workbench shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802

xvi WebSphere Studio Application Developer Version 5 Programming Guide


Editing shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
Java editor shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
Java development tools shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
Debug perspective shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
Page and CSS Designer shortcuts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
Page Designer source page shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807

Appendix C. Additional material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809


Locating the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
Using the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
System requirements for downloading the Web material . . . . . . . . . . . . . 810
How to use the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
Installing the EJBBANK database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
Installing the ItsoProGuide.ear file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 812
Installing the server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
Installing other projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
DB2 user ID and password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814

Abbreviations and acronyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815

Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817


IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817
Other publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
Online resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
How to get IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821

Contents xvii
xviii WebSphere Studio Application Developer Version 5 Programming Guide
Notices

This information was developed for products and services offered in the U.S.A.

IBM may not offer the products, services, or features discussed in this document in other countries. Consult
your local IBM representative for information on the products and services currently available in your area.
Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product, program, or service that
does not infringe any IBM intellectual property right may be used instead. However, it is the user's
responsibility to evaluate and verify the operation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matter described in this document.
The furnishing of this document does not give you any license to these patents. You can send license
inquiries, in writing, to:
IBM Director of Licensing, IBM Corporation, North Castle Drive Armonk, NY 10504-1785 U.S.A.
The following paragraph does not apply to the United Kingdom or any other country where such provisions
are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES
THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer
of express or implied warranties in certain transactions, therefore, this statement may not apply to you.

This information could include technical inaccuracies or typographical errors. Changes are periodically made
to the information herein; these changes will be incorporated in new editions of the publication. IBM may
make improvements and/or changes in the product(s) and/or the program(s) described in this publication at
any time without notice.

Any references in this information to non-IBM Web sites are provided for convenience only and do not in any
manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the
materials for this IBM product and use of those Web sites is at your own risk.

IBM may use or distribute any of the information you supply in any way it believes appropriate without
incurring any obligation to you.

Information concerning non-IBM products was obtained from the suppliers of those products, their published
announcements or other publicly available sources. IBM has not tested those products and cannot confirm
the accuracy of performance, compatibility or any other claims related to non-IBM products. Questions on
the capabilities of non-IBM products should be addressed to the suppliers of those products.

This information contains examples of data and reports used in daily business operations. To illustrate them
as completely as possible, the examples include the names of individuals, companies, brands, and products.
All of these names are fictitious and any similarity to the names and addresses used by an actual business
enterprise is entirely coincidental.

COPYRIGHT LICENSE:
This information contains sample application programs in source language, which illustrates programming
techniques on various operating platforms. You may copy, modify, and distribute these sample programs in
any form without payment to IBM, for the purposes of developing, using, marketing or distributing application
programs conforming to the application programming interface for the operating platform for which the
sample programs are written. These examples have not been thoroughly tested under all conditions. IBM,
therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. You may copy,
modify, and distribute these sample programs in any form without payment to IBM for the purposes of
developing, using, marketing, or distributing application programs conforming to IBM's application
programming interfaces.

© Copyright IBM Corp. 2003. All rights reserved. xix


Trademarks
The following terms are trademarks of the International Business Machines Corporation in the United States,
other countries, or both:

AIX® ^™ Redbooks™
BookMaster® Informix® Redbooks (logo) ™
Cloudscape™ IBM® SAA®
CICS® ibm.com® VisualAge®
Domino™ IMS™ WebSphere®
DB2® Lotus® z/OS®
™ Notes®

The following terms are trademarks of International Business Machines Corporation and Rational Software
Corporation, in the United States, other countries or both.

ClearCase® Rational®

The following terms are trademarks of other companies:

Intel, Intel Inside (logos), MMX, and Pentium are trademarks of Intel Corporation in the United States, other
countries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the
United States, other countries, or both.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun
Microsystems, Inc. in the United States, other countries, or both.

UNIX is a registered trademark of The Open Group in the United States and other countries.

SET, SET Secure Electronic Transaction, and the SET Logo are trademarks owned by SET Secure
Electronic Transaction LLC.

Other company, product, and service names may be trademarks or service marks of others.

xx WebSphere Studio Application Developer Version 5 Programming Guide


Preface

This IBM® Redbook is a programming guide for the application development


tool, WebSphere® Studio Application Developer V5. This tool is not only
intended for the Java™ developer, but also for the Web designer who creates
Web pages. The WebSphere Studio Application Developer basic tooling and
team environment is presented along with the development and deployment of
Web applications.

WebSphere Studio Application Developer provides integrated development tools


for all e-business development roles, including Web developers, Java
developers, business analysts, architects, and enterprise programmers. The
customizable, targeted, role-based approach of WebSphere Studio Application
Developer will be characteristic of all new products built on the WebSphere
Studio Workbench. It is well integrated with WebSphere Application Server and
provides built-in server test environments that can be used for testing and
profiling Web applications.

This redbook consists of six parts:


򐂰 Introducing WebSphere Studio Application Developer
򐂰 Developing applications
򐂰 Testing and debugging applications
򐂰 Deploying and profiling applications
򐂰 Team programming
򐂰 Appendixes and additional material

© Copyright IBM Corp. 2003. All rights reserved. xxi


The team that wrote this redbook
This redbook was produced by a team of specialists from around the world
working at the International Technical Support Organization, Raleigh Center.

Ian Maik Ueli Fabio Henrik

Ueli Wahli is a Consultant IT Specialist at the IBM International Technical


Support Organization in San Jose, California. Before joining the ITSO 19 years
ago, Ueli worked in technical support at IBM Switzerland. He writes extensively
and teaches IBM classes worldwide on application development, object
technology, VisualAge® for Java, WebSphere Application Server, and lately
WebSphere Studio products. In his ITSO career Ueli has produced over 25 IBM
Redbooks™. Ueli holds a degree in Mathematics from the Swiss Federal
Institute of Technology.

Ian Brown is a Consultant for ASTECH Solutions Inc. in Aurora, Ontario,


Canada. He has 5 years of experience in the field of information technology, and
2 years of experience in analysis, design and development of Web and J2EE
applications. He holds a degree in Computer Science from the University of
Waterloo. His areas of expertise include application development using the
Eclipse platform, Java, and WebSphere Application Server administration.

Fabio Ferraz is the Chief Consultant for e-Voilà Enabling in Rio de Janeiro,
Brazil. He has years 11 years of experience in the IT field, and 8 of those
dedicated to e-business.

xxii WebSphere Studio Application Developer Version 5 Programming Guide


Maik Schumacher is an IT Specialist at IBM Software Services for Lotus® in
Cologne, Germany. He has 9 years of experience in the field of information
technology and he has been with IBM for two years, mainly working on an
architecture of e-business solutions. Maik is a Principal Certified Lotus
Professional and holds a degree in Computer Science with Business from the
University of Applied Sciences in Dortmund, Germany. His areas of expertise are
in software development, e-business, and Internet design.

Henrik Sjostrand is an Advisory IT Specialist working for IBM Sweden since 8


years. He has 12 years of experience in the field of information technology.
During his time with IBM he has had a number of different positions from
consulting and education to pre-sales activities. The last 3 years he has focused
on e-business application development, and WebSphere Application Server
architecture and deployment. Henrik is certified in WebSphere Application
Server 4.0 and holds a Master of Science in Electrical Engineering from
Chalmers University of Technology in Gothenburg, Sweden, where he lives.

Thanks to the following people for their contributions to this project:

Osamu Takagiwa, Joseph Korchmar, Arne Lindquist, and Martin Vojtko, who
wrote the original redbook, WebSphere Studio Application Developer
Programming Guide, SG24-6585.

Yvonne Lyon, for technical editing


International Technical Support Organization, San Jose Center

Become a published author


Join us for a two- to six-week residency program! Help write an IBM Redbook
dealing with specific products or solutions, while getting hands-on experience
with leading-edge technologies. You'll team with IBM technical professionals,
Business Partners and/or customers.

Your efforts will help increase product acceptance and customer satisfaction. As
a bonus, you'll develop a network of contacts in IBM development labs, and
increase your productivity and marketability.

Find out more about the residency program, browse the residency index, and
apply online at:
ibm.com/redbooks/residencies.html

Preface xxiii
Comments welcome
Your comments are important to us!

We want our Redbooks to be as helpful as possible. Send us your comments


about this or other Redbooks in one of the following ways:
򐂰 Use the online Contact us review redbook form found at:
ibm.com/redbooks
򐂰 Send your comments in an Internet note to:
redbook@us.ibm.com
򐂰 Mail your comments to:
IBM Corporation, International Technical Support Organization
Dept. HZ8 Building 662
P.O. Box 12195
Research Triangle Park, NC 27709-2195

xxiv WebSphere Studio Application Developer Version 5 Programming Guide


Summary of changes from SG24-6585
This section describes the technical changes made in this edition of the book and
in previous editions. This edition may also include minor corrections and editorial
changes that are not identified.

Summary of Changes
for SG24-6957-00
for WebSphere Studio Application Developer Version 5 Programming Guide
as created or updated on July 16, 2003.

July 2003, First Edition


This book is a major rewrite of WebSphere Studio Application Developer
Programming Guide, SG24-6585. The previous book was based on Application
Developer Version 4, this book is based on Version 5.

This revision reflects the addition, deletion, or modification of new and changed
information described below.

New information
򐂰 Support for J2EE 1.3, including EJB 2.0, Servlet 2.3, and JSP 1.2 levels
򐂰 New chapters on XML development, EJB development, Web services
development, Struts development, GUI application development
򐂰 Filters and listeners in Web development
򐂰 Support for DB2® stored procedures
򐂰 Component testing in the JUnit chapter
򐂰 Usability enhancements for Common Versions System

Changed information
򐂰 General update of existing information to Version 5

Deleted information
򐂰 Migration—covered very well in the migration guide that is shipped with the
product
򐂰 Plugin development—Very good information in a new book: The Java
Developer’s Guide to Eclipse (see “Other publications” on page 818)

Preface xxv
xxvi WebSphere Studio Application Developer Version 5 Programming Guide
Part 1

Part 1 Introducing
WebSphere Studio
Part 1 introduces WebSphere Studio Application Developer with concepts about
the Workbench, tools, workspace, perspectives, and projects.

© Copyright IBM Corp. 2003. All rights reserved. 1


2 WebSphere Studio Application Developer Version 5 Programming Guide
1

Chapter 1. Introduction and concepts


This chapter contains an introduction to the concepts behind Application
Developer. An overview of the features and the WebSphere Studio family is
provided as well. The following topics are discussed:
򐂰 Eclipse
򐂰 Platform architecture
򐂰 Workbench features
򐂰 WebSphere Studio products
򐂰 What is new in Application Developer Version 5
򐂰 Tools
򐂰 Sample code in this book

© Copyright IBM Corp. 2003. All rights reserved. 3


Introduction
WebSphere Studio Application Developer (hereafter called Application
Developer) is one of the WebSphere Studio family of products that has been
developed based on the Eclipse Workbench.

The Eclipse Workbench platform was designed by IBM and released to the open
source community. It is an open, portable, universal tooling platform that provides
frameworks, services, and tools for building tools.

In essence, the Workbench provides the tool infrastructure. With this


infrastructure in place, the tool builders are able to focus on the actual building of
their tools. The Workbench has been designed for maximum flexibility to support
the development of tools for new technologies that may emerge in the future.

Development environments written for the Workbench should support a


role-based development model, in which the outcomes of the developers’ work
will be consistent. The developers should not have to be concerned with how
different individual tools may be treating their files.

The WebSphere Studio product family is based on an integrated development


environment (IDE) for developing, testing, debugging, and deploying
applications. It provides support for each phase of the application development
life cycle.

Eclipse
Eclipse is an open platform for tool integration built by an open community of tool
providers. With a common public license that provides royalty free source code
and world wide redistribution rights, the Eclipse platform provides tool developers
with ultimate flexibility and control over their software technology.

Industry leaders like IBM, Borland, Merant, QNX Software Systems, Rational®
Software, RedHat, SuSE, TogetherSoft, and WebGain formed the initial
eclipse.org board of directors of the Eclipse open source project. Visit the
Eclipse Web Site for more information about the project:
http://www.eclipse.org

Platform architecture
Figure 1-1 shows an overview of the Eclipse platform.

4 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 1-1 Eclipse platform

Eclipse is a platform that has been designed from the ground up for building
integrated regardless of presentation technology and application development
tooling. By design, the platform itself does not provide a great deal of end user
functionality. The value of the platform is what it encourages: rapid development
of integrated features based on a plug-in model.

Eclipse provides a common user interface (UI) model for working with tools. It is
designed to run on multiple operating systems while providing robust integration
with each underlying OS. Plug-ins can be programmed to the Eclipse portable
APIs and run unchanged on any of the supported operating systems.

The Eclipse platform uses the model of a common Workbench to integrate the
tools from the end user's point of view. Tools that you develop can be plugged
into the Workbench using well defined hooks called extension points.

The underlying platform runtime uses the same extension model to allow plug-in
developers to add support for additional file types and customized installations,
such as Web servers, workgroup servers, and repositories. The artifacts for each
tool, such as files and other data, are coordinated by a common platform
resource model.

The platform gives the users a common way to work with the tools, and provides
integrated management of the resources they create with plug-ins.

Chapter 1. Introduction and concepts 5


Workbench features
The Eclipse Workbench provides a set of APIs, models, and frameworks for
developing source editors and other user interfaces, as well as access to
common services for resource management, debugging, and team
programming.

The main features of the Eclipse Workbench are:


򐂰 Plug-in based tooling
򐂰 Role-oriented development tools
򐂰 Vertical and horizontal integration
򐂰 Open standards
򐂰 Open team environment
򐂰 File based IDE

Plug-in based tooling


The Workbench provides a flexible plug-in platform. Different tools can plug in to
the Workbench, with each tool providing new functionality to be added to the
Workbench or to already existing plug-ins. Each plug-in integrates with the
Workbench and with the other tools. Ideally the end-user should not notice any
difference when moving from one tool to another.

By programming to the portable Eclipse APIs, plug-ins can run unchanged on


any of the supported operating systems using a common user interface model.
The Workbench is designed to run on multiple operating systems while providing
robust integration with each one.

At the core of Eclipse is an architecture for dynamic discovery of plug-ins. The


platform handles the logistics of the base environment and provides a standard
user navigation model. Each plug-in can focus on performing a small number of
tasks well, without having to provide the supporting infrastructure. Some
examples of such tasks are defining, testing, animating, publishing, compiling,
debugging, and diagramming.

Because the Workbench is based on an open architecture, each plug-in


development team can focus on their area of expertise. This enables the team
management experts to build the back-end interfaces and the usability experts to
build the end user tools. If these are well designed, and use the standard APIs,
significant new features and levels of integration can be added to the Workbench
and Workbench based products without impacting other tools.

6 WebSphere Studio Application Developer Version 5 Programming Guide


Role-oriented development with consistent look and feel
The Workbench is designed to provide special support for a particular e-business
development role, or for a set of roles.

Within the Workbench based products, task-oriented perspectives filter out much
of the overall complexity, and present the developer only with those functions that
are relevant to the task at hand.

Users can switch perspectives depending on what they are working on at any
given moment, or depending on their current role in the project.

Because different developers are accustomed to working in different ways, any


perspective can be further customized. And because all tools and perspectives
are built using the Eclipse Workbench technology, they share a common look and
feel, which reduces learning curves and help maximize developer productivity.

All development resources for all projects are stored in a single repository,
therefore developers have consistent team support for their projects, and are
able to easily share their work products.

Vertical and horizontal integration


Traditionally software vendors have provided vertical tools, forcing customers to
do their own integration. The purpose of the Eclipse Workbench is to provide a
platform that software vendors can easily extend. ISVs have already embraced
this technology and are actively building tools on this base.

As an example, every WebSphere Studio family of products that is built on the


Workbench offers a set of already integrated tools, freeing you to focus on
building applications rather than on integrating tools. Furthermore, you can easily
integrate other tools (from other vendors or locally developed), as long as they
conform to the Workbench standard plug-in protocol.

Open standards
The whole Eclipse Workbench, as well as all products of the WebSphere Studio
family of products, are built on open standards and the code that they generate
also complies with open standards.

This allows you to build and deploy state-of-the-art, server-side applications that
conform to the Servlet 2.2, JavaServer Pages 1.1, and EJB 1.1 specifications.

Chapter 1. Introduction and concepts 7


Open team development
Application development teams are becoming more distributed, more diverse,
and are under increasing pressure to deliver solutions quickly. In such an
environment it is critical to have development tools that can support these needs,
while at the same time addressing personalized requirements. The team
development environment for all products based on the Eclipse Workbench
supports pluggable repositories rather than mandating any proprietary
repository, and support an optimistic concurrency model.

File-based IDE
The Eclipse Workbench is a platform for building file-based IDEs. All content is
saved as files. Workbench resources, such as Java classes and HTML files, are
stored in the file system, making them easy to access.

WebSphere Studio products


The WebSphere Studio product family is built on top of the Eclipse Workbench as
a set of plug-ins conforming to the Workbench’s open standard APIs.

The WebSphere Studio family of products currently has the following members
(Figure 1-2):
򐂰 WebSphere Studio Site Developer Advanced
򐂰 WebSphere Studio Application Developer
򐂰 WebSphere Studio Application Developer Integration Edition
򐂰 WebSphere Studio Enterprise Developer

These products provide support for end-to-end development, testing, and


deployment of Web and J2EE applications.

The WebSphere Studio product family provide integrated development tools for
most e-business development roles including Web developers, Java developers,
business analysts, architects, and enterprise programmers. The customizable,
targeted and role-oriented approach of the Workbench will be a common
characteristic of future products in the WebSphere Studio family.

8 WebSphere Studio Application Developer Version 5 Programming Guide


Enterprise Developer
User: Enterprise
Application Developer Integration Edition Developer
Function:
Application Developer Create new EIS
applications as part
Site Developer User: Advanced J2EE of a J2EE app
Developer EGL Tools
User: Web Developer User: J2EE Developer
Function: Develop/Maintain
Function: Function:
Access existing EIS z/OS Apps
HTML/JSP/Servlet EJB Tools applications using COBOL
Struts Tools
Web Services Tools
+ Performance and
Trace tools
Component Test tools
+ JCA
Visual Service Flow + PL/I
ASM
XML Tools Choreography COBOL XML
Java Visual Editor ClearCase LT OEM Target Runtime: Enablement
Target Runtime: Target Runtime: WAS AE, ND, WAS E Target Runtime: WAS
WAS AE, WAS ND WAS AE, WAS ND AE, ND, WAS E, z/OS

WebSphere Studio Workbench


IBM's commerically supported version of Eclipse Basis for IBM Tooling

Eclipse Workbench
Provides frameworks for tool builders
to focus on tool building

Figure 1-2 WebSphere Studio family

WebSphere Studio Site Developer


Site Developer is an IDE intended for Web developers who develop and manage
complex Web sites. It is an easy-to-use environment that minimizes the time and
effort required to create, manage, and debug multi-platform Web sites. It is
designed according to the J2SE and J2EE specifications and supports JSPs,
servlets, HTML, JavaScript, and DHTML. It further includes tools for developing
images and animated GIFs.

Site Developer enables Web developers to use their favorite content creation
tools in conjunction with the built-in local and remote publishing capabilities.

Using Site Developer, you can develop Web applications that use the following
technologies.
򐂰 JSPs—A simple, fast, and consistent way to extend Web server functionality
and create dynamic Web content. JSPs enable rapid development of Web
applications that are server and platform-independent.
򐂰 Servlets—Server code that executes within a Web Application Server.
򐂰 Web services—Self-contained, modular applications that can be described,
published, located, and invoked over the Internet or within intranets.

Chapter 1. Introduction and concepts 9


WebSphere Studio Application Developer
Application Developer is designed for professional developers of Java and J2EE
applications, who require integrated Java, Web, XML, and Web services support.

It includes all of the features of Site Developer, and adds tools for developing EJB
applications, as well as performance profiling and logging tools for both local and
remote execution.

Developers can quickly build and test business logic and enhance the
presentation artifacts with built-in Web creation tools inside the Application
Developer IDE before deploying to a production server.

Using the performance profiling and tracing tools, it is possible to detect


application performance bottlenecks early in the development cycle.
Furthermore, the built-in test environment for WebSphere Application Server and
advanced tools for code generation help shorten the test cycle.

WebSphere Studio Application Developer Integration Edition


Integration Edition includes all of the functionality in Application Developer, plus:
򐂰 Powerful graphical tools to help you quickly and easily build custom
application adapters to integrate your J2EE application with your back-end
systems, helping you save time and money by reusing existing resources.
򐂰 Visual flow-based tools that increase developers productivity by allowing them
to visually define the sequence and flow of information between application
artifacts such as adapters, Enterprise JavaBeans components and Web
services.
򐂰 Wizards that help in building and deploying complex Web services out of
adapters, EJB components, flows, and other Web services.
򐂰 Support for the full set of Enterprise services provided by WebSphere
Application Server Enterprise Edition such as business rule beans,
internationalization, and work areas that deliver additional integration
capabilities, developer productivity, and business agility.

WebSphere Enterprise Developer


Enterprise Developer includes all of the functionality in WebSphere Studio
Application Developer Integration Edition, plus among others:
򐂰 Integrating transactional environments such as CICS® and IMS™
򐂰 Creating new EIS applications as part of a J2EE application
򐂰 Developing and maintaining z/OS® applications
򐂰 Supporting Java, COBOL, PL/I, and EGL (enterprise generation language)
development

10 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Implementing Struts-based MVC applications using connectors and EGL.

Here is another core technology that is integrated within Enterprise Developer:


򐂰 WebSphere Studio Asset Analyzer (WSAA)—Identifies application processes
and connecting points, and provides the ability to generate components from
existing code.

Enterprise Developer provides a visual construction and assembly based


environment supporting the implementation of enterprise level applications,
including support for the multiple developer roles and technologies required by
those applications. Some examples of technologies supported are HTML, JSPs,
servlets, EJBs, COBOL, EGL, PL/I, and connectors.

What is new in Application Developer Version 5


Application Developer Version 5 contains many new and improved features. For
details about changes to specific product features, refer to the readme file located
in the readme subdirectory of both the installation CD and the WebSphere Studio
installation directory (Windows® users can also access the readme file directly
from the Start menu, after installing WebSphere Studio).

Here are some highlights of the new features:


򐂰 Support for J2EE 1.3, including EJB 2.0, Servlet 2.3, and JSP 1.2 levels
򐂰 Concurrent support for WebSphere Application Server V4 (J2EE 1.2) and
WebSphere Application Server V5 (J2EE 1.3)
򐂰 Enables WebSphere Application Server Version 4 users to adopt the latest
innovations from Eclipse Version 2, and enhancements from Application
Developer Version 5 without server upgrade
򐂰 Numerous updates and new functions for Java, Web services, XML,
Database, Test and Analysis, and Web components
򐂰 Specialized support for Struts, which is a set of Java classes and JSP tag
libraries that provide a conceptual framework for developing Web applications
򐂰 New Visual Editor for Java (Java-based client for building GUI components
with Swing or AWT)
򐂰 XSL source editor; new wizards to help you create your XSL files

Chapter 1. Introduction and concepts 11


Migration from previous versions
The root directory of Application Developer’s installation CD contains a migration
guide that is provided in the migrate.pdf and the migrate.html files.

This migration guide discusses how you can:


򐂰 Target WebSphere Application Server Version 4.0.x versus Version 5
򐂰 Migrate from WebSphere Studio Application Developer Version 4.0.x
򐂰 Migrate from WebSphere Studio Application Developer Version 5 Beta
򐂰 Migrate from WebSphere Studio Classic to WebSphere Studio Application
Developer
򐂰 Migrate from VisualAge for Java to WebSphere Studio Application Developer
򐂰 Migrate from WebSphere Studio Application Developer for Linux
򐂰 Migrate enterprise beans from VisualAge for Java to WebSphere Studio
Application Developer
򐂰 Migrate from EJB 1.0 to EJB 1.1 or to EJB 2.0
򐂰 Migrate from VisualAge for Java Visual Composition Editor to Visual Editor for
Java
򐂰 Convert from VisualAge for Java Persistence Builder to EJB 2.0
򐂰 Build setup (library JARs, dependant project JARs, Ant builds)

The migration guide also provides some migration examples that show you, step
by step, how to migrate to Version 5 from previous versions.

Tools
The WebSphere Studio product family include the following basic tools:
򐂰 Web development
򐂰 Relational database
򐂰 XML
򐂰 Java development
򐂰 Web services development
򐂰 Team collaboration
򐂰 Integrated debugger
򐂰 Server tools for testing and deployment
򐂰 Enterprise JavaBean development tools (not in Site Developer Advanced)
򐂰 Performance profiling (not in Site Developer Advanced)
򐂰 Plug-in development

12 WebSphere Studio Application Developer Version 5 Programming Guide


Web development tools
The professional Web development environment provides the necessary tools to
develop sophisticated Web applications consisting of static HTML pages, JSPs,
servlets, XML deployment descriptors, and other resources.

Wizards are available to generate ready to run Web applications based on SQL
queries and JavaBeans. Links between Web pages can be automatically
updated when content is moved or renamed.

The Web development environment brings all aspects of Web application


development into one common interface. Everyone on your Web development
team, including content authors, graphic artists, programmers, and Web
masters, can work on the same projects and access the files they need.

Such an integrated Web development environment makes it easy to


collaboratively create, assemble, publish, deploy, and maintain dynamic,
interactive Web applications.

The Web development tools provide the following features:


򐂰 Support for latest Web technology with an intuitive user interface
򐂰 Advanced scripting support to create client-side dynamic applications with
VBScript or JavaScript
򐂰 Web Art Designer to create graphic titles, logos, buttons, and photo frames
with professional-looking touches
򐂰 Animated GIF Designer to create life-like animation from still pictures,
graphics, and animated banners
򐂰 Over 2,000 images and sounds in the built-in library
򐂰 Integrated, easy-to-use visual layout tool for JSP and HTML file creation and
editing
򐂰 Web project creation, using the J2EE-defined hierarchy
򐂰 Creation and visual editing of the Web application deployment descriptor
(web.xml) file
򐂰 Automatic update of links as resources are moved or renamed
򐂰 A wizard for creating servlets
򐂰 Generation of Web applications from database queries and JavaBeans
򐂰 J2EE WAR/EAR deployment support (not in Site Developer)
򐂰 Integration with the WebSphere unit test environment

Chapter 1. Introduction and concepts 13


Relational database tools
The database tools provided with the WebSphere family products allow you to
create and manipulate the data design for your project in terms of relational
database schemas.

You can explore, import, design, and query databases working with a local copy
of an already existing design. You can also create an entirely new data design
from scratch to meet your requirements.

The database tools provide a metadata model used by all other tools that need
relational database information, including database connection information. In
that way, tools, although unaware of each other, are able to share connections.

The SQL Statement Wizard and SQL Query Builder provide a GUI-based
interface for creating and executing SQL statements. When you are satisfied with
your statement, you can use the SQL to XML Wizard to create an XML
document, as well as XSL, DTD, XSD, HTML, and other related artifacts.

The relational database tools support connecting to, and importing from, several
database types, including DB2, Oracle, SQL Server, Sybase, and Informix®.

XML tools
The comprehensive XML toolset provided by the WebSphere Studio family of
products includes components for building DTDs, XML schemas (XSD) and XML
files. With the XML tools you can perform all of the following tasks:
򐂰 Create, view, and validate DTDs, XML schemas, and XML files.
򐂰 Create XML documents from a DTD, from an XML schema, or from scratch.
򐂰 Generate JavaBeans from a DTD or XML schema.
򐂰 Define mappings between XML documents and generate XSLT scripts that
transform documents.
򐂰 Create an HTML or XML document by applying an XSL style sheet to an XML
document.
򐂰 Map XML files to create an XSL transformation script and to visually step
through the XSL file.
򐂰 Define mappings between relational tables and DTD files, or between SQL
statements and DTD files, to generate a document access definition (DAD)
script, used by IBM DB2 XML Extender. This can be used either to compose
XML documents from existing DB2 data or to decompose XML documents
into DB2 data.
򐂰 Generate DADX, XML, and related artifacts from SQL statements and use
these files to implement your query in other applications.

14 WebSphere Studio Application Developer Version 5 Programming Guide


Java development tools (JDT)
All WebSphere Studio family of products provide a professional-grade Java
development environment with the following capabilities:
򐂰 Application Developer Version 5 ships with JDK 1.3
򐂰 Pluggable run-time support for JRE switching and targeting of multiple
run-time environments from IBM and other vendors
򐂰 Incremental compilation
򐂰 Ability to run code with errors in methods
򐂰 Crash protection and auto-recovery
򐂰 Error reporting and correction
򐂰 Java text editor with full syntax highlighting and complete content assist
򐂰 Refactoring tools for reorganizing Java applications
򐂰 Intelligent search, compare, and merge tools for Java source files
򐂰 Scrapbook for evaluating code snippets

Web services development tools


Web services represent the next level of function and efficiency in e-business.
Web services are modular, standards-based e-business applications that
businesses can dynamically mix and match in order to perform complex
transactions with minimal programming.

The WebSphere Studio family of products that include the Web services feature,
help you to build and deploy Web services-enabled applications across the
broadest range of software and hardware platforms used by today's businesses.
These tools are based on open, cross-platform standards such as Simple Object
Access Protocol (SOAP), Web Services Description Language (WSDL), and
Universal Description Discovery and Integration (UDDI).

EJB development tools


The WebSphere Studio family of products, except Site Developer Advanced,
feature full EJB support (Application Developer V5 supports EJB 1.1 and 2.0), an
updated EJB test client, an enhanced unit test environment for J2EE, and
deployment support for Web application archive (WAR) files and enterprise
application archive (EAR) files. Entity beans can be mapped to databases, and
EJB components can be generated to tie into transaction processing systems.
XML provides an extended format for deployment descriptors within EJB.

Chapter 1. Introduction and concepts 15


Team collaboration
Team developers do all of their work in their individual Workbenches, and then
periodically release changes to the team code. This model allows individual
developers to work on a team project, share their work with others as changes
are made, and access the work of other developers as the project evolves. At any
time, developers can update their Workbenches by retrieving the changes that
have been made to the team code.

All products of the WebSphere Studio family support the Concurrent Versions
System (CVS) and the Rational ClearCase® LT products.

Other software configuration management (SCM) repositories can be integrated


through the Eclipse Workbench SCM adapters. SCM adapters for commercial
products are provided by the vendors of those products.

Debugging tools
The WebSphere Studio family of products include a debugger that enables you to
detect and diagnose errors in your programs running either locally or remotely.
The debugger allows you to control the execution of your program by setting
breakpoints, suspending launches, stepping through your code, and examining
the contents of variables.

You can debug live server-side code as well as programs running locally on your
workstation.

The debugger includes a debug view that shows threads and stack frames, a
process view that shows all currently running and recently terminated processes,
and a console view that allows developers to interact with running processes.
There are also views that display breakpoints and allow you to inspect variables.

Performance profiling tools


The WebSphere Studio family of products (except for Site Developer) provide
tools that enable you to test the performance of your application. This allows you
to make architectural and implementation changes early in your development
cycle, and significantly reduces the risk of finding serious problems in the final
performance tests.

The profiling tools collect data related to a Java program's run-time behavior, and
present this data in graphical and non-graphical views. This assists you in
visualizing program execution and exploring different patterns within the
program.

16 WebSphere Studio Application Developer Version 5 Programming Guide


These tools are useful for performance analysis and for gaining a deeper
understanding of your Java programs. You can view object creation and garbage
collection, execution sequences, thread interaction, and object references. The
tools also show you which operations take the most time, and help you find and
plug memory leaks. You can easily identify repetitive execution behavior and
eliminate redundancy, while focusing on the highlights of the execution.

Server tools for testing and deployment


The server tools provide a unit test environment where you can test JSPs,
servlets and HTML files, (EJB testing is supported in Application Developer and
Enterprise Developer). You also have the capability to configure other local or
remote servers for integrated testing and debugging of J2EE applications.

The following features are included:


򐂰 A copy of the complete WebSphere Application Server run-time environment.
򐂰 Standalone unit testing.
򐂰 Ability to debug live server-side code using the integrated debugger.
򐂰 Support for configuring multiple servers.

The server tools support the following run-time environments, which can be
installed locally or remotely and support testing of Web applications:
򐂰 WebSphere Application Server Version 5.0
򐂰 WebSphere Application Server Express Version 5.0
򐂰 WebSphere Application Server Version 4.0 (AEs)
򐂰 Apache Tomcat Version 4.1
򐂰 Apache Tomcat Version 4.0
򐂰 Apache Tomcat Version 3.2

Plug-in development tools


The WebSphere Studio product family (except for Site Developer) include the
plug-in development environment (PDE) that is designed to help you develop
platform plug-ins while working inside the platform Workbench and it provides a
set of platform extension contributions (views, editors, perspectives, etc.) that
collectively streamline the process of developing plug-ins inside the Workbench.
The PDE is not a separate tool, but it is a perspective.

The following project types are supported:


򐂰 Plug-in project—Application Developer is based on the concept of plug-ins
that have a clearly defined structure and specification. This project supports
the ability to create, test, and deploy a plug-in in the PDE.

Chapter 1. Introduction and concepts 17


򐂰 Fragment project—A plug-in fragment is used to provide additional plug-in
functionality to an existing plug-in after it has been installed. Fragments are
ideal for shipping features like language or maintenance packs that typically
trail the initial products by a few months.
򐂰 Plug-in component—PDE attaches a special component nature to plug-in and
fragment projects to differentiate them from other project types. The project
must have a specific folder structure and a component manifest. The project
must be set up with references to all of the plug-in and fragment projects that
will be packaged into the component.

Sample code in this book


All the code examples in this book are based on a banking model (Figure 1-3).
This model was used in the IBM Redbook EJB 2.0 Development with WebSphere
Studio Application Developer, SG24-6819.

business logic
Bank
Deposit, Withdraw,
1:m Transfer

Customer
update create

m:m
1:m
Account TransRecord

Checking Savings

Figure 1-3 Banking model

The banking model is supported by a relational database called EJBBANK. In this


book we only use a subset of the model: Customer, Account, and TransRecord.

For simple Java and Web development we implement the model in memory. For
advanced development, such as Web with database and EJB, we use the
relational database.

18 WebSphere Studio Application Developer Version 5 Programming Guide


EJBBANK database
The database consist of the tables shown in Table 1-1. Only the shaded tables
are used in the examples in this document.

Table 1-1 EJBBank tables


Table Description

CUSTOMER Bank customer with ID, title, firstname, lastname, user ID, password,
and address.

ACCOUNT Bank account with ID, balance, interest rate, account type, overdraft
amount (CHECKING) and minimum amount (SAVINGS).

TRANSRECORD Transaction record with ID, account ID, transaction type (deposit,
withdraw), and amount.

CUSTACCT Relationship table between CUSTOMER and ACCOUNT.

CUSTADDRESS Customer address with customer ID, street, city, state, zipcode (not
used in this book).

CUSTOMERINFO Customer information, for example picture (not used in this book).

CHECKING Checking account, subtype of account, with overdraft amount (not


used in this book)

SAVINGS Savings account, subtype of account, with minimum amount (not


used in this book).

See Appendix C, “Additional material” on page 809 for instructions on how to


create and load the EJBBANK database.

Naming convention
All projects and packages used in this book follow a naming convention:
򐂰 ItsoProGuideXxxxx for projects
򐂰 itso.xxxx for packages

Chapter 1. Introduction and concepts 19


Summary
This chapter introduced the concepts behind Application Developer and gave an
overview of the features of the various members of the WebSphere Studio family
of tools. The following topics were discussed:
򐂰 Eclipse
򐂰 Platform architecture
򐂰 Workbench features
򐂰 WebSphere Studio products
򐂰 What is new in Application Developer Version 5
򐂰 Tools
򐂰 Sample code in this book

20 WebSphere Studio Application Developer Version 5 Programming Guide


2

Chapter 2. Setting up your Workbench


and workspace preferences
After you have installed Application Developer, and before you start creating your
projects, you may want to modify some of the default Workbench settings to suit
your needs or site standards. This chapter describes the most important areas
where you can customize the Application Developer setup.

The following topics are discussed in this chapter:


򐂰 Workbench basics
򐂰 Java development preferences

Note: Installation of Application Developer is covered in Appendix A, “Product


installation” on page 785.

© Copyright IBM Corp. 2003. All rights reserved. 21


Workbench basics
Once you have started Application Developer, you will see it opened in a single
window. Application Developer initially displays a perspective — the J2EE
perspective. A perspective contains views, such as the J2EE Navigator view, and
editors. More information regarding perspectives and views are provided in
Chapter 3, “Perspectives, views, and editors” on page 47.

Figure 2-1 shows Application Developer’s initial Workbench.

Figure 2-1 Application Developer Workbench

At the far left of the window is a shortcut bar that allows you to open new
perspectives and navigate between perspectives that are already open. The
name of the active perspective is shown in the title of the window and its icon in
the shortcut bar (left side) is a pushed button.

The J2EE Hierarchy, Tasks, and Outline views are open, along with an editor on
the welcome page. The welcome page provides a quick starting point if you are
eager to customize your Workbench or learn about other installed features.

22 WebSphere Studio Application Developer Version 5 Programming Guide


The term Workbench refers to the desktop development environment. Each
Workbench window of Application Developer contains one or more perspectives.
Perspectives contain views and editors and control what appears in certain
menus and toolbars.

Workspace basics
The Application Developer workspace is a private work area for the individual
developer. It holds the environment metadata and the loaded projects’ data in
regular files.

Every time you save a resource, the changes are reflected in the file system.
Normally this is your local file system, but you can also choose to store your
workspace in a network file system (NFS) as well.

Note: The advantages of storing workspaces in NFSs are such as ease of


backup—it is easier for the administrators to back up a team’s workspaces if
they all stand in the same machine—and increased mobility, as you may
connect to the workspace from any machine on the network. The
disadvantage, though, is decreased performance and mobility (laptop).

Application Developer also allows you to open more than one Workbench at a
time. To open a new Workbench in another window, click Window -> New
Window and a new Workbench with the same perspective opens in a new
window.

If you do not specify otherwise, Application Developer creates a default


workspace which is placed in the directory:
My Documents\IBM\wsad\workspace

However, you can change the default workspace by starting Application


Developer with the -data workspacePath parameter where the workspacePath
points to your preferred workspace directory. Relative paths are interpreted
relative to the directory that Application Developer was started from.

Tip: If for some reason you ever need to clean your workspace and start over
from scratch, the quickest way would be to exit Application Developer and
rename the workspace directory. Upon restarting Application Developer, you
would have a clean workspace. You could then import the resources that you
still require from the old workspace directory.

Chapter 2. Setting up your Workbench and workspace preferences 23


By using the -data parameter you can start a second instance of Application
Developer that uses a different workspace. To start a new instance of Application
Developer, start Application Developer with the -data workspacePath parameter.

For example, if your second instance should use the NewWorkspace workspace
folder, you can launch Application Developer with this command (this assumes
Application Developer has been installed in the default installation directory):
c:\Program Files\IBM\WebSphere Studio\wsappdev.exe -data c:\NewWorkspace

There are a number of parameters that you can add when launching Application
Developer (Table 2-1).

Table 2-1 Startup parameters


Command Description

-data workspacedirectory Start Application Developer with a specific workspace.

-configuration The location for the platform configuration file,


configurationFileURL expressed as a URL. The configuration file determines
the location of the platform, the set of available plug-ins,
and the primary feature. Note that relative URLs are not
allowed. The configuration file is written to this location
when Application Developer is installed or updated.

-vm vmPath This optional option allows you to set the location of Java
Runtime Environment (JRE) to use to run Application
Developer. Relative paths are interpreted relative to the
directory that Eclipse was started from.

-vmargs -Xmx256M For large-scale development you should modify your VM


arguments to make more heap available. This example
allows the Java heap to grow to 256MB. This may not be
enough for large projects.

-debug [optionsFileURL] Puts the platform in debug mode and loads the debug
options from the file at the given URL, if specified. This
file indicates which debug points are available for a
plug-in and whether or not they are enabled. If a file path
is not given, the platform looks in the directory that
Application Developer was started from for a file called
".options". Note that relative URLs are not allowed.

-consolelog Mirrors the Eclipse platform's error log to the console


used to run Eclipse. Handy when combined with -debug.

-setworkspace This flag forces Application Developer to display a


prompt dialog for selecting of the workspace directory.

24 WebSphere Studio Application Developer Version 5 Programming Guide


Setting the workspace with a prompt dialog
If you specify the flag -setworkspace, Application Developer displays a startup
dialog for selecting the workspace directory (Figure 2-2).

Figure 2-2 Select workspace

Do not select the check box Use this workspace as the default..., otherwise you
are not prompted again.

Tip: If you want to work with multiple workspaces create a duplicate startup
icon for Application Developer and use the -data flag to point to the
workspace.

All other startup parameters are described in Application Developer’s help facility.

Memory consideration
Use the -vmargs flag to set limits to the memory that is used by Application
Developer.

For example, with only 512 MB RAM you may be able to get better performance
by limiting the memory:
-vmargs -Xmx150M

You can also modify VMArgs initialization parameters in the wsappdev.ini file (in
the installation directory):
VMArgs=-Xms64M -Xmx150M -Xquickstart -Xgcpolicy:optavgpause

These arguments significantly limit the memory utilization. Setting the -Xmx
argument below 150M does begin to degrade performance.

For more information on memory management for the built-in WebSphere server,
see “Environment page” on page 547.

Chapter 2. Setting up your Workbench and workspace preferences 25


Application Developer’s log files
Application Developer provides logging facilities for plug-in developers to log and
trace important events, primarily expected or unexpected errors. Log files are a
crucial part of the Application Developer problem determination process.

The only reason to use log files is if you encounter unexpected program behavior.
In some cases, an error message tells you explicitly to look at the error log.

There are two main log files in the .metadata directory of the workspace folder:
򐂰 .log—The .log file is used by the Workbench to capture errors, and any
uncaught exceptions from plug-ins. The .log file is cumulative, each new
session of Application Developer appends its messages to the end of the .log
file without deleting any previous messages. This enables you to see a history
of past messages over multiple Application Developer sessions, each one
starting with the !SESSION string.
򐂰 LoggingUtil.log—The LoggingUtil.log file is provided by the Application
Developer specific tools (a set of plug-ins added on top of the Workbench).
The Application Developer plug-ins use LoggingUtil.log to log various
events, errors, and caught exceptions through a logging API.

Both log files are ASCII files and can be viewed with any text editor.

Preferences
Application Developer’s preferences can be modified by selecting Window ->
Preferences from the menu bar. Opening the preferences displays the dialog
shown in Figure 2-3.

In the left pane you can navigate through many entries. Each entry has its own
preferences page, where you can change the initial options.

This section describes the most important options. Application Developer’s help
manual contains a complete description of all options available in the preferences
dialogs.

Tip: Each page of Application Developer’s preferences dialog contains a


Restore Defaults button. When you click this button, Application Developer
restores the settings of the current dialog to its initial values.

26 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 2-3 Workbench preferences

Automatic builds
By default, builds in Application Developer are done automatically whenever a
resource has been modified and saved. If you require more control regarding
builds you can disable the auto-building feature. To perform a build you have to
explicitly start it. This may be a desirable in cases where you know that building is
of no value until you finish a large set of changes.

If you want to turn off the automatic build feature, select Windows -> Preferences
-> Workbench and deselect the Perform build automatically on resource
modification check box (see previous Figure 2-3).

Chapter 2. Setting up your Workbench and workspace preferences 27


In this dialog you can also specify whether or not you want unsaved resources to
be saved before performing a manual build. Check the Save all modified
resources automatically prior to manual build check box to enable this feature.

File associations
The File Associations preferences page (Figure 2-4) enables you to add or
remove file types recognized by the Workbench. You can also associate editors
or external programs with file types in the file types list.

Figure 2-4 File associations preferences

The top right pane allows you to add and remove the file types. The bottom right
pane allows you to add or remove the associated editors.

If you want to add, for example, the Internet Explorer as an additional program to
open your .gif files, select *.gif from the file types list and click Add next to the
associated editors pane.

28 WebSphere Studio Application Developer Version 5 Programming Guide


A new dialog opens (Figure 2-5) where you have to select the External Programs
option, then click Browse and select iexplore.exe from the folder where Internet
Explorer is installed and confirm the dialog with Open.

Figure 2-5 File association editor selection

Confirm the Editor Selection dialog with OK and you will notice that the program
has been added to the editors list. Optionally you can set this program as the
default program for this file type by clicking Default.

Now you can open the file by using the context menu on the file and select Open
With and select the appropriate program.

Local history
A local edit history of a file is maintained when you create or modify a file. A copy
is saved each time you edit and save the file. This allows you to replace the
current file with a previous edit or even restore a deleted file. You can also
compare the content of all the local edits. Each edit in the local history is uniquely
represented by the data and time the file has been saved.

Note: Only files have local history. Projects and folders do not have a local
history.

Chapter 2. Setting up your Workbench and workspace preferences 29


To compare a file with the local history, select Compare With -> Local History
from its context menu. To replace a file with an edit from the local history, select
Replace With -> Local History from its context menu.

Select Window -> Preferences -> Workbench -> Local History to open its
preferences page (Figure 2-6).

Figure 2-6 Local history preferences

Table 2-2 explains the options for the local history preferences.

Table 2-2 Local history settings


Option Description

Days to keep files Indicates for how many days you want to maintain changes
in the local history. History state older than this value will be
lost.

Entries per file This option indicates how many history states per file you
want to maintain in the local history. If you exceed this value,
you will lose older history to make room for new history.

Maximum file size (MB) Indicates the maximum size of individual states in the history
store. If a file is over this size, it will not be stored.

30 WebSphere Studio Application Developer Version 5 Programming Guide


Perspectives preferences
The Perspectives preferences page enables you to manage the various
perspectives defined in the Workbench. To open the page, click Window ->
Preferences -> Workbench -> Perspectives (Figure 2-7).

Figure 2-7 Perspectives preferences

Here you can change the following options:


򐂰 Open a new perspective in the same or in a new window
򐂰 Open a new view within the perspective or as a fast view (docked to the side
of the current perspective)
򐂰 Open a new project in the same window, in a new window or do not switch the
perspective

Chapter 2. Setting up your Workbench and workspace preferences 31


There is also a list with all available perspectives where you can select the
default perspective. If you have added one or more customized perspectives you
can delete them here if you want to.

Internet preferences
When using Application Developer and working within an intranet, you may want
to use a proxy server to get across the firewall to access the Internet.

To be able to access the Internet from Application Developer, you have to set
preferences for the HTTP proxy server within the Workbench. You can do this by
clicking Window -> Preferences and selecting Internet (Figure 2-8).

Figure 2-8 Internet preferences

32 WebSphere Studio Application Developer Version 5 Programming Guide


Java development preferences
Application Developer provides a number of coding preferences. Some of these
are described in this section. Chapter 5, “Developing Java applications” on
page 93 also provides information regarding these preferences and Java coding.

Java classpath variables


Application Developer provides a number of default classpath variables.
classpath variables can be used in a Java build path to avoid a reference to the
local file system. Using a variable entry, the classpath only contains a variable.
This is a good idea when developing within a team as the team members do not
have to change their directory structure.

Depending on the type of Java coding you plan to do, you may have to add
variables pointing to other code libraries. For example, this can be driver classes
to access relational databases or locally developed code that you would like to
reuse in other projects.

Once you have created a Java project, you can add any of these variables to the
project’s classpath. Chapter 5, “Developing Java applications” on page 93
provides more information on adding classpath variables to a Java project.

To view and change the default classpath variables, click Window -> Preferences
and select Java -> Classpath Variables from the list. A list of the existing
classpath variables is displayed as shown in Figure 2-9.

You can create, edit and remove variables by using this dialog. Click New to add
a new variable. A new dialog comes up where you have to enter the name of the
variable and specify its path and file.

Chapter 2. Setting up your Workbench and workspace preferences 33


Figure 2-9 Classpath variables preferences

Figure 2-10 shows the New Variable Entry dialog with a DB2Java variable that
points to the DB2 JDBC driver class. The name of the file containing the class,
db2java.zip, is specified along with the file system path to it.

Figure 2-10 New Variable Entry dialog

34 WebSphere Studio Application Developer Version 5 Programming Guide


Appearance of Java elements
The page Java -> Appearance provides a dialog with some settings regarding the
appearance of Java elements in viewers. Here you can change the following
options:
򐂰 Show method return types, methods in views display their return types.
򐂰 Show override indicators in outline and hierarchy displays an indicator for
overridden and implemented methods in the Outline and the Type Hierarchy
views.
򐂰 Show members in Package Explorer, if enabled, displays Java elements
below the level of Java files and Class files as well
򐂰 Compress package name segments, if enabled, compresses package names
according to the compression pattern
򐂰 Stack views vertically in the Java Browsing perspective stacks the views in the
Java Browsing perspective vertically rather than horizontally

Code formatter
The Java editor in the Workbench can be configured to format code in
conformance with personal preferences or team standards. When setting up the
Workbench you can decide what formatting should be applied.

To modify the default code formatting select Windows -> Preferences -> Java ->
Code Formatter as shown in Figure 2-11.

Use the tabs at the top of the page to modify various aspects of the code
formatting. The sample code in the bottom right pane shows you a preview of the
effects of changes that you make.

The code formatting options are almost self explaining. However, a detailed
description of each option is provided in Application Developer’s help manual.

Note: To apply the formatting rules defined here, select Format from the Java
editor context menu. Some formatting, for example indenting of braces, will be
done on the fly while you are editing the source code.

Chapter 2. Setting up your Workbench and workspace preferences 35


Figure 2-11 Code Formatter preferences

Compiler options
Problems detected by the compiler are classified as either warnings or errors.
The existence of a warning does not affect the execution of the program. The
code executes as if it had been written correctly. Compile-time errors (as
specified by the Java Language Specification) are always reported as errors by
the Java compiler.

For some other types of problems you can, however, specify if you want the Java
compiler to report them as warnings, errors or to ignore them. To change the
default settings, use the Window > Preferences > Java > Compiler preferences
page (Figure 2-12).

36 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 2-12 Java compiler preferences dialog

Note: The Java compiler can create .class files even in presence of
compilation errors. In the case of serious errors (for example, references to
inconsistent binaries, most likely related to an invalid build path), the Java
builder does not produce any .class file.

Java Editor settings


By default the Java editor will use the standard Workbench font. If you want to
change the font, click Windows -> Preferences -> Java -> Editor and click
Change in the Editor dialog.

Chapter 2. Setting up your Workbench and workspace preferences 37


Besides the font, the following Java editor preferences can be set on this page:
򐂰 Appearance
򐂰 Syntax
򐂰 Code Assist
򐂰 Problem Indication

Figure 2-13 shows the Java editor preferences dialog.

Figure 2-13 Java editor preferences

There are a number of options for the code assist feature, which specify the
behavior and appearance of code assist. A description of how to use the code
assist feature is provided in “Code assist” on page 118. Also Application
Developer’s help manual contains a detailed description of each option of the
code assist feature.

38 WebSphere Studio Application Developer Version 5 Programming Guide


Installed JREs
Application Developer allows you to specify which Java Runtime Environment
(JRE) should be used by the Java builder. By default the standard Java VM that
comes with Application Developer is used, but if you have special requirements
you may want to add another JRE to be used as default or for special projects.

Select Window -> Preferences -> Java -> Installed JREs to display the dialog as
shown in Figure 2-14.

Figure 2-14 Installed JREs

By default, the JRE used to run the Workbench will be used to build and run Java
programs. It appears with a check mark in the list of installed JREs. You can add
another JRE and indicate whether it should be the default JRE or not.

When setting up the project you can also choose which of the JREs you would
like to use. If you do not explicitly specify the JRE for the project, the default JRE
is used.

Chapter 2. Setting up your Workbench and workspace preferences 39


You can either add, edit or remove a JRE by using this dialog. To add a new JRE
click Add. This brings up a new dialog (Figure 2-15).

Figure 2-15 Add JRE dialog

In the JRE type field, select the type of JRE you want to add from the drop-down
list and enter a unique name in the JRE name field. In the JRE home directory
field, type or click Browse to select the path to the root directory of the JRE
installation (usually the directory containing the bin and lib directories for the
JRE). This location is checked automatically to make sure it is a valid path.

In the Javadoc URL field, type or click Browse to select the URL location. The
location is used by the Javadoc export wizard as a default value. If you want to
use the default libraries and source files for this JRE, select the Use default
system libraries check box. Otherwise, clear it and customize as desired. Source
can be attached for the referenced JARs as well.

Javadoc documentation
Application Developer supports the creation of Javadoc documentations.
Javadoc is the tool from Sun Microsystems for generating API documentation in
HTML format from doc comments in source code.

40 WebSphere Studio Application Developer Version 5 Programming Guide


For more information regarding Javadoc, see this Web site:
http://java.sun.com/j2se/javadoc/

The JDT uses the Javadoc command (typically available in JDK distributions) to
generate Javadoc documentation from source files. Before you create Javadoc
documentation, you have to set the location of the Javadoc command.

Select Window -> Preferences -> Java -> Javadoc to open the Javadoc
preferences page (Figure 2-16).

Figure 2-16 Javadoc preferences

In the Javadoc command field you have to enter the absolute path to the Javadoc
command. A javadoc.exe file is located any JDK installed on your system, for
example, the JDK within the built-in WebSphere Application Server:
<wsadhome>\runtimes\base_v5\java\bin\javadoc.exe

Chapter 2. Setting up your Workbench and workspace preferences 41


Once you have set the Javadoc command, you can start creating Javadoc
documentation. Therefore, select the set (containing one or more elements) of
packages, source folders or projects for which you want to generate Javadoc
documentation. Then open the Export wizard by selecting File -> Export from the
menu bar and Javadoc and click Next. Now you have to go through three pages
of a wizard to customize the Javadoc export:
򐂰 In the first page of the wizard, select the types for which Javadoc will be
generated and the members with visibility. Also specify the destination folder
where the documentation should be created.
򐂰 In the second page of the wizard, you can specify a style sheet, the document
title, document tags and basic options as well as the referenced classes to
which Javadoc should create links.
򐂰 In the third page of the wizard you can specify some extra Javadoc options
and save the settings of the export as an Ant script.

For an example of Javadoc generation see “Javadoc” on page 133.

Organize imports
You can specify how you want the Java editor to handle imports when using the
automatic import generation feature. For more information on this feature see
“Import generation” on page 120.

In the Organize Imports preferences (Figure 2-17) you can specify the order of
the import statements. You can also control at what stage <package name>.*
import statements should be generated rather than fully qualified import
statements. The default number of fully-qualified import statements that are
allowed from the same package before <package>.* is 99.

Use the Up and Down buttons to change the order to imports. You can also add,
edit and remove imports. To add a new import entry, click New.

In the new dialog, simply type the package name or the package name prefix you
would like a add to the import statements list and confirm the dialog with OK.

Tip: You can also save and load your import statements settings by using the
Load and Save buttons. This might be a good idea when working in a team
where you have to apply coding standards.

42 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 2-17 Organize Imports preferences

Refactoring
Refactoring refers to the process of moving or renaming Java elements. A more
detailed description about Application Developer’s refactoring capabilities and
the refactoring preferences is provided in “Refactoring” on page 122.

Templates
Application Developer also provides templates. Templates are often reoccurring
source code patterns. The JDT of Application Developer offers support for
creating, managing, and using templates.

You can use a template in the Java editor by pressing Ctrl-Space (see “Code
assist” on page 118 for more information) and the templates appear in the
presented list. Note that the list is filtered as you type, so typing a few first
characters of a template name will reveal it.

Chapter 2. Setting up your Workbench and workspace preferences 43


The symbol in front of each template, shown Figure 2-18, in the code assist list is
colored yellow, so you can distinguish between a template and a Java statement
entry.

Figure 2-18 Using templates for code assist

The Templates preference page allows you to create new and edit existing
templates. A template is a convenience for the programmer to quickly insert often
reoccurring source code patterns.

To open the Templates preferences page, click Window -> Preferences -> Java
and select Templates from the Java tree, as shown in Figure 2-19.

Figure 2-19 Templates preferences

44 WebSphere Studio Application Developer Version 5 Programming Guide


The Templates preferences page opens where you can perform the following
tasks:
򐂰 Create templates
򐂰 Edit existing templates
򐂰 Remove templates
򐂰 Import templates from XML files
򐂰 Export selected or all templates to a XML file
򐂰 Enable or disable selected or all templates for code assist.

To create a new template, click New. The New Template dialog comes up as
shown in Figure 2-20. Here you have to enter the name of the template, the
description and its pattern.

Figure 2-20 Creating a new template

The name you enter here, will be displayed in the code assist list when you press
Ctrl-Space. In the Pattern field you have to enter the actual code you want to be
inserted by using the template.

There are also some predefined variables available. These variables can be
inserted by clicking Insert Variable. This will bring up a list and a brief description
of the variable.

Tip: Application Developer provides additional templates that are located in


the following directory of Application Developer’s installation:
wstools\eclipse\plugins\com.ibm.etools.jbcf.codegen_5.0.1\Examples\Templates

You can import all templates in a directory by selecting the AllTemplates.xml


files of the specific sub directory.

Chapter 2. Setting up your Workbench and workspace preferences 45


To import these templates, launch the templates preferences dialog and click
Import to open a file browser, and then navigate to the directory containing the
template files.

You can also enable or disable specific or all templates by either using the check
boxes in front of the template or using the Enable All or Disable All buttons.

Exporting templates exports them to an XML file in a folder you can specify.

Summary
In this chapter we covered the basic functionality of the Workbench and the
underlying Java development environment.

In particular, we discussed setting up workspaces and preferences.

46 WebSphere Studio Application Developer Version 5 Programming Guide


3

Chapter 3. Perspectives, views, and


editors
Application Developer supports a role-based development model. It does so by
providing several different perspectives on the same project. Each perspective is
suited for a particular role and provides the developer with the necessary tools to
work on the tasks associated with that role.

This chapter provides information about these topics:

Integrated development environment (IDE)


Resource perspective XSL Debug perspective
Java perspective Plug-in Development perspective
Java Browsing perspective Data perspective
Java Type Hierarchy perspective Debug perspective
Web perspective Profiling perspective
J2EE perspective Component Test perspective
Server perspective CVS Repository Exploring perspective
XML perspective Install/Update perspective

© Copyright IBM Corp. 2003. All rights reserved. 47


Integrated development environment (IDE)
An integrated development environment (IDE) is a set of software development
tools such as source editors, compilers, and debugger, that are accessible from
a single user interface.

In Application Developer, the IDE is called the Workbench. Application


Developer’s Workbench supports customizable perspectives that support
role-based development. It provides a common way for all members of a project
team to create, manage, and navigate resources easily. It consists of a number
of interrelated views and editors.

Views provide different ways of looking at the resource you are working in.
Editors allow you to create and modify the resource. Perspectives are a
combination of views and editors that show various aspects of the project
resource, and are organized by developer role or task. For example, a Java
developer would work most often in the Java perspective, while a Web designer
would work in the Web perspective.

Several perspectives are provided in Application Developer, and team members


also can customize them, according to their current role of preference. You can
open more than one perspective at a time, and switch perspectives while you are
working with Application Developer.

Before describing the perspectives, we take a look at Application Developer’s


help feature.

Application Developer help


Application Developer’s online help system provides access to the
documentation, and lets you browse, search, and print help content. It also has a
full-text search engine included as well as context-sensitive help.

Application Developer provides the help content in a separate window that you
can open by selecting Help -> Help Contents from the menu bar (Figure 3-1).

48 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-1 Help windows bookshelf

In the new help window you see the available books in the left pane and the
content in the right pane. When selecting a book in the left pane, the appropriate
table of contents opens up and you can select a topic.

At any time, you can return to the bookshelf by clicking the Table of Contents
button .

You can navigate through the help documents by using the Go Back and Go
Forward buttons on the top right side. There are also buttons for printing the
document, toggling and synchronizing the navigation. Synchronizing the
navigation synchronizes the navigation frame with the current topic. This is
helpful if you have followed several links to related topics in several files, and
want to see where the current topic fits into the navigation path.

Figure 3-2 shows the help window with the table of contents of the Application
developer information book.

Chapter 3. Perspectives, views, and editors 49


Figure 3-2 Application Developer help

Application Developer’s help manual contains a lot of useful information about


the tool and technologies. It provides information about the different concepts
used by the Workbench, the different Tasks you can do within the Workbench,
and some useful samples and tutorials.

The Search field allows you to do a search over all books. The link Advanced
Search opens a dialog box where you can specify your search in more detail
(Figure 3-3).

Note: The first time you search the online help, the help system initiates an
index-generation process. This process builds the indexes for the search
engine to use. It may take several minutes, depending on the amount of
documentation. Each time you add or modify the documentation set (for
example, when you install a new feature or update an existing one), the index
will be updated to reflect the new information set.

50 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-3 Advanced Search dialog for help

Enter your search expression in the appropriate field of the search dialog and
select the set of books to searched. Click Search to start your search.

Perspectives
Perspectives provide a way to look at a project through different “glasses”.
Depending on the role you are in and/or the task you have to do, you open a
different perspective. A perspective defines an initial set and layout of views and
editors for performing a particular set of development activities, for example, EJB
development, profiling, and so forth. You can change the layout and the
preferences and save a perspective that you can have customized, so that you
can open it again later.

Views
Views provide alternative presentations of resources or ways of navigating
through the information in your Workbench. For example, the Navigator view
displays projects and other resources that you are working as a folder hierarchy.
Application Developer provides synchronization between different views and
editors.

A view might appear by itself, or stacked with other views in a tabbed notebook
arrangement. A perspective determines the views that you are likely to need. For
example, the Java perspective includes the Packages view and the Hierarchy
view to help you work with Java packages and hierarchies.

Chapter 3. Perspectives, views, and editors 51


Editors
When you open a file, Application Developer automatically opens the editor that
is associated with that file type. For example, an HTML editor is opened for
.html, .htm and .jsp files while a Java editor is opened for .java and .jav files.

Editors that have been associated with specific file types open in the editor area
of the Workbench. By default, editors are stacked in a notebook arrangement
inside the editor area. You also have the option of tiling open files. However, if
there is no associated editor for a resource, Application Developer will attempt to
launch an external editor outside the Workbench.

Perspective layout
Most of Application Developer’s perspectives use a similar layout. Figure 3-4
shows a layout of a perspective which is quite common.

Menu bar / Toolbar

Source Editor (Code) Outline view


Navigator view Design View (Visual Editor) Properties
Package view
Explorer view
Hierarchy view synchronize

synchronize
synchronize

Task view (show compilation errors)


Search view (display search results)
Console view (program output, server status)

Figure 3-4 Perspective layout

52 WebSphere Studio Application Developer Version 5 Programming Guide


On the left side you have views that help you to navigate through your project’s
files, where in the middle of the Workbench you find a larger pane, usually the
source editor or the design pane. This allows you to change the code and design
of files in your project. The right pane usually contains the Outline or the
Properties views.

In some perspectives you can see that the editor pane is a little larger and the
Outline or Properties view is placed at the bottom left corner of the perspective.

The content of the views is synchronized. This means that if you change a value
in the Properties view, for example, the Editor view is automatically updated to
reflect the change.

Switching perspectives
There are two ways to open another perspective. You can use the Open a
Perspective icon in the top left corner of the Workbench working area and
select the appropriate perspective from the list. Alternatively, you can click
Window -> Open Perspective and either select a perspective or click Other to
bring up the Select Perspective dialog (Figure 3-5).

Figure 3-5 Select Perspective dialog

Select the perspective you would like to open and confirm the dialog with OK.

Chapter 3. Perspectives, views, and editors 53


Tips:
򐂰 The name of the perspective is shown in the window title area.
򐂰 The vertical toolbar at the left side of the Workbench, called the shortcut
bar, provides icons that you can use to quickly switch between the
perspectives that you have opened.
򐂰 To close a perspective, right-click that perspective's button on the shortcut
bar and select Close.
򐂰 After working with Application Developer for some time, you have opened
several perspectives. You might have the impression that Application
Developer is working slower. It is good practice to close perspectives,
because they can consume a lot of memory; hence, they slow down the
overall performance.

Specifying the default perspective


The J2EE perspective is Application Developer’s default perspective. You can
also change the default perspective from the preferences dialog:
򐂰 From the main menu bar, select Window > Preferences -> Workbench ->
Preferences.
򐂰 Select the perspective that you want to define as the default, and click Make
Default.
򐂰 Click OK.

Organizing and customizing perspectives


Application Developer provides the following features to organizing perspectives:
򐂰 Open perspectives
򐂰 Customize perspectives
򐂰 Reset perspectives
򐂰 Save perspectives
򐂰 Close perspectives

These actions can be found in the Window menu. To customize a perspective,


click Window -> Customize Perspective. The Customize Perspective dialog
opens (Figure 3-6).

54 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-6 Customize perspective

In the dialog you can use the check boxes to select which elements you want to
see on drop-down menus of the selected perspective. Items you do not select
are still accessible by clicking the Other menu option. These options can be
customizes:
򐂰 The New menu
򐂰 The Window -> Open Perspective menu
򐂰 The Window -> Show View menu
򐂰 Action sets (icons) that show up on the toolbar

You can also customize a perspective by adding, closing, moving, and resizing
views. To add a new view to the perspective, simply click Window -> Show View
and select the view you would like to add to the currently open perspective.

You can move a view to another pane by using drag and drop. To move a view,
simply select its title bar, drag the view, and drop it on top of another view. Both
views are now stacked and you can use the tabs at the bottom of the view to
switch between them.

While you drag the view, the mouse cursor changes into a drop cursor. The drop
cursor indicates what will happen when you release the view you are dragging:
The floating view appears below the view underneath the cursor.

Chapter 3. Perspectives, views, and editors 55


The floating view appears to the left of the view underneath the
cursor.
The floating view appears to the right of the view underneath the
cursor.
The floating view appears above the view underneath the cursor.

The floating view appears as a tab in the same pane as the view
underneath the cursor. You can also drop the view on the
perspective toolbar to make it a fast view.
You cannot dock the floating view at this point.

Once you have configured the perspective to your preferences, you can save it
as your own perspective by selecting Window -> Save Perspective As.

To restore the currently opened perspective to its original layout, select Window
-> Reset Perspective.

Tip: You can double-click a view’s title bar to maximize the view. Double-click
again to restore it to the original size. Alternatively, you can press CTRL-M to
maximize and restore the view.

Perspectives walkthrough
In this section we describe the perspectives that we are using to develop, test,
and deploy the samples in this document.

J2EE perspective
The default perspective of Application Developer is the J2EE perspective, shown
in Figure 3-7. Application Developer lets you change the default perspective. See
“Specifying the default perspective” on page 54 for an instruction to change the
default perspective.

The J2EE perspective contains the following views that you would typically use
when you develop resources for enterprise application, EJB, Web, and
application client, or connector projects or modules:
򐂰 J2EE Navigator view—This view provides a project and Java-centric view of
your J2EE and other projects in the workspace. It will show the project
resources and not the individual model objects as in the J2EE Hierarchy view.
For Java projects, the source folders will show the packaged based grouping

56 WebSphere Studio Application Developer Version 5 Programming Guide


of the files much like the Java Packages view. Note that the four J2EE
module types (EJB, application client, Web, and connector) are also Java
projects.

Figure 3-7 J2EE perspective

򐂰 J2EE Hierarchy view—Provides a hierarchical view of the content models


for J2EE resources found in the J2EE projects. This view provides you with
an easy way to view deployment descriptor trees of your J2EE applications
and modules, and to quickly navigate to editors for component objects.
Additionally, it provides links to EJB to RDB mapping, and for configuring
applications to run on a J2EE application server.
򐂰 Outline view—Shows the outline of the file that you are editing. The Outline
view changes as you change open files in different editors or select different
editor tabs.
򐂰 Tasks view—Lists the to-do items that you have entered, plus any
automatically logged problems, warnings, or other information associated
with the selected project. The former is true if you have this option enabled.

Chapter 3. Perspectives, views, and editors 57


You can double-click an item to address the specific problem in the
appropriate resource.
򐂰 Properties view—Provides a tabular view of the properties and associated
values of objects in files you have open in an editor. For example, you can
specify converters in the Properties view of the Mapping editor.
򐂰 Status bar—Provides a description of the location of selected objects in the
J2EE Hierarchy and J2EE Navigator views in the left side. When file and
deployment descriptors are open, it shows the read-only state of the files and
the line and column numbers when applicable. Sometimes when long
operations run, a status monitor will appear in the status bar, along with a
button with a stop sign icon. Clicking the stop sign will stop the operation
when the operation can be cancelled.

Resource perspective
The Resource perspective is a very simple perspective (Figure 3-8).

Figure 3-8 Resource perspective

By default it shows these elements:

58 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Navigator view—This view provides a hierarchical view of all the resources
in the Workbench. By using this view you can open files for editing, or select
resources for operations such as exporting.
򐂰 Outline view—This view displays an outline structure of the file that is
currently open in the editor area, and lists structural elements. The contents
of the outline view are editor-specific.
򐂰 Editor pane—Depending on the type of file you are editing, the appropriate
editor is displayed in the editor area. For example, if you are editing a .java
file, the Java editor displays in the editor area.

Web perspective
Web developers can use the Web perspective to build and edit Web resources,
such as servlets, JSPs, HTML pages, Style sheets and images, as well as the
deployment descriptor file, web.xml (Figure 3-9).

Figure 3-9 Web perspective

Chapter 3. Perspectives, views, and editors 59


The Web perspective contains a number of views, such as:
򐂰 J2EE Navigator view—The same view is included in the J2EE perspective.
򐂰 Page Designer—Page Designer allows you to work with HTML files, JSP
files, and embedded JavaScript. Within the Page Designer, you can move
among three pages that provide different ways for you to work with the file
that you are editing. You can switch pages by clicking the tabs at the bottom
of the editor pane. These pages work in conjunction with the Workbench
Outline and Properties views, tool bar buttons, menu bar options, and context
menus.
– Design—The Design page of Page Designer is the WYSIWYG mode for
editing HTML and JSP files. As you edit in the Design page, your work
reflects the layout and style of the Web pages you build without the added
complexity of source tagging syntax, navigation, and debugging. Although
many tasks can also be performed in the same way in the Source page,
the Design page provides full access to Page Designer menu options,
context menu actions, view-specific GUI options (such as those in the
Styles view), and drag and drop behavior.
– Source—The Source page enables you to view and work with a file's
source code directly. The Outline and Properties views both have features
that supplement the Source page.
– Preview—Shows how the current page is likely to look when viewed in a
Web browser. JSPs shown in this view will contain only static HTML
output.
򐂰 Gallery view—Contains a variety of catalogs of reusable files that can be
applied to Web pages. The file types available include images, wallpaper,
Web art, sound files, and style sheet files.
򐂰 Library view—Allows you to catalog and organize reusable programming
objects, such as HTML tagging, JavaScript, and JSP code, along with files
and custom JSP tags. The view can be extended based on additional objects
that you define and include.
򐂰 Outline view—Shows the outline of the file that you are currently editing. For
example, for an HTML file, the Outline view shows the tag structure and
hierarchy within the HTML file. The context menu for any selected tag
enables you to remove the tag, add an attribute to the tag (if any exist or have
not already been specified), add a child tag (if any exist), and add a sibling tag
before or after the tag.
򐂰 Web Structure view—Provides you with a way to navigate through the
various referenced parts of a Web application from a starting point such as a
Web page (JSP or HTML file), an Action mapping, or a global forward. Parts
of a Web application can be JSP files, links, Action mappings, form beans,
and so forth.

60 WebSphere Studio Application Developer Version 5 Programming Guide


The view also give you a general idea of how the different parts of a Web
application are linked together and how different parts reference each other.
The view provides additional information about a part to facilitate Web
application development. Among the information displayed are errors that
may cause a Web application to run incorrectly and data parameters that a
part requires.
򐂰 Attributes view—Provides tabbed pages that allow you to update attributes
for tags selected in files open in the active Web editor. Changes to attribute
value text fields are reflected in the edited file immediately when cursor focus
is changed, or when you press the Enter key. In addition, changes to any of
the controls in the Attributes view are immediately reflected in the edited file.
򐂰 Links view—Shows the resources that the selected file in the J2EE
Navigator view links to or uses. It also shows the files that link to the file
selected in the J2EE Navigator view or are open in Page Designer.
򐂰 Thumbnail view—Shows thumbnails of the images in the selected project,
folder, or file. This view is especially valuable when used in conjunction with
the Gallery view to add images from the artwork libraries supplied by
WebSphere Studio to your page designs. You can drag and drop from this
view into the J2EE Navigator view or the Design or Source page of Page
Designer.
򐂰 Styles view—Provides guided editing for cascading style sheets and
individual style definitions for HTML elements.
򐂰 Colors view—Allows you to apply colors from a palette (or custom colors) to
selected objects in the editing area.
򐂰 Servers view—Lists servers defined for the project and their status.

Java perspective
The Java perspective (Figure 3-10) supports developers who create, edit and
build Java code.

The Java perspective consists of an editor area and displays by default the
following views:
򐂰 Package Explorer view—This is displayed by default in the Java perspective
and shows the Java element hierarchy of all the Java projects in your
Workbench. It provides you with a Java-specific view of the resources shown
in the Navigator. The element hierarchy is derived from the project's build
classpath. For each project, its source folders and referenced libraries are
shown in the tree view. From here you can open and browse the contents of
both internal and external JAR files.

Chapter 3. Perspectives, views, and editors 61


Java Editor

Fields/Methods

Packages/Classes

Tasks

Figure 3-10 Java perspective

򐂰 Hierarchy view—Can be opened for a selected type to show its super


classes and subclasses. It offers three different ways to look at a class
hierarchy:
– The Type Hierarchy displays the type hierarchy of the selected type, that
is, its position in the hierarchy, along with all its Superclass and
subclasses
– The Supertype Hierarchy displays the supertype hierarchy of the selected
type
– The Subtype Hierarchy displays the subtype hierarchy of the selected type
More information about the Hierarchy view is provided in “Java Type Hierarchy
perspective” on page 64.
򐂰 Outline view—Shows the elements (imports, class, fields, and methods),
that exist in the source file that is currently open in the editor. Clicking an item
in the outline will position you in the editor view at the line where that structure
element is defined.

62 WebSphere Studio Application Developer Version 5 Programming Guide


See Chapter 5, “Developing Java applications” on page 93 for more information
about how to work with the Java perspective.

Tip: To get a larger Java editor view, you can move the Outline view and
place it tabbed next to the Package Explorer and Hierarchy view.

Java Browsing perspective


The Java Browsing perspective also addresses Java developers, but it provides
different views (Figure 3-11).

Java Editor

Figure 3-11 Java Browsing perspective

The Java Browsing perspective also displays an editor area, but unlike the Java
perspective, it displays by default the following views: Projects, Packages,
Types, Members, and an editor pane.

Chapter 3. Perspectives, views, and editors 63


Java Type Hierarchy perspective
This perspective also addresses Java developers and allows them to explore a
type hierarchy. It can be opened on types, compilation units, packages, projects
or source folders and consists of the Hierarchy view and an editor (Figure 3-12).

Java Editor

Figure 3-12 Java Type Hierarchy perspective

By default this perspective displays the Hierarchy view and the Editor pane. The
Hierarchy view does not display a hierarchy until you select a type (Figure 3-13).

Figure 3-13 Hierarchy view - initial

64 WebSphere Studio Application Developer Version 5 Programming Guide


To open a type in the Hierarchy view, open the context menu from a type in the
Package Explorer, the Editor, the Navigator or the Outline view and select Open
Type Hierarchy.

Once you have selected a type and opened it to the type hierarchy, the type
hierarchy is displayed in the Hierarchy view. Figure 3-14 shows the Hierarchy
view of the Java Swing class JList.

Figure 3-14 Hierarchy view

Icons are provided at the top of the Hierarchy view to display the type hierarchy
, the supertype hierarchy (bottom-up) , or the subtype hierarchy
(top-down) . The supertype hierarchy also shows interfaces that are
implemented for each class in the hierarchy.

Chapter 3. Perspectives, views, and editors 65


Server perspective
The Server perspective (Figure 3-15) is used to manage the server test
environments you use when testing, debugging, and profiling your applications.

Figure 3-15 Server perspective

The perspective has the following views:


򐂰 Server Configuration view—Shows the servers and server configurations
created. By clicking the down arrow and selecting Standard or Advanced the
view can be slightly customized.
򐂰 Servers view—Provides another view of the servers and also displays the
console which shows the stdout output from each server.

Servers can be controlled (start, stop, restart) either using the Server
Configuration view or the Servers view. Select the server and choose the
appropriate action from its context menu. If a server configuration is opened (by
double-clicking it) it opens up in the upper right pane and allows for editing of its
properties.

66 WebSphere Studio Application Developer Version 5 Programming Guide


XML perspective
The XML perspective (Figure 3-16) contains several editors and views that can
help a developer in building XML files, XML schemas, DTDs, style sheets, and
integrating between data extracted from relational databases and XML.

Figure 3-16 XML perspective

The XML perspective contains four sections:


򐂰 Outline view—Shows the Outline view for the active editor; in this case the
XML editor is active.
򐂰 Navigator view—Displays the folders, and files of the project.
򐂰 Tasks view—Shows the problems and errors to be fixed.
򐂰 Editor pane—Active editors.

Chapter 3. Perspectives, views, and editors 67


XSL Debug perspective
The XSL Debug perspective is used when you transform XML files. This
perspective and its capabilities are described in the section “Debugging XSL” on
page 369.

Data perspective
The Data perspective lets you access relational databases tools and you can
create and manipulate the data definitions for your project. This perspective also
lets you browse or import database schemas in the DB Servers view, create and
work with database schemas in the Data Definition view, and change database
schemas in the table editor. You can also export data definitions to another
database installed either locally or remotely. The Data perspective is shown in
Figure 3-17.

Figure 3-17 Data perspective

68 WebSphere Studio Application Developer Version 5 Programming Guide


These views characterize the Data perspective:
򐂰 Data Definition view—This view of lets you work directly with data
definitions, defining relational data objects. It can hold local copies of existing
data definitions imported from the DB Servers view, designs created by
running DDL scripts, or new designs that you have created directly in the
Workbench. Using the Data Definition view, you can also rename logical
objects.
򐂰 DB Servers view—Using this view, you can:
– Create a new database connection.
– Connect to existing databases and view their designs.
– Reconnect to a database if your database connection was disconnected.
– Disconnect from a database connection if you are connected.
– Import the designs to another folder in the Data Definition view, where you
can extend or modify the designs.
– Refresh the database objects defined to a database connection.
– Delete a database connection.

Debug perspective
Application Developer provides a Debug perspective that supports testing and
debugging of your applications.

The Debug perspective, shown in Figure 3-18, contains five panes:


򐂰 Top left—Shows Debug and Servers views.
򐂰 Top right—Shows Breakpoints, Expressions, Variables and Display views.
򐂰 Middle left—Shows the Source, the Design view, or the Web browser. In the
Source view, the line with the current error or breakpoint is displayed (where
the process stopped).
򐂰 Middle right—Shows the Outline view of the currently displayed source.
򐂰 Bottom—Shows the Console and the Tasks view.

Chapter 3. Perspectives, views, and editors 69


Figure 3-18 Debug perspective

򐂰 Debug view—Displays the stack frame for the suspended threads for each
target you are debugging. Each thread in your program appears as a node in
the tree. If the thread is suspended, its stack frames are shown as child
elements.
If the resource containing a selected thread is not open and/or active, the file
opens in the editor and becomes active, focusing on the source with which
the thread is associated.
The Debug view enables you to perform various start, step, and terminate
debug actions as well as enable or disable step-by-step debugging
򐂰 Variables view—Displays information about the variables in the
currently-selected stack frame.
򐂰 Breakpoints view—Lists all the breakpoints you have set in the Workbench
projects. You can double-click a breakpoint to display its location in the editor.
In this view, you can also enable or disable breakpoints, delete them, or add

70 WebSphere Studio Application Developer Version 5 Programming Guide


new ones. This view also lists Java exception breakpoints, which suspend
execution at the point where the exception is thrown. You can add or remove
exceptions.
򐂰 Expressions view—Data can be inspected in the Expressions view. You can
inspect data from a scrapbook page, a stack frame of a suspended thread,
and other places. The Expressions view opens automatically when the
Inspect command is activated.
򐂰 Display view—Shows the result of evaluating an expression in the context of
the current stack frame. You can evaluate and display a selection either from
the editor or directly from the Display view.

More information about the Debug perspective can be found in “Testing and
debugging” on page 553.

Profiling perspective
Profiling is controlled from the Profiling perspective (Figure 3-19). To open the
perspective, select Window -> Open Perspective -> Other -> Profiling.

Figure 3-19 Profiling perspective

Chapter 3. Perspectives, views, and editors 71


The Profiling perspective contains all the views used in a profiling session. Once
you open the Profiling perspective, the Profiling Monitor view is visible on the top,
left side of the Workbench.

The Profiling Monitor view displays profiling objects such as project folders,
monitors, hosts, processes, and agents that get created during a profiling
session.

On the right of the Workbench, the Profiling perspective offers the following
views, which display data that is collected from a profiling session:
򐂰 Statistical profiling views:
– Package Statistics view
– Class Method Statistics view
– Method Statistics view
– Class Instance Statistics view
– Instance Statistics view
򐂰 Graphical profiling views:
– Execution Flow view
– Object References view
– Method Execution view
– Method Invocation view
– Heap view

More details about these views can be found in “Performance analysis” on


page 666.

Component Test perspective


The Component Test perspective (Figure 3-20) provides a framework for defining
and executing test cases.
򐂰 Definition view—Used to define test cases. This is also where you define the
hosts on which the test cases will run. Once you define the test case element
in the Definition pane, its contents appear in the Outline pane.
򐂰 Outline view—Displays the contents of a test case currently being edited.
Here you add elements to the test case's main block, and once your definition
is complete you prepare it to run and create a test case instance.
򐂰 Execution view—Once you prepare a test case definition to run, a test case
instance is generated in the Execution pane. You can then review the
instance and edit any associated generated code before running the test
case.

72 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-20 Component Test perspective

More information about Component Testing is located in “Component testing” on


page 588.

CVS Repository Exploring perspective


The CVS Repository Exploring perspective (Figure 3-21) lets you connect to
CVS repositories. It allows you to add and synchronize projects with the
workspace and to inspect the revision history of resources:
򐂰 CVS Repositories view—Shows the CVS repository locations that you have
added to your Workbench. Expanding a location reveals the main trunk
(HEAD), project versions and branches in that repository. You can further
expand the project versions and branches to reveal the folders and files
contained within them.
The context menu for this view also allows you to specify new repository
locations. Use the CVS Repositories view to checkout resources from the
repository to the Workbench, configure the branches and versions shown by
the view, view resource history, and compare resource versions.

Chapter 3. Perspectives, views, and editors 73


Figure 3-21 CVS Repository Exploring perspective

Files that exist in the repositories can be viewed by double-clicking them in a


branch or version. This opens the version of the file specified in the file editor,
located at the top right of the workspace.
򐂰 CVS Resource History view—Displays more detailed history of each file.
This view provides a list of all the revisions of a resource in the repository.
From this view you can compare two revisions, replace (get sticky), or revert
the corresponding workspace file to the revision (get contents), or open an
editor on a revision.

More details about using the CVS Repository Exploring perspective can be found
in Chapter 22, “Using Concurrent Versions System” on page 701.

74 WebSphere Studio Application Developer Version 5 Programming Guide


Install/Update perspective
The Install/Update perspective (Figure 3-22) allows you to check to see whether
there are updates for a product's existing features. Working with this perspective
usually requires access to the Internet.

Figure 3-22 Install/Update perspective

The Install/Update perspective contains these views:


򐂰 Install Configuration view—This view allows you to manage your
workspace configuration. The Current Configuration folder shows which local
installation locations are part of the workspace configuration, and which
features are installed in those locations. The Configuration History folder
shows a history of changes made to your workspace configuration. The
Saved Configurations folder show any configurations that were preserved.
򐂰 Feature Updates view—This view allows you to locate and install new
features and feature updates. The view contains three standard folders. The
Sites to Visit folder contains update sites pre-configured by the product you
are using. The Available Updates is a built-in search results folder used for
searching update sites. The My Computer folder is a file explorer that can be
used to navigate to updates located in the file system.
򐂰 Preview view—This view displays detailed information about the current
active selection. Its content changes according to your selection.

Chapter 3. Perspectives, views, and editors 75


For information about how to work with the Update Manager consult Appendix A,
“Product installation” on page 785.

Plug-in Development perspective


You can develop your own Application Developer tools by using the Plug-in
Development Environment (PDE). The PDE provides a set of platform extension
contributions (views, editors, perspectives, etc.) that collectively streamline the
process of developing plug-ins inside the Workbench.

In this book we do not describe how to develop plug-ins for Application


Developer. Figure 3-23 shows the Plug-in Development perspective.

Figure 3-23 Plug-in Development perspective

To learn more about plug-in development, refer to The Java Developer’s Guide
to Eclipse (see “Other publications” on page 818).

76 WebSphere Studio Application Developer Version 5 Programming Guide


Summary
In this chapter we described the perspectives and views that you use with
Application Developer to perform your tasks.

Chapter 3. Perspectives, views, and editors 77


78 WebSphere Studio Application Developer Version 5 Programming Guide
4

Chapter 4. Projects
This chapter introduces the project types and some of the main terms used in
Application Developer.
򐂰 J2EE architecture:
– EAR files
– WAR files
– JAR files
򐂰 Projects and folders
򐂰 Project types:
– Simple project
– Java project
– Web project
– Enterprise Application project
– EJB project
– Application Client project
– Server project
򐂰 Creating a new project

© Copyright IBM Corp. 2003. All rights reserved. 79


J2EE architecture
The Java 2 Platform, Enterprise Edition (J2EE) is a robust suite of middle-ware
application services for server side application development. J2EE is an
extension of the Java 2 Platform, Standard Edition (J2SE).

J2EE makes all Java enterprise APIs and functionality available and accessible
in a well integrated fashion. This helps in simplifying complex problems in the
development, deployment, and management of multi-tier, server-centric
enterprise solutions.

Figure 4-1 shows an overall view comprising the different J2EE technologies.

Applet WebSphere
Container HTTP
SSL
Applet
Web Container EJB Container

JSP Servlet EJB

Java
RMI-IIOP

Java

RMI-IIOP
J2SE
JDBC

JDBC
JNDI

JNDI
Mail
JMS

Mail
JMS
JTA

JTA
JAF JAF

Application HTTP J2SE J2SE


Client SSL
Container

Application
Client
RMI-IIOP

Database
JDBC
JNDI
JMS

J2SE

Figure 4-1 J2EE architecture diagram

Web containers and EJB containers


Containers are basically run-time environments that provide components with
specific services. For example, Web containers provide run-time support to
clients by processing requests through invoking JSPs and servlets and returning
results from the components to the client. Similarly, EJB containers provide

80 WebSphere Studio Application Developer Version 5 Programming Guide


automated support for transaction and state management of EJB components,
as well as look up and security services.

For additional information regarding the J2EE architecture and its technologies,
consult the J2EE specification on Sun’s Web Site:
http://java.sun.com/j2ee

EAR files
Enterprise archive (EAR) files represent a J2EE application that can be deployed
in a WebSphere application server. EAR files are standard Java archive files and
have the file extension .ear. EAR files also contain a deployment descriptor (an
XML file) that describes the contents of the application and contains instructions
for the entire application, such as security settings to be used in the run-time
environment.

An EAR file has the following modules (zero, one, or more of each type):
򐂰 Web modules
򐂰 EJB modules
򐂰 Application client modules
򐂰 Utility JAR files required by other modules

WAR files
Web archive (WAR) files contain all the components of a Web application. These
components are usually:
򐂰 HTML files
򐂰 CSS files
򐂰 JSP files
򐂰 Servlets
򐂰 Compiled Java files
򐂰 Images

JAR files
The Java archive (JAR) file format allows you to store multiple files into a single
archive file. Typically, a JAR file contains the class files and additional resources
associated with applets and applications.

EJB modules and utility modules are packaged as JAR files.

Chapter 4. Projects 81
Projects and folders
Application Developer organizes all resources into projects.

A project in Application Developer is the top-level construct for organizing the


different resources. It contains files as well as folders. In the Workbench you can
create different kinds of projects, and they will have a different structure.

Unless not specified differently, projects are created in the workspace directory
of Application Developer’s installation folder. Also, the metadata is stored in the
workspace directory. The .metadata directory of a workspace directory stores
important information about the workspace structure, such as a project’s
reference or a resource’s properties.

A project is either open or closed. When a project is closed, it cannot be changed


in the Workbench and it cannot be referenced from other projects. The resources
of a closed project do not appear in the Workbench, but they do reside in the
local file system.

Tip: Closed projects require less memory. Because they are not examined
during builds, closing a project can improve the build time.

Application Developer’s project types


Application Developer provides different project types for different tasks.

Simple project
A Simple project in Application Developer does not have any default folders and
does not have an associated builder. The files stored inside the project are not
compiled when you select to rebuild all projects in the Workbench.

We will use a simple project in Chapter 6, “Developing database applications” on


page 139.

Java project
A Java project contains Java packages and Java code as .java files and .class
files. Java projects have an associated Java builder that incrementally compiles
Java source files as they are changed. Java projects can be exported as JAR
files or into a directory structure.

82 WebSphere Studio Application Developer Version 5 Programming Guide


Java projects are used for stand-alone applications or to build utility JAR files for
an enterprise application. A detailed example of how to create a new Java
project is provided in “Creating and working with a Java project” on page 94.

Enterprise Application project


Enterprise Application projects contain references to the resources needed for
enterprise applications and can contain a combination of Web modules, EJB
modules, application client modules, and JAR files.

An Enterprise Application project is deployed in the form of an EAR file. In


Application Developer, the modules in an Enterprise Application project are
mapped to other J2EE projects. The mapping information is stored in metadata
files within the Enterprise Application project. The metadata files are used for
exporting the project to an EAR file, and for running the project on the server.

Application Developer mirrors the layout of a J2EE enterprise application


modules with matching project types. For each type of module, a project type
tailored for that purpose is provided (Figure 4-2).

DD = Deployment Descriptor
Application J2EE
Developer EAR Application Application
Project EAR file
DD

application.xml
EJB
Project
Web
EJB Project Web Client
Module Module Module
Client
JAR file WAR file JAR file
Project

Enterprise EJB HTML, Web Client Client


DD Servlet JSP DD Class
Bean GIF, etc. DD

ejb-jar.xml web.xml

Figure 4-2 Application Developer projects for J2EE

We will create an Enterprise Application project together with a Web project in


Chapter 7, “Developing Web applications” on page 179.

Chapter 4. Projects 83
Web project
A Web project contains resources needed for Web applications, such as source
files and metadata, that correspond to the hierarchy of files necessary to deploy
a Web page or Web application. There are two types of Web projects:
򐂰 Static Web project
򐂰 J2EE Web project

A static Web project contains only static content such as HTML pages or images,
and any associated metadata. In addition to static content, J2EE Web projects
can contain additional kinds of resources for Web applications, including servlets,
JSP files, and Java files. J2EE Web projects incur more system overhead
because of additional validation and Java compilation that is automatically
performed by the Workbench. A Web project is deployed as a WAR file.

A step-by-step description of how to create a new Web project is provided in


“Creating a Web project” on page 185. Also, some detailed information regarding
the structure of a Web project is given in “Web project directory structure” on
page 190.

Struts project
With Application Developer Version 5, a Web project with Struts support can be
created. Such a project is tailored to provide an organization suitable for Struts
development, including the Struts runtime, configuration file, a Web diagram
editor, and wizards to create Struts components.

Refer to Chapter 10, “Developing Struts applications” on page 293 for details
about Struts and the support in Application Developer.

EJB project
Enterprise JavaBeans (EJB) projects contain the resources for EJB applications.
The EJB project contains the metadata files (such as the deployment descriptor,
IBM extensions, and RDB mappings) for the EJB application, Java source files,
compiled code for the enterprise beans, and stubs for the beans. An EJB project
is deployed as an EJB JAR file.

EJB projects allow you to organize your enterprise beans logically. As you
develop EJB applications in the Workbench, your source and output files are
kept in the ejbModule folder of the EJB project. As you make changes and
generate deployment code, the Java classes are compiled into the ejbModule
folder. You cannot use the EJB project as the source folder; doing so will cause
errors.

84 WebSphere Studio Application Developer Version 5 Programming Guide


Application Client project
Application Client projects contain the resources needed for application client
modules. An application client module is used to contain a full-function client
Java application (non Web-based) that connects to and uses the J2EE resources
defined in your server.

When you place the client code in an application client module instead of a
simple JAR file, the application client benefits from the server's resources (it does
not need to re-specify the class path to J2EE and server JAR files), as well as
benefiting from easier JNDI lookup (the server fills in the initial context and other
parameters). The application client project allows you to work as if you are
creating a standalone Java application in a Java project.

An application client project enables you to do the following things:


򐂰 Develop the Java classes that implement the client EJB module
򐂰 Set the application client deployment descriptor
򐂰 Test the application client

When creating a new Application Client project, you can choose between these
two project types:
򐂰 J2EE 1.2 Application Client project
򐂰 J2EE 1.3 Application Client project

Application client projects allow you to organize your client applications logically.
As you develop client applications in the Workbench, your source files will be
kept in the appClientModule folder of the application client project and the binary
files will be kept in the bin folder.

Refer to “Building an application client module” on page 614 for an example.

Server project
A Server project stores information about test and deployment servers and their
configurations. To test an EJB or Web project, you have to define a server with a
server configuration to publish and run the code. Servers identify where you can
test your projects, and server configurations contain setup information.

See the section “Creating a Server project” on page 519 in Chapter 15, “Servers
and server configurations” on page 513 for a detailed instruction of how to create
a Server project and a server.

Chapter 4. Projects 85
Creating a new project
You normally start developing a new application by creating one or more projects.
The Workbench provides wizards to create each specific type of project.

As we work with a number of projects in this book, we provide more detailed


information regarding the creation of projects in the appropriate chapters. For
now we only want to demonstrate how to launch the new project wizard by
selecting File -> New -> Project from the menu bar. The New Project wizard is
shown in Figure 4-3.

Figure 4-3 New Project wizard

In this example we select the Enterprise Application Project, which is categorized


as a J2EE project. Depending on what project you choose in the New Project
dialog, Application Developer shows a tailored dialog after clicking Next.

In general (it differs, depending on what type of project is created), when you
create a new project, you have to specify the following:
򐂰 Name—Project name (we will use ItsoProGuideXxxxx).
򐂰 Location—By default projects are store in the workspace directory, but
another location may be specified.
򐂰 Organization—Directories for source and compiled files (unless this is
dictated by J2EE standards).
򐂰 Dependencies—Within an enterprise application you have dependencies
between modules, for example a Web module requires an EJB module and a
utility JAr file.

86 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Build path—Projects, folders, and JAR files that have to be in the build path.
For some project types this can only be changed after the project has been
created.

After creation of a project, the appropriate perspective opens and displays a view
of the project.

Project properties
To make changes to the definition of a project, select the project and Properties
from the context menu. Figure 4-4 shows the properties dialog for a Web project.

Figure 4-4 Project properties

In the properties dialog you may want to change:


򐂰 Java Build Path—Project dependencies and JAR files
򐂰 Server Preference—Which test server to start when testing the project
򐂰 Validation—What validation tools should run after making changes
򐂰 Web—J2EE level, context root, and tag libraries

Chapter 4. Projects 87
Using templates to create application projects
Application Developer provides an Application Template Wizard that creates
projects containing complete model applications based on application templates.

An application template is the skeleton of an application. It includes the entire


application and may be either fully configured or may have certain parts that
remain to be specified. The Application Template Wizard guides you through a
step-by-step process where you can easily specify the parameters required by
the template to generate the desired application. This enables users with minimal
or no programming skills to quickly build a fully operational application based on
simple wizard guided settings.

The Application Template Wizard currently includes a small set of pre-defined


templates. Each available template stores a description of an application along
with customized settings that enable wizard-driven specification of parameters
and automatic code generation that will produce a complete operational
application.

Running the Application Template Wizard


To generate a template-based application, select File -> New -> Other -> Web ->
Template Application. The Application Template Wizard (or Template Application
Wizard) opens as shown in Figure 4-5:
򐂰 There are three sets of templates to choose from:
– Solution Templates—provides four template applications (see
Figure 4-5)
– IT Templates—provides two template applications: List - Details, Login
– Tutorial—provides one template application: Shopping Cart
򐂰 To create an application, select a template and progress through the dialog.
򐂰 Depending on the template, you have to configure the application in a
variable number of steps, providing information for properties, data sources,
titles, and Web page content. A sample dialog for the Self Service Insurance
template is shown in Figure 4-6.
򐂰 In the Application Developer Help you can find a tutorial for the Shopping Cart
template.
򐂰 A future update to Application Developer will deliver a Template Builder that
enables users to create there own templates.

We did not use the Application Template Wizard in this document.

88 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 4-5 Template wizard: template selection

Configure each step in


the list while progressing
through the wizard.

Figure 4-6 Template wizard: example

Chapter 4. Projects 89
Summary
In this chapter we described the type of projects provided by Application
Developer for the development of J2EE applications.

We also touched briefly on the Application Template Wizard.

90 WebSphere Studio Application Developer Version 5 Programming Guide


Part 2

Part 2 Developing
applications
Part 2 describes how to develop applications. These chapters are provided:
򐂰 Developing Java applications
򐂰 Developing database applications
򐂰 Developing Web applications
򐂰 Developing Web applications with database access
򐂰 Developing applications with stored procedures
򐂰 Developing XML applications
򐂰 Developing EJBs
򐂰 Developing Web services
򐂰 Developing Struts applications
򐂰 Developing GUI applications

Note: See Appendix C, “Additional material” on page 809 for instructions on


how to download the sample code and set up the database that is used in our
examples. In addition, see “Installing DB2 UDB” on page 786 for instructions
on how to enable JDBC 2.0.

© Copyright IBM Corp. 2003. All rights reserved. 91


92 WebSphere Studio Application Developer Version 5 Programming Guide
5

Chapter 5. Developing Java


applications
This chapter provides an introduction in the Java development capabilities of the
Application Developer. The chapter is divided into four major sections:
򐂰 Creating and working with a Java project—This section demonstrates how to
create and work with a Java project. A simple Java class that reads a DB2
database table to retrieve information about customers is used.
򐂰 Preparing a utility project—This section shows how to prepare a utility project
that is available to multiple modules of an enterprise application.
򐂰 Programming assists—This section describes the main Java programming
assist features and capabilities of Application Developer.
򐂰 Javadoc—This section explains how to generate Javadoc for a project or a
set of packages.

The sample Java code used in this chapter is provided in the directory:
\sg246957\sampcode\dev-java

© Copyright IBM Corp. 2003. All rights reserved. 93


Creating and working with a Java project
Before we demonstrate Application Developer’s programming assists, we show
how to create and work with a Java project. You can use Application Developer
to develop the Java packages for your application specific business logic and for
common code that will be used by several projects. These packages can be
exported as JAR files and included in the build path for other types of projects, or
in the application path of the application servers.

Existing Java code can also be imported and integrated into new applications.

Application Developer 5 also introduces the Visual Editor for Java, which allows
you to design applications containing a graphical user interface (GUI). See
Chapter 14, “Developing GUI applications” on page 469 for a detailed description
of the Visual Editor.

Application Developer provides features to perform the following development


tasks:
򐂰 Creating a Java project
򐂰 Creating Java packages
򐂰 Running your programs
򐂰 Exporting code and running outside Application Developer
򐂰 Locating compile errors in your code
򐂰 Debugging your code

Creating a Java project


Java projects contain the resources needed for Java applications, including Java
files and class files. Java projects are used to create Java packages. When you
create a new Java project, the environment is set up for Java development.

To create a new Java project, select File -> New -> Project. This displays the New
Project dialog (Figure 5-1).

94 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-1 New Project dialog

Select Java and Java Project from this dialog and click Next to start the Java
project wizard (Figure 5-2).

Figure 5-2 New Java project: project name and directory

On the first page you name the Java project and specify the directory, where the
project files should be stored. In this example the project is named
ItsoProGuideJava. By default, the project files will be stored in a directory
created under the Application Developer workspace directory. You can change
the project directory by removing the Use default check box and specifying
another directory.

Chapter 5. Developing Java applications 95


If you click Finish, the project is configured with default options that can be
configured in the preferences (select Window -> Preferences and then select
Java -> New Project. to set up defaults for a new Java project).

We click Next to bring up the second dialog of the wizard, where we define the
Java build settings for the new project (Figure 5-3).

Figure 5-3 New Java project: source settings

On the Source tab you decide whether it is appropriate to store source code
directly in the project folder, or if you want to use separate source folders. For our
sample project, the simple model is used. If you want to use the complex model
instead, you can create the required folders by clicking Create New Folder and
adding them to the list.

Here you can also select the target folder for the generated class files. By default
the class files are placed in the same folder as the source folder, but you can edit
the Build output folder field to define a different target folder.

Note: In the Package Explorer view you cannot see the generated .class
files. If you open the Navigator view (Window -> Show View -> Navigator) you
can see source and class files.

96 WebSphere Studio Application Developer Version 5 Programming Guide


On the Projects tab you can specify any other projects in your workspace that
should be in the Java build path for the new project (Figure 5-4). You might have
some common code in a project that already exists and you want to reuse it in
the new project.

Figure 5-4 New Java project: required projects

On the Libraries tab, you can add other code libraries that have to be included in
the build path of your project (Figure 5-5). By default, the library list contains an
entry representing the Java runtime library.

You can also add:


򐂰 Workbench-managed (internal) JAR files
򐂰 File system (external) JAR files
򐂰 Folders containing class files

You can also add Java classpath variables which have been defined in the
Classpath Variable preferences page. Consult the section “Java classpath
variables” on page 33 for more information about the Classpath Variable
preferences page.

The Add Variable button allows you to add classpath variables to the build path.
Classpath variables are symbolic pointers to JAR files with the benefit of
avoiding local file system paths in a classpath.

Chapter 5. Developing Java applications 97


This is a good idea when projects are shared in a team. Variables can be created
and edited in the Classpath Variable preference page. If you want to open the
Classpath Variable preferences page, click Window -> Preferences -> Java ->
Classpath Variables.

Figure 5-5 New Java project: libraries settings

On the last tab, Order and Export, you can specify the order in which you want
items in the build path to be searched. Using the Up and Down buttons allow you
to arrange the order of the classpath entries in the list (Figure 5-6).

The checked list entries are marked as exported. Exported entries are visible to
projects that require the project. Use the Select All and Deselect All buttons to
change the checked state of all entries. The source folder itself is always
exported, and cannot be deselected.

Clicking Finish creates the new project.

98 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-6 New Java project: order and export settings

Creating Java packages


Once the Java project has been created, you can add Java packages to it. Select
the project in the Package Explorer view and New -> Package from the context
menu. In the dialog window, you enter the fully qualified name of the package.
The package where our sample Java application code resides is named
itso.java (Figure 5-7).

Figure 5-7 Create Java package dialog

Chapter 5. Developing Java applications 99


Creating Java classes
After you have created the new package, you can add classes to it. The sample
code is in a new class called CustomerListing. To create a new class, select the
package that has been created in the previous step and select New -> Class from
the context menu. In the Name field of the new Java class dialog, you have to
enter the name of the new class, CustomerListing (Figure 5-8).

You can also set the modifiers, the name of the superclass, add interfaces which
should be implemented, and create method stubs for the new class.

Figure 5-8 Create Java Class dialog

After all settings have been made, you click Finish to create the class. The Java
editor opens with the new class and its selected method stubs (Figure 5-9).

100 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-9 Java source editor with new class

Tip: Notice the Javadoc comment that is generated for a new class. You can
tailor the comment by selecting Window -> Preferences -> Java -> Templates
and editing the typecomment entry.

CustomerListing sample
Complete the CustomerListing class with the sample code from:
\SG246957\sampcode\dev-java\CustomerListing.java

We do not explain in detail the code for the CustomerListing class. The basic
functions of the sample code are:
򐂰 Connect to the DB2 database.
򐂰 Select all customers from the CUSTOMER table.
򐂰 Display the first name, the last name and the user ID of the customers.

Chapter 6, “Developing database applications” on page 139 describes database


access using JDBC. For now we just use this class to experiment with editing,
running, and debugging a Java class.

Figure 5-10 shows the complete code of the sample CustomerListing class.

Note. We also provide a companion program, CustomerListingNet, which uses


the DB2 JDBC net driver to connect to the database:
Class.forName("COM.ibm.db2.net.DB2Driver");
con = DriverManager.getConnection("jdbc:db2://localhost:6789/EJBBANK");

Chapter 5. Developing Java applications 101


package itso.java;
import java.sql.*;

public class CustomerListing {


static String dbtab = "CUSTOMER";

public static void main(String[] args) {


System.out.println("Customer Listing for " + dbtab);
Connection con = null;
con = connect();
Statement stmt = null;
ResultSet rs = null;
String select = "SELECT * FROM ITSO." + dbtab;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(select);
while (rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String userID = rs.getString("userID");
System.out.println(firstName + " " + lastName + " " + userID);
}
System.out.println("End of Listing");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}
}

protected static Connection connect() {


Connection con = null;
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
con = DriverManager.getConnection("jdbc:db2:EJBBANK");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
return con;
}
}

Figure 5-10 Sample class code CustomerListing

102 WebSphere Studio Application Developer Version 5 Programming Guide


Running your programs
After the code has been completed and is free of compile errors, it can be
executed using the Workbench Java Application Launcher. To launch the
program, you click the Run icon from the toolbar.

If you launch the program the first time, the Launch Configuration dialog opens
(Figure 5-11). Here you can select the type of configuration you would like to
create to run the program.

Select Java Application from the list and click New. A new launch configuration
with the appropriate settings for the selected class is created. You can also
specify arguments, JRE, and classpath settings for your launch configuration.
Clicking Run invokes the main method of the class.

Figure 5-11 Launch Configurations dialog

Tip: By defining launch configurations for a program you can create multiple
configurations with different arguments and settings (such as the JRE).

You can also use the drop-down arrow of the Run icon. Clicking this drop-down
arrow the first time allows you either to open the configuration launcher or select
the type of application you would like to run, directly.

You can add other launch configurations for any program. Each configuration is
displayed when clicking the drop-down arrow of the Run icon.

Chapter 5. Developing Java applications 103


Executing the CustomerListing class should result in an error. The Console view
will display the following error message:
Customer Listing for CUSTOMER
Exception: COM.ibm.db2.jdbc.app.DB2Driver
Exception: null

The exception information indicates that there was a problem locating a class
required to run the program. To correct the error you have to add the JAR file with
the DB2 JDBC driver code to the classpath.

Adding a JAR file to the classpath


We have to update the Java build path that was previously defined. Select the
ItsoProGuideJava project and Properties from the context menu. Then you
select the Java Build Path entry and the Libraries tab (Figure 5-12).

Figure 5-12 Java Build Path settings for the ItsoProGuideJava project

There are two ways you can specify access to the required classes:
򐂰 Select Add External JARs and locate the db2java.zip file in the file system.
򐂰 Select Add Variable to add a variable that refers to the db2java.zip file.

It is recommended to use the second option because you are not directly
referencing a physical path that could be different for another developer within a
team.

104 WebSphere Studio Application Developer Version 5 Programming Guide


For this sample it is assumed that a variable DB2JAVA has been defined. If DB2 is
installed on your system, Application Developer predefines this variable.

To add this variable to the Java build path for the project, select Add Variable to
display the New Variable Classpath Entry dialog (Figure 5-13).

Figure 5-13 Adding a variable to the classpath

Select the DB2JAVA variable and close the dialog with OK.

If the DB2JAVA variable is not available in the dialog, you have to create a new
variable. Click the New button to display the New Variable Entry dialog
(Figure 5-14). Enter DB2JAVA in the name field and select the file db2java.zip
from the file system by clicking the File button and confirm the dialog with OK.

DB2JAVA
c:\sqllib\java\db2java.zip

Figure 5-14 New Variable Entry dialog

The sample code can now be executed again and the list of customers in the
database table should be displayed in the Console view.

Note: The EJBBANK database must be defined for this example. See “Installing
the EJBBANK database” on page 811 for instructions.

Chapter 5. Developing Java applications 105


Exporting code and running outside Application Developer
If you would like to run this sample application outside of Application Developer
you can export the class file to the file system and run it from there:
򐂰 Select File -> Export. The Export dialog is displayed (Figure 5-15).

Figure 5-15 Export dialog

򐂰 This dialog allows you to select the destination of the export. In this example
we will do a simple export to the file system. If the code would have been in
several class files, or if there would have been other resources required to run
the program, you could have chosen to export the sample project as a JAR
file instead.
When you have made your selection—in this case select File system—click
Next to specify the resources to export (Figure 5-16).

106 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-16 Export to File System dialog

򐂰 Expand the project which is shown in the left pane and select the
CustomerListing.class file in the right pane. You can specify the directory
where you would like to export the file. In this example we use C:\ as the path
and check the Create directory structure for files check box. This option
creates the directory path ItsoProGuideJava\itso\java for the file.
򐂰 To run the application, open a command prompt window, switch to the
ItsoProGuideJava directory and enter the command:
java -cp ".;c:\sqllib\java\db2java.zip" itso.java.CustomerListing
The db2java.zip file is already added to the classpath after DB2 has been
installed. Therefore the following command should also execute the sample
application:
java itso.java.CustomerListing
򐂰 After running this program, the customer list is displayed in the command
window.

Chapter 5. Developing Java applications 107


Note: The command may be different on your system, depending on where
DB2 has been installed.

You also need to ensure that the file java.exe is accessible in the path. In the
Application Developer installation folder you will find a copy of java.exe
located in the <wsadhome>\eclipse\jre\bin directory.

Locating compile errors in your code


All compile errors in your Java code are shown in the Tasks view. An example of
such an entry in the CustomerListings.java file is displayed in Figure 5-17. The
entry in the Tasks view is marked with this symbol . Double-clicking the entry
in the task list will navigate to the line in the source editor, where the error was
detected.

The line where the error occurs is also indicated by a yellow light bulb. If you
move the mouse over the light bulb, the error message is shown.

Figure 5-17 Identifying errors in Java code

To more easily find the errors in the file you are working in, you can filter the
Tasks view to only show errors related to the current resource. To do this, click
the Filter icon in the Tasks view and select the entry On selected resource
only (or On any resource in same project) in the Filter Tasks dialog (Figure 5-18).

108 WebSphere Studio Application Developer Version 5 Programming Guide


Typical setting:
resources in
the same
project

Figure 5-18 Filter Tasks dialog

Debugging your code


How to debug Java applications in Application Developer is described in detail in
Chapter 16, “Testing and debugging” on page 553. In this section we will only
take a quick look at how to debug the simple Java application we have just
created.

Setting a breakpoint in a method causes the Debug perspective to open. A


breakpoint is a temporary marker in your code to tell the debugger to suspend
executing your program at a given point.

To set a breakpoint in the code, double-click in the grey area left of the statement
in the Java editor where you want to set the breakpoint. You can also open the
context menu and select Add Breakpoint (Figure 5-19).

Chapter 5. Developing Java applications 109


If you want to see all breakpoints that are currently set, select Window -> Show
View -> Other and select the Breakpoints view located in the Debug tree.

Figure 5-19 Setting a breakpoint

To debug the CustomerListing class, you can start the program in debug mode
by clicking the Debug icon in the toolbar .

This opens the Debug perspective and run the program until the first breakpoint
has been reached. Within the Debug perspective you can view, inspect, and
modify variables, and can trace your code (Figure 5-20).

Step through
the code

Watch the variables

Breakpoint

Figure 5-20 Debug perspective

110 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Step through the code line by line using the icon in the toolbar of the
Debug view. Other icons let you step into methods, or step to the return of a
method.
򐂰 Watch the variable values in the Variables view.
򐂰 Run the program to the end using the icon.
򐂰 Close the Debug perspective and any open editors.

Preparing a utility project


Utility projects are Java projects containing code that should be available to
multiple modules of an enterprise application.

J2EE 1.3 provides support for utility JAR files at the enterprise application level.
Such JAR files are then made available to Web and EJB modules as JAR file
dependencies.

Banking model
Later in this book, when we implement an enterprise application with a Web
module in Chapter 7, “Developing Web applications” on page 179, we will use a
banking model that we define in the Java project. Figure 5-21 shows the types
used in the banking model.

Front-end Façade Business


Model
Banking
Bank
Test

Servlet 1:m 1:m

Customer Account
m:m

1:m
JSP

TransRecord

Figure 5-21 Banking model

Chapter 5. Developing Java applications 111


Customer A customer of the bank.
Account A bank account. A customer may have multiple bank accounts
and an account may be owned by multiple customers.
TransRecord A transaction record that is generated for each banking
transaction, such as a deposit, withdrawal, or transfer of money
between two accounts. A bank account may have many
transaction records.
Bank The mediator. Mediators act as coordinators, encapsulating the
other objects and how they interact. The bank class holds the
customer, account, and transaction record objects, and
methods to work with them.
In Chapter 12, “Developing EJB applications” on page 373 we
replace the Bank class with a EJB session bean that provides
the same functions. The session bean interacts with entity
beans that map to relational tables.
BankingTest The facade. The intent of facades is to provide a simple and
unified interface to the otherwise complex model that lies
behind it. By doing so, we reduce the dependencies between
the model classes and its clients. Less dependencies mean
more freedom to adapt to new requirements.
The BankingTest facade is for testing purposes only. We will
implement the real facade in the front-end modules, for
example, in Web applications.

Note: Both mediator and facade are documented design patterns. Refer to
Design Patterns: Elements of Reusable Object-Oriented Software.

Design considerations
This design with separation of front-end and backend enables us to implement
multiple front-ends and multiple business models that work with each other.
򐂰 In Chapter 7, “Developing Web applications” on page 179, we implement a
front-end Web application using basic servlets and JSPs.
򐂰 In Chapter 10, “Developing Struts applications” on page 293, we implement a
front-end Web application using the Struts framework.
򐂰 In Chapter 12, “Developing EJB applications” on page 373, we implement the
business model as enterprise beans (EJBs). With a small change to the
facade bean we can then run both Web applications against the EJB business
model.

112 WebSphere Studio Application Developer Version 5 Programming Guide


Implementation
We use an implementation in regular JavaBeans with data in memory for the
model. Additional services like persistence, distribution, security, or transaction
management were not considered. We wanted to keep the model layer as simple
as possible, not to add to the complexity natural to this kind of application.

However, we can redesign the model with the use of an underlying database at
any time.

Packages and classes


The model is implemented in these packages and classes:
itso.bank.model Model classes: Bank, Customer, Account, TransRecord
Customer: id, title, firstname, lastname
Account: id, balance, type
TransRecord: timeStamp, transType, transAmt
itso.bank.facade The facade for banking operations is the BankingTest
class. This is the initial implementation of the facade.
itso.bank.exception Application exceptions: AccountDoesNotExistException,
CustomerDoesNotExistException, ZeroAmountException,
InvalidAmountException, BankException,
InsufficientFundsException
itso.bank.util Converter of amounts between numeric and character
representations: AmountConverter
itso.bank.main Test program: BankMain

The Bank class initializes the data in memory. Instances of customers and
accounts are kept as java.util.Map. The customer-account relationship is held
as a java.util.Vector for each customer within a java.util.Map. The
transaction records of an account are held as a java.util.TreeSet for each
Account within a java.util.Map.

All amounts are kept as java.math.BigDecimal, which provide accurate


calculations of amounts.

Business logic
All classes provide getter and setter methods for the attributes. To work with the
model the following business logic methods are provided:
򐂰 The Customer class provides no special methods.
򐂰 The Account class provides deposit and withdraw methods to perform
banking transactions.

Chapter 5. Developing Java applications 113


򐂰 The TransRecord class provides no special methods.
򐂰 The Bank class provides:
– Customer getCustomer(customerID)—retrieve customer information
– Account getAccount(accountID)—retrieve account information
– Account[] get Accounts(customerID)—retrieve the accounts of one
customer as an array
– TransRecord[] getTransactions(accountID)—retrieve the transactions
records of one account as an array
– BigDecimal deposit(accountID, amount)
– BigDecimal withdraw(accountID, amount)
– BigDecimal ransfer(accountID1, accountID2, amount)
򐂰 The BankingTest facade class provides the same methods as the Bank class
and forwards the execution to the Bank class.

Importing the implementation


The banking model is provided in a JAR file that you can import into the
ItsoProGuideJava project, which becomes our utility project:
򐂰 Select the ItsoProGuideJava project and Import (context).
򐂰 Select ZIP file and click Next.
򐂰 Click Browse and locate the file:
\sg246957\sampcode\dev-java\BankingModel.jar
򐂰 Select Overwrite existing resources without warning.
򐂰 Click Finish.

After importing the code you find the five packages in the ItsoProGuideJava
project.

We will use the ItsoProGuideJava project as a utility project in Chapter 7,


“Developing Web applications” on page 179.

Testing the model


To test the model, select the ItsoProGuideJava project and Run -> Run As ->
Java Application. When prompted, select the BankMain class and click OK.

Alternatively, you can run the BankMain program using the instruction in “Running
your programs” on page 103.

The program executes a few of the business methods and displays the output in
the Console view.

114 WebSphere Studio Application Developer Version 5 Programming Guide


Programming assists
Application Developer contains a number of Java programming assist features.
These features are designed to make life easier for both experienced and novice
Java programmers by simplifying or automating many common tasks.

The following topics are covered:


򐂰 Pluggable JDK
򐂰 Java Scrapbook
򐂰 Code assist
򐂰 Navigating through your code
򐂰 Import generation
򐂰 Tasks view
򐂰 Refactoring
򐂰 Code generation actions
򐂰 Smart compilation
򐂰 Java search and working sets
򐂰 Bookmarks

Pluggable JDK
To provide support for different JDK levels and run-time environments, new JREs
can be added to the Workbench. For each project you can then select which
particular JRE you would like to use. By default the current version of Application
Developer supports the IBM JDK 1.3.1. The corresponding JRE will be used for
all projects unless it has been specified differently.

See “Installed JREs” on page 39 of Chapter 2, “Setting up your Workbench and


workspace preferences” on page 21 for more information regarding the JRE
environment of Application Developer and how to add a new JRE.

Java Scrapbook
Snippets of Java code can be entered in a Scrapbook window and evaluated by
simply selecting the code and running it. This feature can be used to quickly test
code without having to modify any actual Java source file.

These scrapbook pages can be added to any project. The extension of a


scrapbook page is jpage, to distinguish them from normal Java source files.

Tip: Content assist (such as code assist) is also available on scrapbook


pages.

Chapter 5. Developing Java applications 115


To create a scrapbook page, select a folder (itso.java) and New -> Scrapbook
Page (context). Make sure the correct folder is selected and enter a file name
(JavaTest) for the new page (Figure 5-22).

Figure 5-22 Create Java Scrapbook Page dialog

Click Finish to create the scrapbook page. After the page has been created and
opened in the source editor, you can start entering code snippets in it.

To test a scrapbook page, we use code similar to the BankingTest class from the
banking model (Figure 5-23). The code is available in:
sg246957\sampcode\dev-java\JavaTest.jpage

Tip: All class names in a scrapbook page must be fully qualified or you have to
set import statements:
򐂰 Select Set Imports from the context menu anywhere in the scrapbook.
򐂰 For our example, select the itso.bank.model, itso.bank.util, and
java.util packages.

After you have added the code, you can run one of the snippets by selecting the
code and Run Snippet (context) or click the Run the Selected Code icon in
the toolbar. The result are displayed in the Console view.

116 WebSphere Studio Application Developer Version 5 Programming Guide


// ------------------------------------- snippet 1
Bank bank = Bank.getInstance();
for (int i=101; i<107; i++) {
String id = String.valueOf(i);
Customer customer = bank.getCustomer(id);
System.out.println("Customer: " + id + " " + customer.getLastName());
Account[] accounts = bank.getAccounts(id);
for (int j=0; j<accounts.length; j++) {
Account account = accounts[j];
System.out.println(" - Account: " + account.getId() + " "
+ AmountConverter.fromDecimal(account.getBalance()));
}
}

// ------------------------------------- snippet 2
Bank bank2 = Bank.getInstance();
itso.bank.facade.BankingTest banking = new itso.bank.facade.BankingTest();
String acct1 = "101-1001";
String acct2 = "101-1002";
System.out.println("Transfer 33 from " + acct1 + " to " + acct2);
banking.transfer(acct1, acct2, new java.math.BigDecimal("33"));
System.out.println("Account: " + acct1 + " "
+ AmountConverter.fromDecimal(banking.getAccount(acct1).getBalance()));
TransRecord[] tx = banking.getTransactions(acct1);
for (int j=0; j<tx.length; j++) {
TransRecord tr = tx[j];
System.out.println(" - Tx: " + tr.getTimeStamp() + " " +
tr.getTransType() + " "+
AmountConverter.fromDecimal(tr.getTransAmt()));
}

Figure 5-23 Scrapbook code sample

Note: You cannot run code in a scrapbook page until you have at least one
statement selected.

You can also select Display from (context) to display the result expression or
Inspect to bring up the Expressions view, which allows you to inspect the result
like a variable in the debugger (see Chapter 16, “Testing and debugging” on
page 553 for more information about debugging and inspecting).

Change one of the account numbers for the transfer in snippet 2 to an invalid
account and run the code again. The debugger opens when the exception is
thrown.

Chapter 5. Developing Java applications 117


Code assist
When writing Java code, you can use the code assist feature of the Application
Developer to display classes, methods, fields and variables that are valid to use
in the current context. In the example in Figure 5-24, you want to use the method
from the SQL Connection class to create a new SQL statement, but you cannot
remember the exact name and parameters. To see all valid methods, position the
cursor at the point where you want to insert the method call and press
Ctrl-Space.

A window is displayed and lists all methods and fields available for this object. In
addition, an infopop window is displayed, which shows the Javadoc associated
with the selected item. To insert a call to the method createStatement, simply
double-click the method’s name or press Enter on your keyboard.

Figure 5-24 Code assist feature

The Java editor also supports syntax highlighting and hover help for the Java
code, which displays the Javadoc associated with the selected code.

Application Developer also provides templates, which helps the user to add
occurring source code patterns. For more information regarding templates see
“Templates” on page 43.

118 WebSphere Studio Application Developer Version 5 Programming Guide


Navigating through your code
By default, the Java perspective contains an Outline view on the right hand side
of the Java source editor (Figure 5-25). The Outline view displays an outline of a
structured file that is currently open in the editor area, and lists structural
elements. The contents of the Outline view are editor-specific. For a Java source
file (our example), the structural elements are classes, fields, and methods.

By selecting elements in the Outline view, you can navigate to the corresponding
point in your code. This allows you to easily find methods and field definitions
without scrolling the editor window.

Figure 5-25 Using the Outline view for navigation

Tip: If you have a source file with many fields and methods, you can use the
Show Source of Selected Element Only icon from the toolbar to limit the
edit view to the element that is currently selected in the Outline view.

The Package Explorer view, which is available by default in the Java perspective,
can also be used for navigation (Figure 5-26).

The Package Explorer view provides you with a Java-specific view of the
resources shown in the Navigator. The element hierarchy is derived from the
project's build paths.

Chapter 5. Developing Java applications 119


Figure 5-26 Package Explorer view

Import generation
The Application Developer Java Editor simplifies the task of finding the correct
import statements to use in your Java code.

Simply select the type name in the code and select Add Import from the context
menu. If the type name is unambiguous, the import will be pasted at the correct
place in the code. If the type exists in more than one package, a window with all
the types is displayed and you can choose the correct type for the import
statement.

Figure 5-27 shows an example where the selected type (Statement) exists in
several packages. Once you have determined that the java.sql package is what
you want, double-click the entry in the list and the import statement is generated
in the code.

120 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-27 Import generation

You can also add the required import statements for the whole compilation unit.
Open the context menu somewhere in the Java source editor and select Source
-> Organize Imports. The code in the compilation unit is analyzed and the
appropriate import statements are added.

You can control the order in which the imports are added and when package level
imports should be used through the Preferences dialog. See “Organize imports”
on page 42 for details about this feature.

Tasks view
The Tasks view displays the following information:
򐂰 System generated tasks errors
򐂰 User-defined tasks that you add manually

System generated tasks are typically created by the various builders. System
generated tasks can be errors, warnings, or information associated with a
resource. For example, if you save a Java source file that contains syntax errors,
the errors will automatically be logged in this view.

Chapter 5. Developing Java applications 121


User-defined tasks are global and not related to a particular resource or folder.
Tasks in this context are similar to an item in a to-do list. Any user task can be
inserted into the Tasks view and tracked for completion.

Figure 5-28 shows an example of the Tasks view with one user-defined task and
five system generated tasks (a broken link warning in an HTML file and four
compile errors in a Java file).

Figure 5-28 Tasks view

Also, the Tasks view can be filtered to show only specific types of tasks. For
example, you may want to see only error or tasks related to a specific resource.
For more information on this issue, refer to “Locating compile errors in your code”
on page 108.

A typical filter in a Java project would be to display the tasks that apply to any
resource in same project (see Figure 5-18 on page 109).

Refactoring
When developing Java applications, it is often necessary to perform tasks such
as renaming classes, moving classes between packages, and breaking out code
into separate methods. The term refactoring is sometimes used to describe
these types of changes. In traditional programming environments such tasks are
both time consuming and error prone, because it is up to the programmer to find
and update each and every reference throughout the project code. Application
Developer provides functions to automate this process.

The Java development tools (JDT) of Application Developer provides assistance


for managing refactoring. In the Refactoring wizard you can select:
򐂰 Refactoring with preview—Click Next in the dialog to bring up a second
dialog panel where you are notified of potential problems and are given a
detailed preview of what the refactoring action will do.
򐂰 Refactoring without preview—Click Finish in the dialog and have the
refactoring performed. If a stop problem is detected, refactoring is halted and
a list of problems is displayed.

122 WebSphere Studio Application Developer Version 5 Programming Guide


Table 5-1 shows the refactoring actions available in Application Developer.

Table 5-1 Refactoring actions


Name Function

Rename Starts the Rename refactoring wizard. Renames the selected


element and (if enabled) corrects all references to the elements
(also in other files). Is available on methods, fields, local variables,
method parameters, types, compilation units, packages, source
folders, projects and on a text selection resolving to one of these
element types.

Move Starts the Move refactoring wizard. Moves the selected elements
and (if enabled) corrects all references to the elements (also in
other files). Can be applied on one or more static methods, static
fields, types, compilation units, packages, source folders and
projects and on a text selection resolving to one of these element
types.

Pull Up Starts the Pull Up refactoring wizard. Moves a field or method to its
super class. Can be applied on one or more methods and fields
from the same type or on a text selection resolving to a field or
method.

Modify Starts the Modify Parameters refactoring wizard. Changes


Parameters parameter names and parameter order and updates all references
to the corresponding method. Can be applied on methods with
parameters or on text selection resolving to a method with
parameters.

Extract Method Starts the Extract Method refactoring wizard. Creates a new
method containing the statements or expressions currently
selected and replaces the selection with a reference to the new
method.

Extract Variable Starts the Extract Variable refactoring wizard. Creates a new
variable assigned to the expression currently selected and replaces
the selection with a reference to the new variable.

Inline Local Starts the Inline Local Variable refactoring wizard. Replaces the
Variable references to the selected local variable with the variable's initializer
expression and removes the variable.

Self Encapsulate Starts the Self Encapsulate Field refactoring wizard. Replaces all
Field references to a field with getter and setter methods. Is applicable to
a selected field or a text selection resolving to a field.

Undo Does an Undo of the last refactoring.

Redo Does a Redo of the last undone refactoring.

Chapter 5. Developing Java applications 123


Refactoring preferences
In the Refactoring preferences page, located in Window -> Preferences -> Java
-> Refactoring, you can select the default level for problems to be displayed when
you are carrying out a refactoring without a preview (Figure 5-29).

Figure 5-29 Refactoring preferences

The set of radio buttons is used to indicate what type of error reporting you want
to see in the refactoring dialog. These options are listed in order of severity. By
default Application Developer will display any error that would occur if the
refactoring is performed.

If you check the option Save all modified resources automatically prior to
refactoring, any outstanding changes will be saved without displaying a prompt.

Refactoring example
The following example of a refactoring operation assumes that you want to
rename a class in your Java program. To initiate the renaming, simply select the
class and select Refactor -> Rename in the context menu. The Refactoring
wizard is displayed, where you rename the class and select the appropriate
refactoring settings (Figure 5-30).

124 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-30 Refactoring wizard

Enter the new name for the class and click Next. If there are any files with
unsaved changes in the Workbench and you have not indicated in the
preferences that the save should be done automatically, you are prompted to
save these files before continuing the refactoring operation.

If problems more severe than the default level set in the refactoring preferences
are anticipated, then the problems page is displayed (Figure 5-31). If the
problems are severe, the Next and Finish buttons are disabled and the
refactoring must be aborted until the problems have been corrected. If the
buttons are enabled, you can select whether to accept the problems and
continue, or to cancel the refactoring operation.

Figure 5-31 Refactoring problems

Selecting Next at this point displays a window showing what actions will be
performed during the refactoring (Figure 5-32).

Chapter 5. Developing Java applications 125


Figure 5-32 Refactoring preview

After reviewing the changes that will be applied, you can again select whether to
Finish or to Cancel the refactoring operation. Clicking Finish will perform the
renaming operation of the class. If there are any problems detected, they will be
displayed after the operation has been completed. The type of problem shown
depends on the settings in the Refactoring preferences dialog (Figure 5-29 on
page 124).

Application Developer provides one level of an undo operation for refactoring


commands. If you want to undo the renaming changes at this point, select
Refactor -> Undo from the menu bar.

Code generation actions


Application Developer’s Java editor allows you to generate default Java code. It
can generate getters and setters, override methods, or add constructors from the
superclass.

126 WebSphere Studio Application Developer Version 5 Programming Guide


Generate getters and setters
When working with the Java editor you can generate accessors (getters and
setters) for the fields of a type inside a compilation unit. There are several ways
to generate getters and setters for a field:
򐂰 Select Source -> Generate Getter and Setter from the context menu in the
Java editor.
򐂰 Select Source -> Generate Getter and Setter from the context menu of the
field in the Outline view.
򐂰 Select Source -> Generate Getter and Setter from the menu bar.

A dialog opens to let you select which methods you want to create. Select the
methods and click OK (Figure 5-33).

Figure 5-33 Generate Getter and Setter dialog

Override methods
The override methods feature helps you to override methods from the
superclass. Select Source -> Override Methods from the menu or Override
Methods in the context menu of a selected type or on a text selection in a type.

The Override Methods dialog (Figure 5-34) displays all methods that can be
overridden from superclasses or implemented from interfaces. Abstract methods
or not yet implemented methods are selected by default.

When clicking OK, method stubs for all selected methods are created.

Chapter 5. Developing Java applications 127


Figure 5-34 Override methods dialog

Add constructors from superclass


This feature allows you to automatically add constructors as defined in the
superclass for the currently selected type. Open the context menu in the Java
editor and select Source -> Add Constructors from Superclass.

Smart compilation
The Java Builder in the Workbench incrementally compiles the Java code as it is
changed, unless you disable the automatic build feature. For more information
consult the section “Automatic builds” on page 27.

Java search and working sets


In addition to the normal text search functionality, Application Developer provides
a special Java element search feature. Using the Java Search dialog, you can
search for types, methods, packages, constructors and fields within the
workspace. The search results can be limited to show only declarations,
references, implementors or read or write access if you are searching for a
specific field.

You can also specify the scope of the search. You can either search the
workspace, choose only the selected resources or create a working set, which
can be used for future searches as well.

128 WebSphere Studio Application Developer Version 5 Programming Guide


Working sets are used, because users often find it necessary to filter views such
as the navigator view in order to reduce clutter. Working sets can be used to filter
resources by only including specified resources. They are selected and defined
using the view's filter selection dialog.

Simply click the Search icon to open the search dialog. Figure 5-35
demonstrates how to search for the field dbtab within a working set.

Figure 5-35 Java search dialog

Type in the search string, specify that you would like to search for a field, and
select Working Set as the scope of this search.

Click Choose to display a new dialog, where you can select an existing working
set or create a new one (Figure 5-36).
򐂰 Click New to create a new working set. Select a Resource working set or a
Java working set and click Next.
򐂰 The last page of the wizard is displayed. You have to name your new working
set and specify the working set content.
򐂰 Click Finish to create the working set.

Chapter 5. Developing Java applications 129


Select the
projects or
folders of the
working set

Figure 5-36 Creating a working set

By confirming this dialog with OK, the new set will be used in our Java search.

Figure 5-37 shows the Java search dialog with the new working set. Click Search
to start the search operation.

130 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-37 Java search dialog with Working Set

The search results are displayed in the Search view (Figure 5-38).
Double-clicking the result entry in the Search view opens the source file where
the field has been found and the first match is highlighted. The yellow arrows on
the left hand side indicate the lines where a match has been found.

Figure 5-38 Java search results

Chapter 5. Developing Java applications 131


Bookmarks
Bookmarks are a simple way to navigate to resources that you frequently use.
The Bookmarks view displays all bookmarks in the Workbench. To show the
Bookmarks view choose Window -> Show View -> Other and select Bookmarks
from the Basic section.

To set a bookmark in your code, right-click in the gray sidebar left of your code in
the Java editor and select Add Bookmark (Figure 5-39).

Figure 5-39 Adding a bookmark

A dialog is displayed where you have to enter a name for the new bookmark
(Figure 5-40).

Figure 5-40 Naming a bookmark

132 WebSphere Studio Application Developer Version 5 Programming Guide


The newly created bookmark is indicated by a symbol in the marker bar and also
appears in the Bookmarks view. Double-clicking the bookmark entry in the
Bookmarks view opens the file and navigates to the line where the bookmark has
been created.

Tip: You can bookmark individual files in the Workbench to open them quickly
from the Bookmark’s view later. In the Navigator view, right-click the file that
you want to add to you list of bookmarks and select Add Bookmark from the
file’s pop-up menu.

You can remove a bookmark by using the bookmark’s context menu in the
Bookmarks view and select Delete.

Note: Bookmarks are not specific to Java code. They can be used in any file
to provide a quick way of navigating to a specific location.

Javadoc
Javadoc is a tool in the Java JDK to generate documentation about Java
packages, classes, and methods. The Javadoc documentation is based on
comments entered for each class and method, and the packaging of classes into
packages.

Preferences
The location of the javadoc.exe must be specified in the Javadoc preferences.
Refer to “Javadoc documentation” on page 40 for instructions.

Generating Javadoc
Application Developer provides a wizard to generate Javadoc for selected
packages or projects.

In this section we generate Javadoc for the ItsoProGuideJava project:


򐂰 Select the ItsoProGuideJava project and Export (context).
򐂰 Select Javadoc and click Next.
򐂰 Select the projects (or expand and select packages), member visibility, and
the output location. The default location is in the workspace (Figure 5-41).
Click Next.

Chapter 5. Developing Java applications 133


Figure 5-41 Javadoc generation options (1)

򐂰 On the next page you can specify detailed options about the doclet
generation, including a title (Figure 5-42). Click Next.

Figure 5-42 Javadoc generation options (2)

134 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 On the final page, select the options for generating an Ant script and opening
a browser (Figure 5-43). Click Finish.

Figure 5-43 Javadoc generation options (3)

򐂰 Watch the generation of Javadoc in the Console view:


Loading source files for package itso.bank.facade...
......
Constructing Javadoc information...
Building tree for all the packages and classes...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\itso\bank\facade\class-use
\BankingTest.html...
......
Building index for all the packages and classes...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\overview-tree.html...
......
Building index for all classes...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\allclasses-frame.html...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\index.html...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\packages.html...
......
򐂰 A browser opens with the generated Javadoc and you can explore the
documentation of the packages and classes (Figure 5-44).

Chapter 5. Developing Java applications 135


Figure 5-44 Generated Javadoc in a browser

Note that our source classes do not have many comments for good Javadoc!
򐂰 To see the generated files in the Workbench, select the ItsoProGuideJava
project and Refresh (context).
򐂰 In general you would not generate Javadoc into the Workbench but rather into
a documentation location. Either move the data to another location or delete
the doc folder from the project.

Using Ant to generate Javadoc


The javadoc wizard generated an Ant build script (javadoc.xml) in the
ItsoProGuideJava project. This build script that can be used to regenerate the
documentation (Figure 5-45).

136 WebSphere Studio Application Developer Version 5 Programming Guide


<?xml version="1.0" encoding="UTF-8"?>
<project default="javadoc" name="ItsoProGuideJava">
<target name="javadoc">
<javadoc access="public" author="true"
classpath="E:\WSAD5sg246957\ItsoProGuideJava;
D:\SQLLIB\java\db2java.zip"
destdir="E:\WSAD5sg246957\ItsoProGuideJava\doc"
doctitle="ItsoProGuide Javadoc" nodeprecated="false"
nodeprecatedlist="false" noindex="false" nonavbar="false"
notree="false"
packagenames="itso.bank.facade,itso.bank.exception,
itso.bank.main,itso.bank.model,itso.bank.util,itso.java"
sourcepath="E:\WSAD5sg246957\ItsoProGuideJava"
splitindex="true" use="true" version="true"/>
</target>
</project>

Figure 5-45 Javadoc Ant build script

To regenerate the Javadoc, select the javadoc.xml file and Run Ant (context) and
click Finish in the pop-up dialog.

See Chapter 19, “Building applications with Ant” on page 633 for detailed
information about Ant.

Summary
In this chapter we described how to create a new Java project and how to work
with the programming assists of Application Developer by creating a simple Java
class.

While you are working with larger projects you will experience the benefits of the
programming assists and the Java development tools.

We also demonstrated how to prepare and implement a utility project and how to
generate Javadoc.

Chapter 5. Developing Java applications 137


138 WebSphere Studio Application Developer Version 5 Programming Guide
6

Chapter 6. Developing database


applications
In this chapter we explain how to connect to a database from a Java application.
Concepts such as JDBC and data sources are covered.

We then go into detail about the wizards included in Application Developer to


work with databases. This includes tools to build your own databases and SQL
statements, as well as the wizards to access a database from Java applications.

This chapter covers the following topics:


򐂰 JDBC overview
򐂰 Data source versus direct connection
򐂰 Application Developer database operations
򐂰 XMI and DDL
򐂰 Data perspective
򐂰 Using the DB Servers view
򐂰 Creating database objects
򐂰 Using the SQL Statement Wizard
򐂰 Using SQL Query Builder
򐂰 Accessing databases from a Java application

© Copyright IBM Corp. 2003. All rights reserved. 139


JDBC overview
Java Database Connectivity (JDBC), like Open Database Connectivity (ODBC),
is based on the X/Open SQL call-level interface specifications, but unlike ODBC,
JDBC does not rely on various C features that do not fit well with the Java
language. Using JDBC, you can make dynamic calls to databases from your Java
applications or Java applets.

JCBC is vendor neutral and provides access to a wide range of relational


databases, as well as to other tabular sources of data. It can even be used to get
data from flat files or spreadsheets. This portability and versatility are the main
attractions of using JDBC for database access in application programs. JDBC is
especially suited for use in Web applications. Using the JDBC API you can
connect to databases using standard network connections. Any modern Web
browser is Java enabled, so you do not have to worry about whether the client
can handle the application or not.

Figure 6-1 shows the basic components of JDBC access. The JDBC API sends
the SQL commands from the application through a connection to the vendor
specific driver that provides access to the database. Connections can be
established through a driver manager (JDBC 1.0) or a data source (JDBC 2.0).

Java Application

getConnection getConnection

JDBC Driver Connection Data Source


Manager

Vendor supplied
JDBC Driver

Database

Figure 6-1 JDBC overview

140 WebSphere Studio Application Developer Version 5 Programming Guide


Data source versus direct connection
In JDBC 1.0 the only way of establishing a database connection was by using the
DriverManager interface. This was expensive in terms of performance because a
connection was created each time you had to access the database from your
program, thereby incurring a substantial processing overhead. In the JDBC 2.0
Standard Extension API an alternative way of handling database connections
was introduced.

By using data source objects you have access to a pool of connections to a data
source. Using connection pooling gives you the following advantages:
򐂰 It improves performance. Creating connections is expensive; a data source
object creates a pool of connections as soon as it is instantiated.
򐂰 It simplifies resource allocation. Resources are only allocated from the data
source objects, and not at arbitrary places in the code.

Data source objects work as follows:


򐂰 When a servlet or other client wants to use a connection, it looks up a data
source object by name from a Java Naming and Directory Interface (JNDI)
server.
򐂰 The servlet or client asks the data source object for a connection.
򐂰 If the data source object has no more connections, it may ask the database
manager for more connections (as long as it has not exceeded the maximum
number of connections).
򐂰 When the client has finished with the connection, it releases it.
򐂰 The data source object then returns the connection to the available pool.

Important: Because of the advantages of connection pooling, using data


source objects is the preferred method of handling database connections in
Web applications. The WebSphere Application Server has full support for
connection pooling and for registering data sources through JNDI.

If you use the Create database Web pages wizard, described in detail in
“Accessing databases from a Web application” on page 248, you have the option
of generating code to use either a driver manager connection or a data source
connection.

Chapter 6. Developing database applications 141


Application Developer database operations
Application Developer provides a number of features that make it easier to work
with relational databases in your projects.
򐂰 Ability to import and use existing database models.
򐂰 Ability to create your own database objects and generate DDL for the target
database.
򐂰 Ability to generate XML schemas from database models.
򐂰 Ability to interactively build and execute SQL queries from an imported
database model or through an active connection, using SQL Wizard and SQL
Query Builder.
򐂰 Ability to generate Web pages and supporting Java classes based on existing
or new SQL queries.
򐂰 Ability to access database API from JavaServer Pages, using either
JavaBeans or JSP tags.

These features will be discussed in more detail later in this chapter.

XMI and DDL


XML Metadata Interchange (XMI) is an Object Management Group (OMG)
standard format for exchanging metadata information. Application Developer
uses the XMI format to store all local descriptors of databases, tables, and
schemas. The content of the XMI files can be viewed and edited using tailored
editors. When you import an existing database model, it can be stored in XMI
format.

Data definition language (DDL) is a format used by relational database systems


to store information about how to create of database objects. Application
Developer allows you to generate DDL from an XMI file and vice versa.

Data perspective
The Data perspective is used to work with databases, tables, and SQL
statements. See “Data perspective” on page 68 for an introduction.

There are three main views in the Data Perspective:


򐂰 DB Servers view
򐂰 Data Definition view
򐂰 Navigator view

142 WebSphere Studio Application Developer Version 5 Programming Guide


DB Servers view
The DB Servers view shows active connections to databases and allows you to
create new connections. In Figure 6-2 you can see an active connection to the
EJBBank DB2 database. We will create this connection in “Creating a database
connection” on page 145.

Figure 6-2 DB Servers view

The DB Servers view is independent of any projects. It displays active


connections to databases. When you stop Application Developer, the
connections become inactive and no databases and tables are displayed.

An inactive connection can be activated by selecting the connection and


Reconnect from the context menu.

Data Definition view


The Data Definition view (Figure 6-3) shows the database models that currently
exist in Application Developer. These are either imported through the DB Servers
view or created within the Workbench. In this example we imported the data
model from the DB Servers view.

Chapter 6. Developing database applications 143


Database models are stored within an Application Developer project. This can be
any type of project; for example, a simple project, a Web project with database
access, or an EJB project with entity beans.

The Data Definition view is a hierarchical view of the database objects and does
not display how these definitions are stored in actual files.

Figure 6-3 Data Definition view

Navigator view
In the Navigator view (Figure 6-4) you can see the local descriptor files (.xmi
files) that represent the database objects. Each of the files has an editor
associated with it. Double-clicking the file brings up the appropriate editor for the
type of object that is described, which could be either a database, a schema, or a
table.

144 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-4 Navigator view

Using the DB Servers view


You can use the DB Servers view to connect to existing databases and view their
objects. The objects can be imported into Application Developer and used in your
applications.

The DB Servers view allows you to filter the designs that are returned to only
show a subset of schemas or tables. You can also use the DB Servers view to
generate DDL files and XML schemas.

Important: The DB Servers view is read-only. Before you can edit any
database objects, you have to import them into an Application Developer
project.

Creating a database connection

Note: The examples in this section assume that you have created and
populated the DB2 tables as described in “Installing the EJBBANK database”
on page 811.

To view the definition of an existing database, you first have to create a JDBC
connection to the database. To create a new connection, first make sure you are
in the DB Servers view. Then right-click anywhere in the view and select New
Connection to display the Database Connection wizard (Figure 6-5).

Chapter 6. Developing database applications 145


Figure 6-5 Creating a JDBC connection

You have to provide a unique name for the connection (Con1 in our example), a
user ID and password if required, and the type of database you are connecting
to. Also, you must specify which JDBC driver should be used. There are two
predefined JDBC drivers for DB2:
򐂰 IBM DB2 APP DRIVER (COM.ibm.db2.jdbc.app.DB2Driver) for connections
to local databases or remote databases defined locally with the DB2 Client
Configuration Assistant.
򐂰 IBM DB2 NET DRIVER (COM.ibm.db2.jdbc.net.DB2Driver) for connections
to remote DB2 databases.

See “DB2 JDBC drivers” on page 175 for more details on DB2 JDBC drivers.

146 WebSphere Studio Application Developer Version 5 Programming Guide


If you do not want to use one of the predefined drivers, you can select Other
Driver from the JDBC driver drop-down, and fill in the JDBC driver class field with
the driver name.

Note: Application Developer now contains support for additional database


systems, such as Cloudscape™, Oracle, Microsoft® SQL Server, Informix,
Sybase, InstantDB, and MySQL.

If you want to limit the schemas, tables, stored procedures or user-defined


functions returned, click the Filters button (Figure 6-5 on page 146), and the
Connection Filters dialog, shown in Figure 6-6, is displayed.

Figure 6-6 Creating a JDBC connection: filter

The dialog has four pages to define filters for schemas, tables, stored
procedures, and user-defined functions. By default, one schema filter is
predefined (SCHEMA NOT LIKE SYS%) by the selection Exclude system schemas.

For our example we are limiting the selection to tables with names starting with
CU. To create the filter, select the Table tab and click Add Filter, and the Add
Filter dialog shown in Figure 6-7 opens.

Chapter 6. Developing database applications 147


Figure 6-7 Adding a new filter

Enter CU% in the entry field and click OK. You can modify the filter by clicking any
cell in the table and changing the value. Click OK to close the filter dialog.

After clicking Finish in the connection window, the connection is created and a
new database entry is added to the DB Servers view. You can expand the new
node to see the schemas and tables that are now available for use (Figure 6-8).

Figure 6-8 DB Servers view of EJBBANK database with table filter applied

Next we create another connection without filters. We will use this connection in
the next section to import database objects into our workspace.

Right-click inside the DB Servers view, and select New Connection from the
context menu. The new connection wizard opens, already containing the default
values for connection name (Con2) and database name (EJBBANK). By default, no
filters are entered. All you have to do is click Finish to create this connection.

Figure 6-9 shows the DB Servers view, which now contains the new connection
Con2. This new connection has no table filters, so it shows all the tables in the
EJBBANK database.

148 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-9 Updated DB Servers view with two connections

Importing database objects


In the DB Servers view you can browse the tables and columns, but before you
can actually use them in your application, you have to import them into a folder in
a project.

Simple project
We use a simple project to store the database definitions. A simple project is a
generic project that contains files and folders. To create the project select File ->
New -> Project. Then select Simple and Project from the New Project dialog and
click Next. Enter ItsoProGuideDatabase as the project name, and click Finish.

The Resource perspective opens. However, we will continue to work in the Data
perspective, so we close the Resource perspective.

Import database
We now import the EJBBANK database into the new project:
򐂰 In the Data perspective, DB Servers view, select the connection Con2 Import
to Folder (context).
򐂰 In the Import dialog (Figure 6-10) click Browse to locate the
ItsoProGuideDatabase project, then click Finish.

Chapter 6. Developing database applications 149


Figure 6-10 Import database objects

In the Data Definition view (Figure 6-11) expand the EJBBANK node. The same
database objects are shown, but you can now open editors on them to view and
modify their definitions.

In the Navigator view you will notice that a number of XMI files have been created
for the database objects. (XMI is an open information interchange model that
allows developers who work with object technology to exchange programming
data over the Internet in a standardized way.)

Figure 6-11 Imported database objects in Data Definition and Navigator views

If you double-click one of these files, the appropriate object editor opens. If you
want to see the XMI source, you can right-click any of the files and select Open
With -> Text Editor.

150 WebSphere Studio Application Developer Version 5 Programming Guide


Generate DDL and XML schema files
Application Developer allows you to generate DDL files and XML Schemas for
database objects. To generate a DDL file, select the database object in the Data
Definition or DB Servers view and Generate DDL (context) to open the Generate
SQL DDL wizard, shown in Figure 6-12. You can generate DDL for the database,
for a schema, or for individual tables.

Figure 6-12 Generate DDL for a database object

Enter the name of the folder where you want the generated .sql file to be stored,
select options for the generation and whether you want to open the SQL editor on
the generated file. If you elect not to open the editor, you will have to switch to the
Navigator view to see the generated file. The generated DDL file is shown in
Example 6-1.

Example 6-1 Generated EJBBANK.sql file (extract)


-- Generated by Relational Schema Center on Mon Mar 17 01:07:11 PST 2003

CREATE SCHEMA ITSO;

CREATE TABLE ITSO.ACCOUNT


(ACCID CHARACTER(8) NOT NULL,
BALANCE DECIMAL(8, 2) NOT NULL,
INTEREST INTEGER NOT NULL,
ACCTYPE VARCHAR(8) NOT NULL,
DISCRIMINATOR CHARACTER(1) NOT NULL,
OVERDRAFT DECIMAL(8, 2) NOT NULL,

Chapter 6. Developing database applications 151


MINAMOUNT DECIMAL(8, 2) NOT NULL);

ALTER TABLE ITSO.ACCOUNT


ADD CONSTRAINT SQL030221140126480 PRIMARY KEY (ACCID);

CREATE TABLE ITSO.CUSTACCT


(CUSTOMERID INTEGER NOT NULL,
ACCID CHARACTER(8) NOT NULL);

ALTER TABLE ITSO.CUSTACCT


ADD CONSTRAINT SQL030221140126190 PRIMARY KEY (CUSTOMERID, ACCID);

CREATE TABLE ITSO.CUSTOMER


(CUSTOMERID INTEGER NOT NULL,
TITLE CHARACTER(3) NOT NULL,
FIRSTNAME VARCHAR(30) NOT NULL,
LASTNAME VARCHAR(30) NOT NULL,
USERID CHARACTER(8),
PASSWORD CHARACTER(8),
ADDRESS BLOB(2000));

ALTER TABLE ITSO.CUSTOMER


ADD CONSTRAINT SQL030221140125890 PRIMARY KEY (CUSTOMERID);
......

ALTER TABLE ITSO.CUSTACCT


ADD CONSTRAINT "CAtoAccount" FOREIGN KEY (ACCID)
REFERENCES ITSO.ACCOUNT(ACCID)
ON DELETE RESTRICT
ON UPDATE NO ACTION;

ALTER TABLE ITSO.CUSTACCT


ADD CONSTRAINT "CAtoCustomer" FOREIGN KEY (CUSTOMERID)
REFERENCES ITSO.CUSTOMER(CUSTOMERID)
ON DELETE RESTRICT
ON UPDATE NO ACTION;
......

XML schemas can be generated for tables. To generate an XML schema for a
table, you must already have imported it into a folder and be in the Data
Definition view.

Select the CUSTOMER table and Generate XML Schema from the context menu,
and the Create XML Schema dialog opens (Figure 6-13).

152 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-13 Create XML schema for database table

Click Finish and the schema file (with extension .xsd) is created and opened in
the XML schema editor. The content of the customer XSD file (visible in the
Source tab of the editor) is shown in Example 6-2.

Example 6-2 Generated XML schema


<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ibm.com/EJBBANK/ITSO"
xmlns:EJBBANKITSO="http://www.ibm.com/EJBBANK/ITSO">

<element name="CUSTOMER_TABLE">
<complexType>
<sequence>
<element ref="EJBBANKITSO:CUSTOMER" minOccurs="0"
maxOccurs="unbounded"/>
</sequence>
</complexType>
<key name="CUSTOMER_PRIMARYKEY">
<selector xpath="EJBBANKITSO:CUSTOMER"/>
<field xpath="CUSTOMERID"/>
</key>
</element>

<element name="CUSTOMER">
<complexType>
<sequence>
<element name="CUSTOMERID" type="integer"/>
<element name="TITLE">

Chapter 6. Developing database applications 153


<simpleType>
<restriction base="string">
<length value="3"/>
</restriction>
</simpleType>
</element>
<element name="FIRSTNAME">
<simpleType>
<restriction base="string">
<length value="30"/>
</restriction>
</simpleType>
</element>
<element name="LASTNAME">
<simpleType>
<restriction base="string">
<length value="30"/>
</restriction>
</simpleType>
</element>
<element name="USERID">
<simpleType>
<restriction base="string">
<length value="8"/>
</restriction>
</simpleType>
</element>
<element name="PASSWORD">
<simpleType>
<restriction base="string">
<length value="8"/>
</restriction>
</simpleType>
</element>
<element name="ADDRESS">
<simpleType>
<restriction base="base64Binary">
<length value="2000"/>
</restriction>
</simpleType>
</element>
</sequence>
</complexType>
</element>
</schema>

Notice the Graph page of the XML schema editor (Figure 6-14). Expand the
boxes by clicking the + icon.

154 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-14 XML schema editor: graph

Study the Outline view as well. It shows the structure of the XML schema file.

If you want, you can make changes to the XML file and generate a new DDL file
by selecting Generate -> DDL (context).

Creating database objects


Application Developer provides support for creating new databases, new
schemas, and new tables.

Create database
To create a new database you have to have a project. If you have not already
done so, you should now create a new simple project called
ItsoProGuideDatabase.

To create database objects you have to switch to the Data perspective and open
the Data Definition view.

Chapter 6. Developing database applications 155


To create a database select the ItsoProGuideDatabase project and New -> New
database definition. The Database creation dialog is displayed (Figure 6-15).

Figure 6-15 Database definition dialog

Here you specify the name of the new database and the vendor type. When you
later generate the database DDL it will conform to the database type that you
select. Click Finish to create the new database definition.

Important: Database definitions created within Application Developer are not


automatically created in the database system. You have to export the DDL and
use the appropriate database tool to create the objects, or you can submit the
DDL from Application Developer (see “Define the database schema in a
database system” on page 163).

Database schemas are a way of providing a logical classification of objects in the


database. Some of the objects that a schema may contain include tables, views,
aliases, indexes, triggers, and structured types. The support for schemas varies
between database types; some require them, and some have no support for
them. The schema options available to you depend on the database type that
you chose when the database was created. If the database type does not
support schemas at all, this option will not be available, and the tables and other
objects will be created directly under the database node.

156 WebSphere Studio Application Developer Version 5 Programming Guide


Create schema
To add a schema to the database, select the database created in the previous
step and New -> New schema definition. The Schema Definition dialog is
displayed (Figure 6-16).

Figure 6-16 Schema definition dialog

Select a name (ITSO) for the schema and click Finish to create it.

Expand the new schema in the Data Definition view and you will see the types of
objects that can be added to it.
򐂰 Tables
򐂰 Views
򐂰 Aliases
򐂰 Indexes
򐂰 Triggers
򐂰 Structured types
򐂰 Stored procedures
򐂰 User-defined functions

Note: In the current release of Application Developer, tables, views, stored


procedures, and user-defined functions can be created. The other types of
objects are not supported.

Create table
We will now look at how to create a new table in the schema. Application
Developer provides a wizard for defining table columns as well as primary and
foreign keys. To create a table, select the schema created in the previous step

Chapter 6. Developing database applications 157


and New -> New table definition. The Create table wizard is displayed
(Figure 6-17).

Figure 6-17 Table definition wizard: table name

Here you give the table a name and an optional comment. On the next page you
define the columns of the table (Figure 6-18).

Figure 6-18 Table definition wizard: columns

158 WebSphere Studio Application Developer Version 5 Programming Guide


Click Add Another to add a column to the table and define the column properties.
The exact properties available depend on the database type. For more
information about the properties available, you can consult the documentation
provided by the database vendor.

In our case, in addition to the CUSTOMERID field, we add FIRSTNAME and LASTNAME.
These two additional fields are of type CHARACTER with string length 30 and For bit
data not checked (Figure 6-17).

Figure 6-19 Table definition wizard: columns

The next page of the wizard lets you define the primary key of the table
(Figure 6-20).

Chapter 6. Developing database applications 159


Figure 6-20 Table definition wizard: primary key

You select the items you want from the Source Columns and add them to the
primary key by clicking >.

On the final page of the wizard you can define any foreign key constraints that
you want to apply. In our case, we do not have another table defined, so we do
not add a foreign key (Figure 6-21).

Figure 6-21 Table definition wizard: foreign keys

160 WebSphere Studio Application Developer Version 5 Programming Guide


Clicking Finish creates the table and keys as defined.

If you want, you can generate the DDL for the table you have just created. To do
so, select the table in the Data Definition view and Generate DDL and the
Generate SQL DDL dialog opens (Figure 6-22).

Figure 6-22 Generate DDL dialog

The options available are to create the DDL with or without the schema name,
whether to place delimiters around identifiers or not, whether or not to generate
DROP statements, and whether to open an editor on the generated file. The
generated DDL file is shown in Figure 6-23.

-- Generated by Relational Schema Center on Mon Mar 17 01:56:34 PST 2003

CREATE TABLE ITSO.CUSTOMER


(CUSTOMERID INTEGER NOT NULL,
FIRSTNAME CHARACTER(30) NOT NULL,
LASTNAME CHARACTER(30) NOT NULL);

ALTER TABLE ITSO.CUSTOMER


ADD CONSTRAINT C4956569 PRIMARY KEY (CUSTOMERID);

COMMENT ON TABLE ITSO.CUSTOMER IS 'Table containing customer details';

Figure 6-23 Generated DDL file for the customer table

Chapter 6. Developing database applications 161


You can use the generated DDL to create the table in the database system with
the help of the appropriate tool provided by the database vendor.

You can also execute the DDL on a database server. See “Define the database
schema in a database system” on page 163.

Create table with foreign key


Now we will create a second table with a foreign key. Use the same wizard as
above to create a CUSTADDRESS table with the following columns:
򐂰 ADDRESSID—as an INTEGER and also a key column
򐂰 CITY—as a CHARACTER 50
򐂰 COUNTRY—as a CHARACTER 50
򐂰 CUSTOMERID—as an INTEGER

On the foreign keys page of the wizard (Figure 6-24), click Add Another to add a
foreign key.

Figure 6-24 Defining a foreign key

162 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Select ITSO.CUSTOMER as the target table, then select CUSTOMERID in the
Source Columns list and click >. This defines the primary key of the
ITSO.CUSTOMER table to be the foreign key in the CUSTADDRESS table.
򐂰 Define constraints for referential integrity as RESTRICT for delete and NO
ACTION for update.
򐂰 Click Finish and the new table CUSTADDRESS, complete with foreign key has
been generated in our model. You can again generate DDL to produce the
DDL file for this table (Figure 6-25).

-- Generated by Relational Schema Center on Mon Mar 17 02:09:21 PST 2003

CREATE TABLE ITSO.CUSTADDRESS


(ADDRESSID INTEGER NOT NULL,
CITY CHARACTER(50) NOT NULL,
COUNTRY CHARACTER(50) NOT NULL,
CUSTOMERID INTEGER NOT NULL);

ALTER TABLE ITSO.CUSTADDRESS


ADD CONSTRAINT C0107854 PRIMARY KEY (ADDRESSID);

ALTER TABLE ITSO.CUSTADDRESS


ADD CONSTRAINT C4412200 FOREIGN KEY (CUSTOMERID)
REFERENCES ITSO.CUSTOMER(CUSTOMERID)
ON DELETE RESTRICT
ON UPDATE NO ACTION;

Figure 6-25 DDL for address table

Define the database schema in a database system


To define the ITSOTEST database with its schema and tables in a DB2 system,
generate the DDL for the database.

Select the ITSOTEST object and Generate DDL (context). Note that the generated
file (ITSOTEST.sql) does not contain the DDL for the database object itself, only
the schema and the tables are defined.

Create the database


Create the database, for example, in a DB2 Command Window with the
command:
db2 create database ITSOTEST

Chapter 6. Developing database applications 163


Create the schema and tables
Select the ITSOTEST.sql file and Run on Database Server. The Run Script dialog
opens (Figure 6-26). Select the statements that you want to execute.

Figure 6-26 Run DDL script

Click Next. On the next page, set the commit option, for example, Commit
changes only upon success (Figure 6-27).

Figure 6-27 Commit options for DDL script

Click Next. On the connection page, create a connection to the ITSOTEST


database. The dialog is the same as Figure 6-5 on page 146.

164 WebSphere Studio Application Developer Version 5 Programming Guide


Click Finish and the DDL statements are executed against the database. Using a
DB2 Command Window you can verify that the objects are created:
db2 connect to itsotest
db2 select * from itso.customer
db2 select * from itso.custaddress

This completes our look at creating database objects.

Creating SQL statements


There are two alternative ways of creating an SQL statement in Application
Developer:
򐂰 SQL Statement Wizard—The SQL Statement Wizard is a guided dialog
through a number of panels, with an SQL statement as the result.
򐂰 SQL Query Builder—The SQL Query Builder is an editor for an advanced
user.

Both tools can be used to build an SQL statement. After using the SQL
Statement Wizard, you can use the SQL Query Builder to updates the SQL
statement.

For our example we are developing a SELECT statement against the sample
EJBBANK database. We would like to see a list of all credit transactions where the
last name of the customer contains the letter “o”. We like to see the transaction
ID, account ID, and the first and last name of the customer, as well as the
transaction amount.

Basically we construct this SQL statement:


SELECT t.TRANSID, c.FIRSTNAME, c.LASTNAME, t.ACCID, t.TRANSAMT
FROM CUSTOMER c, CUSTACCT a, TRANSRECORD t
WHERE c.CUSTOMERID = a.CUSTOMERID
AND a.ACCID = t.ACCID
AND t.TRANSTYPE = 'C'
AND c.LASTNAME LIKE :lastname

Using the SQL Statement Wizard


In this section we create an SQL statement using the wizard.

To create some order in the project, select the ItsoProGuideDatabase project and
New -> Folder (Navigator view, context). Enter sql as the folder name.

Chapter 6. Developing database applications 165


Select the ItsoProGuideDatabase project and File -> New -> Other. Select Data
and SQL Statement in the New dialog and click Next to open the SQL Statement
Wizard (Figure 6-28).

Figure 6-28 SQL Statement Wizard: specify statement information

On the first page, you select the type of statement you want to create and say
that you want to use the wizard: Be guided through creating an SQL statement.

There are two ways to specify the database model. You can either use an
existing one or import a new one. In this case we already have the database
model imported into the Workbench, so we select Use existing database model.
Click the Browse button to locate the EJBBANK model in the Workbench and enter
the name of the SQL statement.

Selecting tables and columns


On the second page of the SQL Statement Wizard you build your SQL statement
by selecting tables, columns and adding joins and conditions. First we identify the
tables that should be included in the query (Figure 6-29).

166 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-29 SQL Statement Wizard: add tables

You select the tables in the left pane and use the > button to include them. For
our example we have the CUSTACCT, CUSTOMER, and TRANSRECORD tables. On the
Columns tab you select the columns from these tables that should be included in
the query (Figure 6-30).

Figure 6-30 SQL Statement Wizard: add columns

Chapter 6. Developing database applications 167


Select FIRSTNAME and LASTNAME from the CUSTOMER table and TRANSID, ACCID and
TRANSAMT from the TRANSRECORD table and move them across to the right pane.
Order the output columns using the Move Up and Move Down buttons.

Defining a table join


Next you have to specify the join columns between the three tables on the Join
tab. This is done by selecting the column from one table and dragging it to the
corresponding column of the other table. In our case we link
CUSTOMER.CUSTOMERID to CUSTACCT.CUSTOMERID and CUSTACCT.ACCID to
TRANSRECORD.ACCID. When the joins are complete, connection symbols are
displayed (Figure 6-31).

Figure 6-31 SQL Statement Wizard: add joins

Tip: You can rearrange the tables by dragging them on the pane. You can
enlarge a table by dragging the sides. You can also select the columns in this
dialog step, or make changes to the selection from the previous step.

Defining the conditions for the WHERE clause


The Conditions tab is used to define the restrictions on the SELECT statement.
Each condition is added to the WHERE clause (Figure 6-32).

Select the Column, Operator, Value, And/Or, using the drop-down menu (visible
after you click in the field). Enter the value by typing in the field.

168 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-32 SQL Statement Wizard: add conditions

Using a variable
In a real-life situation you might not want to hardcode that the last name contains
the letter o, but instead leave it as a host variable. Therefore, do not enter '%o%'
in the Value column, rather enter a variable as :lastname. This is especially
useful later in “Accessing databases from a Web application” on page 248.

Tip: If you have to enter more than one condition, you must put in the AND or
the OR element before the next row in the table becomes editable.

On the next two tabs you can enter information regarding grouping (GROUP BY)
and sorting of rows (ORDER BY).

Once you have finished building the statement you can click Next to see the
generated SQL statement (Figure 6-33).

If you want, you can edit the statement directly. When you are finished editing,
you can click Parse to validate that the SQL statement is correct.

Chapter 6. Developing database applications 169


Figure 6-33 SQL Statement Wizard: generated SQL statement

Executing an SQL statement


To test the SQL statement, you click Execute and then Execute again in the next
window. You are prompted for the host variable. Enter '%o%' and click Finish. The
statement is executed and the results are displayed (Figure 6-34).

Host variable prompt

Figure 6-34 SQL Statement Wizard: test SQL statement

170 WebSphere Studio Application Developer Version 5 Programming Guide


Select Close to close the Execute SQL Statement window, then select Finish to
save the SQL Statement.

The SQL statement is opened in the SQL Query Builder editor. Close the editor.
The SQL statement appears as EJBBANK_CreditListing.sqx in the Navigator
view, and as CreditListing in the Data Definition view (under EJBBANK ->
Statements).

Using SQL Query Builder


The other way of creating SQL statements in Application Developer is to use the
SQL Query Builder. This tool supports all the options of the SQL Statement
Wizard, with the addition of WITH and FULLSELECT. In this section we will describe
how to use the SQL Query Builder to build a similar SELECT statement as we did
using the SQL Wizard.

We develop a SELECT statement against the EJBBANK database. We would like to


select credit or debit transactions where the customer’s last name is a variable.
This time we want to display most of the columns of the CUSTOMER and
TRANSRECORD tables.

To start the SQL Query Builder, expand the database folder in the Data Definition
view. Select the Statements folder and New -> Select Statement. A dialog to
enter the name of the statement is displayed. Enter ListCredits and click OK.
The SQL Query Builder editor is displayed (Figure 6-35).

Figure 6-35 SQL Query Builder: create SELECT statement

Chapter 6. Developing database applications 171


To define your query, go through the following steps:
򐂰 First we must add the tables that are involved in the query. In our example
these are CUSTOMER, CUSTACCT, and TRANSRECORD. To add them, simply drag
them from the Navigator or Data Definition view and drop them in the middle
pane of the SQL Query Builder screen. The result is shown in Figure 6-36.
As you can see, the tables have been added to the SELECT statement in the
top pane.

join
join

Figure 6-36 SQL Query Builder: adding tables

򐂰 Next, select the columns from each table. To select a column, check the box
next to its name. For the CUSTOMER table, select all columns except ADDRESS.
For the TRANSRECORD table, select all columns. Do not select any columns of
the CUSTACCT table (they are duplicates anyway). As you select the columns,
the SELECT statement is updated in the top pane and the columns are added
in the bottom pane.
򐂰 Next, join the tables together. To join the tables, select the CUSTOMERID
column in the CUSTOMER table and drag it across to the corresponding column
in the CUSTACCT table. Next, select the ACCID column in the CUSTACCT table and
drag it across to the corresponding column in the TRANSRECORD table. A link

172 WebSphere Studio Application Developer Version 5 Programming Guide


symbol is shown between the tables, and the SELECT statement is updated
with the corresponding WHERE clauses.
򐂰 Finally, we want to add the two conditions (TRANSTYPE = :type and LASTNAME
LIKE :lastname). Use the Conditions tab in the bottom pane to add the
conditions using the drop-down menus, or type them directly into the SQL
statement and the Conditions tab is updated (Figure 6-37).

Join

Conditions

Figure 6-37 SQL Query Builder: adding conditions

Save the statement. You are prompted for the host variables; just click Cancel to
dismiss the dialog.

Chapter 6. Developing database applications 173


To test the statement, select it in the Statements folder and Execute (context) or
select SQL -> Execute in the menu bar.

Enter 'C' as the value for the :type and '%o%' as the value for the :lastname
variables in the Host Variable Values window and click Finish to execute the
query. The matching rows from the database are shown in the DB Output view
(Figure 6-38).

Figure 6-38 SQL Query Builder: testing the SQL statement

Later on we will look at how you can use Application Developer to generate Web
pages and Java classes to quickly and easily build an application based on an
SQL statement that uses host variables.

We will use this SQL statement in “Accessing databases from a Web application”
on page 248.

Accessing databases from a Java application


We have already seen an example of how to access a relational database using
JDBC from a Java application. In Chapter 5, “Developing Java applications” on
page 93 we created a simple application (CustomerListing, Figure 5-10 on
page 102) that accesses a DB2 table to return a list of customers. We now take a
closer look at database access.

Access using the DriverManager


We use the driver manager class to manage the connection to the database.
First we have to establish a connection to the database as shown in Figure 6-39.
򐂰 The first thing that has to be done is to load the JDBC driver. The
Class.forName() call does this. The driver name is dependent on which
database you are connecting to.

Note: You do not have to create an instance of the driver or register it. This is
done automatically for you by the DriverManager class.

174 WebSphere Studio Application Developer Version 5 Programming Guide


protected static Connection connect() {
Connection con = null;
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
con = DriverManager.getConnection("jdbc:db2:EJBBANK");
} catch(Exception e) {...}
return con;
}

Figure 6-39 Establish a connection to the database

򐂰 After loading the driver, you have to establish a connection. The class that
handles this is called DriverManager.
The URL string that is passed in to the getConnection method is again
dependent on which database system you are using. In the example above,
we are connecting to a DB2 database called EJBBANK. In this example we are
not passing a user ID and password, but if that was required, they would be
the second and third parameters of the getConnection call.

DB2 JDBC drivers


DB2 supplies two JDBC drivers:
򐂰 COM.ibm.db2.jdbc.app.DB2Driver—This is a JDBC type 2 driver that uses
a DB2 client installed on the machine where the application runs. You would
use this driver when accessing a local database or a remote database
through a local DB2 client. The database URL has the format:
jdbc:db2:databasename
򐂰 COM.ibm.db2.jdbc.net.DB2Driver—This is a JDBC type 3 driver. It is a Java
driver that is designed to enable Java applets access to DB2 data sources.
Using this driver your application will talk to another machine where the DB2
client is installed. The database URL has the format:
jdbc:db2://hostname:port/databasename
The standard port of the DB2 JDBC Applet Server service is 6789. This DB2
service must be started in your machine.
To connect to a database you have to supply user ID and password:
con = DriverManager.getConnection("jdbc:db2://localhost:6789/EJBBANK",
"db2admin","db2admin");

In our examples we use the DB2 app driver because we are talking to a local
database. If you are trying to connect to another database system, you should
consult the documentation to determine what driver name and URL to use.

Chapter 6. Developing database applications 175


The classes required when connecting to a DB2 database from Java are found in
.\sqllib\java\db2java.zip. You would make this available in Application
Developer by creating a classpath variable for it and adding that to the project
build path, as explained in “Running your programs” on page 103.

Executing SQL statements


You are now ready to perform operations on the database. How to execute a
simple select statement is shown in Figure 6-40.

stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM ITSO.CUSTOMER");

Figure 6-40 Executing a simple select statement

You create a statement using the connection obtained from the DriverManager
and then you execute the query passing the select statement. The result set from
the query is returned in a ResultSet variable.

Next, you have to process the result set from the query. The ResultSet class
provides a number of get methods for various data types as shown in
Figure 6-41.

while (rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String userID = rs.getString("userID");
System.out.println(firstName + " " + lastName + " " + userID);
}

Figure 6-41 Processing the result set from the query

Finally, JDBC objects must be closed to release the resources (Figure 6-42). The
best place is a finally clause that is executed even in case of exceptions.

} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}

Figure 6-42 Releasing JDBC resources

176 WebSphere Studio Application Developer Version 5 Programming Guide


Access using a data source
JDBC access using a data source is not well suited for stand-alone applications.
It is, however, the preferred way to access databases from Web applications
where multiple clients use the same servlet for database access.

Figure 6-43 shows the basic code sequence to get a connection through a data
source.

try {
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource)
ctx.lookup("jdbc/ejbbank");
con = ds.getConnection();
} catch (javax.naming.NamingException e) {
System.err.println("Naming-Exception: " + e.getMessage());
} catch (java.sql.SQLException e) {
System.err.println("SQL-Exception: " + e.getMessage());
}

Figure 6-43 Getting a connection through a data source

The data source is retrieved using a the lookup method of the InitialContext.
The data source must be registered in the JNDI server. In our example we use a
JNDI name of jdbc/ejbbank, which points to the EJBBANK database.

Once a connection is obtained, the rest of the code is the same.

Retrieving the data source is expensive. Good coding practice for Web
applications is to retrieve the data source only once in the init method of a
servlet, and to get and release a connection in the doGet or doPost method for
each client request.

We explore database access in Web applications in Chapter 8, “Developing Web


applications with database access” on page 247.

J2EE client application


In “Building an application client module” on page 614 we implement a modified
version of the CustomerList program. The CustomerListDS program uses a data
source and runs as a J2EE client application accessing the EJBBANK database,
which is defined in a WebSphere server through a data source.

Chapter 6. Developing database applications 177


Summary
We have introduced you to JDBC and data sources, and have seen how to create
and connect to databases using Application Developer.

In particular we covered the Data perspective and the generation of SQL


statements.

178 WebSphere Studio Application Developer Version 5 Programming Guide


7

Chapter 7. Developing Web


applications
In this chapter we develop a Web application as part of an enterprise application.
We develop static and dynamic content in the form of an HTML page, a servlet,
and a JSP.

We use the Page Designer, CSS Designer, and wizards to create servlets and
JSPs. To experiment with the new J2EE 1.3 functions, we develop both a sample
filter and a listener.

Finally, we use the wizard to create a simple Web application from a JavaBean.

© Copyright IBM Corp. 2003. All rights reserved. 179


Introduction
This chapter guides you through the Application Developer’s features designed to
assist you in the creation of Web applications.

We will start off by introducing you to the sample application that will be used
throughout this chapter, and in later chapters as well. We will then proceed to
create a new Web project to hold our example application. Once the project is in
place, we are able to add both static and dynamic content to it, and to use tools
and wizards, such as Page Designer, CSS Designer, and creating Web pages
from a JavaBean.

Even though this chapter does not assume that you are always in the Web
perspective of Application Developer, you may find it easier to perform the tasks
described here using the Web perspective.

Sample application: RedBank


In this section we describe the architecture for our sample banking application:
RedBank.

Note that the intent of this chapter is to introduce you to the Application
Developer’s tools that make the development of Web applications possible.
Together we will work only on a single HTML page, a single servlet, and a single
JSP page. The rest of the application has already been developed and is made
available to you so that you can explore it if you would like to.

The RedBank application was designed using the MVC architecture pattern,
which we will cover in more detail in Chapter 10, “Developing Struts applications”
on page 293.

Because the same example is used throughout the book, you will have the
opportunity to see how little it changes in the face of varying design constraints
and evolving techniques. This is in fact the most important characteristic of the
MVC pattern.

We are now going to introduce you to how the application implements each of the
MVC layers, so that you feel more comfortable with its design.

Model
The RedBank application’s business model (Figure 7-1) is described in “Banking
model” on page 111, and the code is imported into the ItsoProGuideJava project.

180 WebSphere Studio Application Developer Version 5 Programming Guide


Banking Bank Customer

Account TransRecord

Figure 7-1 Banking model revisited

Controller
The control layer was implemented using two different strategies: one
straightforward; and the other a little bit more complex, but more realistic. We did
so to keep the discussion in the book simple, but still have a nice example.

The application has a total of four servlets:


򐂰 ListAccounts—get the list of accounts for one customer.
򐂰 AccountDetails—display the account balance and the selection of
operations: list transactions, deposit, withdraw, and transfer.
򐂰 InvalidateSession—invalidate the session data.
򐂰 PerformTransaction—perform the selected operation by calling the
appropriate control action: ListTransactions, Deposit, Withdraw, or
Transfer.

Three of the servlets, including the ListAccounts servlet that you will implement,
fall into the first category. They work as sole controllers, without any external
collaboration. It is easier to implement and understand them this way.

The last of the four servlets, PerformTransaction, falls into the second category.
It acts as a front controller, simply receiving the HTTP request and passing it to
the appropriate control action object. These objects are responsible for carrying
out the control of the application. For a more thorough explanation of this
strategy, and the motivation behind it, please read Chapter 10, “Developing
Struts applications” on page 293.

Note: Action objects, or commands, are part of the command design pattern.
For more information, refer to Design Patterns: Elements of Reusable
Object-Oriented Software.

Chapter 7. Developing Web applications 181


View
The RedBank application’s view layer is comprised of an HTML file and four JSP
files. The application home page is the index.html file (Figure 7-2).

Figure 7-2 RedBank home page (index.html)

The home page allows you to type the customer ID to access the customer
services. There is no dynamic content in this page, so we use plain HTML. Note
that security issues (logon and password) are not covered in this book.

The second Web page (Figure 7-3) displays the customer’s accounts for
selection.

Figure 7-3 RedBank account listing (listAccounts.jsp)

The customer’s name and the available accounts are processed dynamically, as
they depend on the given customer ID, so we implemented this page as a JSP.

182 WebSphere Studio Application Developer Version 5 Programming Guide


After selecting an account, the user can view the logged transactions or perform
banking transactions, such as deposit, withdraw, and transfer (Figure 7-4).

Figure 7-4 RedBank account maintenance (accountDetails.jsp)

The maintenance screen also shows the current account number and balance,
both dynamic values. A simple JavaScript code controls whether the amount and
destination account fields are available or not, depending on the option selected.

If the user chooses to list the logged transactions, the Web page shown in
Figure 7-5 is displayed.

Figure 7-5 RedBank transaction log (listTransactions.jsp)

Chapter 7. Developing Web applications 183


This is a mostly dynamic page. The user may check the transaction number,
date, type, and amount. The color of the table rows alternate for readability
reasons.

Finally, if anything goes wrong in the regular flow of events, the exception page is
shown to inform the user (Figure 7-6).

Figure 7-6 RedBank exception page (showException.jsp)

The only dynamic content in this page is the message displayed to the user. In
the example shown in Figure 7-6, we entered an invalid customer ID.

Facade
We will use a copy of the facade in the Web application. It is better to have the
facade in the Web application to be able to access a different model that is
implemented in another project (for example as EJBs).

Application flow
The flow of the application is shown in Figure 7-7:
򐂰 The view layer is comprised of one HTML file (index.html) and four JSPs.
You will implement the index.html and the listAccounts.jsp.
򐂰 The control layer is comprised of four servlets and four action classes. The
PerformTransaction servlet passes control to one of the action classes.
You will implement the ListAccounts servlet.
򐂰 The model layer is comprised of the facade and four model classes. All
interactions from the servlets and actions classes go through the facade, the
Banking class.
The model is available in the ItsoProGuideJava project, which will be a utility
project in the enterprise application.

184 WebSphere Studio Application Developer Version 5 Programming Guide


index listAccounts accountDetails listTransactions VIEW

showException

ListAccounts AccountDetails PerformTransation CONTROL

Invalidate
Session ListTransactions Deposit Withdraw Transfer

Facade Banking

MODEL
Bank - Customer - Account - TransRecord

Figure 7-7 Banking application flow

Creating a Web project


In Application Developer, you create and maintain Web resources in Web
projects. They provide a development environment that enables you to perform
activities such as link-checking, building, testing, and publishing. Within a Web
project, Web resources can be treated as a portable, cohesive unit.

Web projects can be static or dynamic. Static Web projects are comprised solely
of static resources, which can be served by a traditional HTTP server (HTML
files, images, and so forth), and are useful for when you do not have to program
any business logic. J2EE Web projects, on the other hand, may deliver dynamic
content as well, which gives them the ability to define Web applications.

A Web application contains components that work together to realize some


business requirements. It might be self-contained, or access external data and
functions, as it is usually the case. It is comprised of one or more related servlets,
JavaServer Pages, and regular static content, and managed as a unit.
Throughout this chapter, we will create both static and dynamic content. Thus,
we need a J2EE Web project to support our tasks.

Chapter 7. Developing Web applications 185


Project name and features
To create a new Web project, select File -> New -> Web Project. The dialog in
Figure 7-8 is displayed.

Figure 7-8 Create a Web project wizard: name and features

Most of the time you will just have to set the project’s name and type. In our case,
we are creating a new J2EE Web project named ItsoProGuideBasicWeb.
Advanced users may also want to change the other options on the window:
򐂰 Use default—Deselect the check box to change the project file location.
򐂰 Web project features—Select one or more of the various options to add
additional features to your Web project. When you select a feature, a detailed
description is provided for you. For now, we will just use a default CSS file.
Later on you will be introduced to more advanced features.

186 WebSphere Studio Application Developer Version 5 Programming Guide


Enterprise application features
Click Next to move to the wizard’s second page (Figure 7-9).

Figure 7-9 Create a Web project wizard: enterprise application

J2EE Web modules, such as the project we are creating, run exclusively within
enterprise applications. For this reason, you have to either select an existing
enterprise application project, or let the wizard create a new one for you.

Type ItsoProGuide in the New project name field. Optionally you can set the
advanced options on this page, which are:
򐂰 Context root—The context root defines the Web application. The context root
is the root part of the URI under which all the application resources are going
to be placed, and by which they will be later referenced. It is also the top level
directory for your Web application when it is deployed to an application server.
Context roots are case-sensitive, so are all the Java URLs. Many developers
like to make their context root all lowercase in order to facilitate the manual
entering of URLs. The context root you select must be unique among all Web
modules within the same application server cell. Application Developer’s
default is to use the project’s name as the context root.
򐂰 J2EE level—You usually want to select the greatest J2EE level that your
target application server allows. For WebSphere Application Server Version 5,

Chapter 7. Developing Web applications 187


that would be J2EE 1.3. Selecting any of the two allowed levels will show you
details on the supported APIs.

Click Finish and the enterprise application and the Web project are created.

Adding the banking model as a utility JAR


The Web application requires the banking model that is in the ItsoProGuideJava
project. To add the ItsoProGuideJava project as a utility JAR file:
򐂰 Expand the ItsoProGuide enterprise application project and open the EAR
Deployment Descriptor (double-click).
򐂰 On the Module page (Figure 7-10), click Add under Project Utility JARs.
򐂰 Select the ItsoProGuideJava project and click Finish. The utility JAR file is
added.
򐂰 Save the deployment descriptor and close the editor.

Figure 7-10 Adding a utility JAR to an enterprise application

188 WebSphere Studio Application Developer Version 5 Programming Guide


Module dependencies
To make the utility JAR available to the Web application we have to specify a
module dependency:
򐂰 Open the Web project properties (select the ItsoProGuideBasicWeb project
and Properties from the context menu).
򐂰 Select the Java JAR Dependencies page and then select the
ItsoProGuideJava.jar file (Figure 7-11).
򐂰 Click OK.

Figure 7-11 Project properties: Java JAR dependencies

Project properties
The project properties dialog can be used at any time to change dependencies or
to change the context root, J2EE level, and other features.

For example, to change the context root, open the properties and select the Web
page (Figure 7-12).

Chapter 7. Developing Web applications 189


Figure 7-12 Project properties: context root

Web project directory structure


The Web project uses the directory structure shown in Figure 7-13.

Figure 7-13 Web Project in the J2EE navigator

190 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Java Source—This folder contains the project’s Java source code for regular
classes, JavaBeans, and servlets. When resources are added to a Web
project, they are automatically compiled and the generated files are added to
the Web Content\WEB-INF\classes folder. By default, the contents of the
source directory are not packaged in exported WAR files. If you want them to
be, you have to select the appropriate option when exporting the WAR file.
򐂰 Web Content—This folder holds the contents of the WAR file that will be
deployed to the server. It contains all the Web resources, including compiled
Java classes and servlets, HTML files, JSPs, and graphics needed for the
application.

Important: Any files not under Web Content are considered design time
resources (for example .java and .sql files) and will not be deployed when
the project is published. Make sure that you place everything that should
be published under the Web Content folder.

– Web Content\META-INF
This folder holds the MANIFEST.MF file, which describes the Web module’s
external dependencies.
– Web Content\theme
Contains cascading style sheets and other style-related objects.
– Web Content\WEB-INF
This directory holds the supporting Web resources for the Web module,
including the Web deployment descriptor (web.xml), IBM WebSphere
extensions’ descriptors (ibm-web-bnd.xmi and ibm-web-ext.xmi), and the
classes and lib directories.
– Web Content\WEB-INF\classes
Contains the project’s Java compiled code for regular classes, JavaBeans,
and servlets. These are the Java classes that will be published to the
application server and loaded in run-time. The class files are automatically
placed in this directory when the source files from the Java Source
directory are compiled. Any files placed manually in this directory will be
deleted by the Java compiler when it runs.
– Web Content\WEB-INF\lib
Contains utility JAR files that your Web module references. Any classes
contained in these JAR files will be available to your Web module.

Chapter 7. Developing Web applications 191


Importing existing resources
In most cases you do not have to start a Web project from scratch; rather you
import existing external resources into your Workspace.

Application Developer lets you import resources from a wide selection of


sources, such as:
򐂰 EAR, WAR, JAR, ZIP, and RAR files
򐂰 Existing projects in the workspace
򐂰 Existing WebSphere Studio V4 ClearCase projects
򐂰 Folder and files from the file system
򐂰 FTP and HTTP sites

As mentioned earlier, you will only develop a small part of our sample application.
The rest of the resources have been made available for you and have to be
imported now.
򐂰 Select File -> Import to open the import wizard. Select WAR file and click Next
to proceed to the second page (Figure 7-14).

Figure 7-14 Importing resources from a WAR file

192 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Select the WAR file by clicking Browse and navigating to
\sg246957\sampcode\dev-web\initial\ItsoProGuideBasicWeb.war.
򐂰 Because we have already created our Web project, select Existing and click
Browse. A small dialog pops-up and lets you select the
ItsoProGuideBasicWeb project. Click OK to continue.

Note: As you can see, you could have created the enterprise application
project, the Web project, and imported the resources in just one step using
this wizard.

򐂰 The Context Root and Enterprise application project fields are automatically
filled in for you. Select Overwrite existing resources without warning and click
Finish to import the resources.

What did we import? We imported the facade (itso.bank.facade.Banking,


which is a copy of the BankingTest class used in “Banking model” on
page 111, the control layer (itso.basicweb.control), three JSPs, an image,
and a CSS style sheet. We will develop the missing pieces of the application.

Creating static Web resources


Now that you have imported the initial set of resources for our sample
application, it is time that you learn how to develop your own. We will start by
creating a static web resource: an HTML page.

Page Designer
Page Designer is the main Application Developer tool used by Web designers to
create HTML pages. It is a WYSIWYG editor that generates the underlying
HTML code and frees the Web designer to concentrate on the visual aspect of
the page rather than on the details of HTML syntax. Page Designer currently
supports the HTML 4.01 specification.

The Page Designer shows three views of an HTML page: design, source, and
preview.
򐂰 In the Design view the work is done visually.
򐂰 In the Source view you manually edit the HTML code. You can use the content
assist feature, the same as for editing Java files. Pressing Ctrl-Space will
bring up a pick list of context-appropriate selections to choose from.
򐂰 The Preview view shows what the page will look like to the user, and thus is
read-only.

Chapter 7. Developing Web applications 193


Changes in the Design and Source views will automatically update each other,
as well as the preview view. You can also preview your page using an external
Web browser by selecting Tools -> Launch External Web Browser -> Default Web
Browser.

Syntax validation
When you save an HTML page, it will not be automatically validated for syntax
compliance by default. To manually validate the syntax of an HTML page, select
Tools -> Validate HTML Syntax .

Alternatively, you can choose to have Application Developer automatically do this


for you, a setting that can be platform-wide (Window -> Preferences ->
Validation) or project-wide (Properties -> Validation, on the Web project's context
menu).

To demonstrate the basic capabilities of Page Designer, we will walk you through
the building of a simple HTML page. In the next section, we discuss in more
detail how to use servlets and JSPs to provide dynamic content on our
application.

Create a simple HTML page


To add a new HTML page to a Web project, select the Web Content folder in your
Web project and New -> HTML/XHTML File from its context menu. This displays
the dialog shown in Figure 7-15, through which you give the page a name and a
location.

Figure 7-15 Create a new HTML/XHTML file wizard (page 1)

194 WebSphere Studio Application Developer Version 5 Programming Guide


Because we had the Web Content folder selected, the wizard automatically fills in
the folder field. You can change it by typing in a new value, or clicking Browse.

The other important information that you have to provide on this page is the file
name, in this case index. You may or may not type the file’s extension. If you do
not, the .html extension is added for you by the wizard.

The other field lets you specify the document’s markup language. In our case, it
should just be the default value of HTML, but other options would be HTML
Frameset, XHTML, or XHTML Frameset.

The Extensible HyperText Markup Language (XHTML) is a class of languages


and modules that reproduce the HTML language in valid XML syntax. It is useful
when you need to process HTML with XML-based user agents, which require
syntactically accurate documents.

Finally, there is the model field, but it is not used in the creation of HTML files.
Click Next to advance to the next page on the wizard (Figure 7-16).

Figure 7-16 Create a new HTML/XHTML file wizard (page 2)

Chapter 7. Developing Web applications 195


The wizard’s second page allows you to change the document’s character
encoding, which defaults to the Workbench’s default setting.

It also permits that you change the content and document types. Your options
depend very much on the markup language that you chose on the previous page.
If you chose HTML, for instance, then the content type is limited to text/html and
the document type should be one of the following:
򐂰 HTML 4.01 Strict—This is a downsized version of HTML 4.01. It allows for the
writing of more portable documents, because it emphasizes structure over
presentation. Deprecated elements and attributes, frames, and link targets
are not allowed in HTML 4.01 Strict. This document type depends very much
on style sheets for presentation.
򐂰 HTML 4.01 Transitional—Includes all elements and attributes of HTML 4.01
strict, plus presentational attributes, deprecated elements, and link targets. It
is a more common document type because it shows nice in browsers that
have limited or no support for style sheets.
򐂰 HTML 4.0 Frameset—This is a variant of HTML 4.01 Transitional, used for
documents that contain frames.

Finally, you can associate style sheets with the new document. By default, the file
Master.css is assigned, but you can add and remove files as you see fit. Click
Finish to complete the wizard.

Using the Page Designer


The Page Designer is opened on the new HTML page and you can now start
adding your page elements. In this example we will add the following elements:
the page title, meta tags to prevent Web clients from caching the page, a table,
an image, a static text, a form, a text field, and a submit button. Make sure you
are in the Design view to perform the tasks described below.

Start by deleting the default text paragraph that the wizard generated. To do that,
simply select the whole paragraph (or click Ctrl-A) and then click the Delete
button.

We will now set the page title and add the meta tags that will tell the Web client
not to cache the page. Most of the times static pages can and should be cached
to improve on performance. However, our static page is referenced not only
directly (by its file name) but also by a servlet (InvalidateSession). We do not
want the Web client to use the cached page when the servlet is called. We
instead want the servlet to receive the request again.

Select Page Properties on the document’s context menu. The dialog in


Figure 7-17 is displayed.

196 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-17 HTML page properties

򐂰 Type the page title (RedBank) on the Page Information tab.


򐂰 Switch to the Meta Info tab and enter the last six attributes shown in
Figure 7-17 (the first three should be there already). Click Add for each new
line, select NAME or HTTP-EQUIV from the drop-down menu, and enter the
item and content values.
򐂰 Click OK to close the dialog. If you switch over to the source tab you will
notice that the HTML code has been updated. The following content has been
added to the head of the document:
<TITLE>RedBank</TITLE>
<META name="Cache-Control" content="no-cache">
<META name="Pragma" content="no-cache">
<META name="Expires" content="-1">
<META content="no-cache" http-equiv="Cache-Control">
<META content="no-cache" http-equiv="Pragma">
<META content="-1" http-equiv="Expires">

Tip: You may alternatively copy and paste the text above directly to the HTML
source through the Source view.

Chapter 7. Developing Web applications 197


Our next step is to insert a simple table to hold our logo. Position the cursor on
the top of the page and then select Table -> Table. Our table will have just one
row and two columns, as shown on Figure 7-18. After setting the correct values,
click OK.

Figure 7-18 Insert a table dialog

The new table is inserted, and the first cell selected. Both cells should be of the
same size and very small, because they are still empty.

We do not want the table to have visible borders. Select the table (or any of its
cells) and Attributes (context) or select Window -> Show View -> Attributes. Set
the border attribute to 0 (Figure 7-19).

Figure 7-19 Table attributes

Now let’s fill the table with content. Select the left cell and type RedBank. We want
this text to be formatted as a heading 1. To accomplish this, select it and then
click Format -> Paragraph -> Heading 1. We also want the first three characters
(Red) to be in red. Select them and then click Format -> Font. Type red on the
color field and click OK.

198 WebSphere Studio Application Developer Version 5 Programming Guide


Alternatively, you can use the colors view to carry out the same task. With the
text still selected, select Window -> Show View -> Colors to display the colors
view. Select the color red from the palette (#FF0000). Finally, make sure the target
attribute is set to Text Color and then click the larger red box.

The second table cell should contain an image: itso.gif. It was imported along
with the rest of the resources and can be found in the Web Content\images folder.
Open the thumbnail view by selecting Window -> Show View -> Thumbnail and
then select the images folder in the J2EE Navigator view. You should now see the
thumbnail of the imported image, as shown in Figure 7-20. Simply drag and drop
it into the second table cell. Alternatively you can also expand the images folder
and drag/drop the itso.gif file into the second table cell.

Figure 7-20 Thumbnail view

Our next task is to place a second heading on the page, right after the table that
we have just created. Type the text Welcome to the ITSO Bank and format the
text as a heading 2.

After the heading comes a form, where the user can enter information that will be
sent back to the server. Click Insert -> Form and Input Fields -> Form. The form
should have a descriptive text that reads Please, enter your customer ID in the
field below:, a text field named customerNumber (Insert -> Form and Input Fields
-> Text Field) and a Submit button (Insert -> Form and Input Fields -> Submit
Button, set the label to Submit). The elements should be separated by a blank
line. The resulting form should look like Figure 7-21.

Figure 7-21 Example HTML form

Chapter 7. Developing Web applications 199


Finally, we will create an HTML link to another Web site. Insert the text For more
information on ITSO and RedBooks, please visit our Internet site at the very end
of the document. Highlight the text Internet site and select Insert -> Link. On the
URL field, enter http://www.redbooks.ibm.com.

The edited page in the Design view is shown in Figure 7-22.

Figure 7-22 Example HTML page

To save the page and validate your changes, select File -> Save index.html, or
alternatively press Ctrl-S. You may now close the editor window.

Using the CSS Designer


Cascading style sheets (CSS) allow authors and readers to attach multiple
presentation styles (such as fonts, colors, and spacing) to an HTML document.
By applying the same set of styles to all the presentation files of a Web
application, you can give it a much more homogeneous and coherent look, just
like a standard set of widgets would do to a GUI application.

Application Developer supports the following World Wide Web Consortium


(W3C) cascading style sheet standards:
򐂰 CSS1 (cascading style sheet level 1)
򐂰 CSS2 (cascading style sheet level 2)
򐂰 CSS Mobile Profile 1.0

In addition, the WAP Forum standard WCSS 1.0 (WAP CSS 1.0) is also
supported.

200 WebSphere Studio Application Developer Version 5 Programming Guide


As was mentioned earlier, you can have Application Developer create a default
CSS for you when you create a project. You can still create as many CSS files as
you like, but for now the default one will do. We just have to make some
modifications to it.

Application Developer provides a special editor to modify CSS files: the CSS
Designer. CSS Designer shows the source of a CSS file, and enables you to edit
styles with the help of syntax highlighting, content assist, and preview function.
The modifications made in CSS Designer are immediately applied to the design
page of Page Designer if the HTML file has a link to the CSS file.

To access the CSS Designer, double-click the existing style sheet in your Web
project (Web Content\theme\Master.css). This will bring up the style sheet editor,
comprised of source and preview panes, and the styles view (Figure 7-23).

Source Pane Preview Pane

Styles View

Figure 7-23 CSS Designer: style sheet editor

Chapter 7. Developing Web applications 201


If you are familiar with CSS file syntax, you can use the source pane to edit the
file directly. Just like when editing HTML files, you can use the content assist
feature to help you select values. If you press Ctrl-Space, a pick list of choices
appropriate to where the cursor is currently positioned will be displayed.

If you prefer, you can instead use the CSS Designer dialogs to edit or add styles
(accessible through the styles view, or through the style menu). These dialogs
are context sensitive and will open up on the style that is currently selected in the
editor.

Finally, the preview pane shows you how the styles will look like when applied to
an HTML file. By default, a sample HTML file is used, but you can choose to
preview the style changes with any file on your Web project.

For our example, we will change the appearance of two HTML elements: H1 and
H2. The first one will be edited directly through the source pane. Find the H1
style definition and manually change the color attribute to black. After edited, the
style source should look like the following:
H1
{
COLOR: black;
FONT-FAMILY: 'Times New Roman';
TEXT-TRANSFORM: capitalize
}

The second style will be changed via the editor's dialog. Double-click the H2 style
in the styles view to bring up the style properties dialog (Figure 7-24).

Figure 7-24 Style properties editor

202 WebSphere Studio Application Developer Version 5 Programming Guide


Change the following attributes: font color to white; background-color to #6098C8;
and padding in all directions to 2px. The items marked with an asterisk are the
items that have been changed. After the changes have been applied, the H2
style source should look as follows:
H2
{
COLOR: white;
FONT-FAMILY: 'Times New Roman';
TEXT-TRANSFORM: capitalize;
background-color: #6098C8;
padding: 2px;
}

Save your changes and close the style editor. Open up the index.html file and
verify its new look (Figure 7-25).

Figure 7-25 Example HTML page with CSS applied

Creating dynamic Web resources


There are many ways to create dynamic Web applications. The most
time-consuming method is to build the pages manually, by writing the code
line-by-line in a text editor. An easier and more productive way is to use the
Application Developer wizards in conjunction with content-specific editors, such
as the HTML and CSS editors, which we have already used.

The Web development wizards help you quickly create forms, HTML pages,
JavaServer Pages (JSPs), and Java servlets, even if you are not an expert
programmer. These files can be used as is, or modified to fit your specific needs.

Chapter 7. Developing Web applications 203


Application Developer wizards not only support you in creating servlets, JSPs,
and JavaBeans, but they also compile the Java code and store the class files in
the correct folders for publishing to your application servers. In addition, as the
wizards generate project resources, the deployment descriptor file, web.xml, is
updated with the appropriate configuration information for the servlets that are
created. You can test the resulting project resources within the Application
Developer using the WebSphere Test Environment, or any other configured
server that supports the chosen J2EE specification level.

Working with servlets


Servlets are flexible and scalable server-side Java components based on the
Sun Microsystems Java Servlet API, as defined in the Sun Microsystems Java
Servlet Specification. For J2EE 1.3, the supported API is Servlet 2.3.

Servlets generate dynamic content by responding to Web client requests. When


an HTTP request is received by the application server, the server determines
which servlet is responsible for answering that request (based on the requested
URI) and forwards the request to that servlet. The servlet then performs its logic
and builds the response HTML that is returned back to the Web client.

Application Developer provides the necessary features to make servlets easy to


develop and integrate into your Web application. Without leaving your
Workbench, you can develop, debug, and deploy them. You can set breakpoints
within servlets, and step through the code. You can make changes that are
dynamically folded into the running servlet on a running server, without having to
restart the server each time.

Adding a servlet to your Web project


Application Developer provides a servlet wizard to assist you in adding servlets
to your Web applications.

To start it, select File -> New -> Other. Select Web -> Servlet and click Next.
Alternatively, you can switch to the J2EE Navigator view, select the Java Source
folder in your Web project folder, and select New -> Servlet from its context
menu. The wizard starts with the dialog shown in Figure 7-26.

204 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-26 New servlet wizard (page 1)

The wizard’s first page will require you to fill out the following information:
Folder The source folder of your Web project. In our case, it is
\ItsoProGuideBasicWeb\Java Source.
Java package The package in which the servlet class will be created. For our
example, it should be itso.basicweb.control.
Class Name The servlet’s class name. We will implement the ListAccounts
servlet.
Superclass Usually, and this is true to our example, you will select the
javax.servlet.http.HttpServlet as your servlet’s superclass.
Application Developer requires you to select a class that
implements the javax.servlet.Servlet interface.

Chapter 7. Developing Web applications 205


Modifiers These are the usual Java class modifiers. We will go with
public. Servlets can also be abstract or final, but not both.
Options The only option that you have here is to have your servlet
implement the SingleThreadModel interface. This option should
only be selected for servlets that must have read/write state
accessed during their service methods. The need to implement
the SingleThreadModel interface probably indicates a poor
design.
Interfaces Which additional interfaces your servlet needs to implement.
Model No models are available for simple servlets.

Click Next to proceed to the wizard’s second page, shown in Figure 7-27.

Figure 7-27 New servlet wizard (page 2)

This page lets you select the appropriate method stubs to be created in the
servlet code. These are the servlet’s life-cycle methods, along with its service
methods specific to the HTTP protocol (the methods that start with “do”).

206 WebSphere Studio Application Developer Version 5 Programming Guide


For our example, we need both doGet and doPost selected. Both are read
methods. Usually, HTTP gets are used with direct links, when no information
needs to be sent to the server. HTTP posts are typically used when information in
a form has to be sent to the server.

Only one instance of a servlet is created in the application server. If you want to
perform any initialization when the servlet instance is created, select the init
method to be created. This method is invoked after the servlet instance has been
created and you can perform the initialization tasks.

Another check box lets you select whether or not you want to generate stubs for
the inherited abstract methods. You should select it if your servlet is concrete.

Because constructors are not inherited in Java, you may also want to generate
constructors that call their counterpart in the superclass.

Finally, the wizard lets you choose whether or not to add the new servlet to the
Web deployment descriptor. If you choose to do so, and we do for our sample
application, you can also define initialization parameters and their values, and the
URLs mapped to the servlet. We will stick to the default URL mapping suggested
by the wizard, which equals the servlet name.

You can now click Finish to complete the process. The servlet is generated and
added to the project. In the J2EE Hierarchy view you can see the servlet and its
mapping in the Web module. In the J2EE Navigator view you can see the servlet
file ListAccounts.java inside the itso.basicweb.control package. An editor is
opened, where you can view and edit the generated servlet source code.

Editing the servlet


Application Developer generates a skeleton servlet for you. Your task is now to
add code to the servlet in order to implement the required behavior for your
needs. The code is provided in:
\sg246957\sampcode\dev-web\servlet

Start by adding these import statements to the statements generated for you:
import javax.servlet.http.HttpSession;
import itso.bank.model.Customer;
import itso.bank.model.Account;
import itso.bank.facade.Banking;

Next, change the doGet and doPost methods’ body to look like this:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}

Chapter 7. Developing Web applications 207


public void doPost(HttpServletReq request, HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}

As you can see, both methods call a third method, called performTask. Because
both doGet and doPost are read methods, and the Java API for handling the
request parameters is the same no matter the request type, this works fine.

Finally, you need to code the performTask method (see Example 7-1).

Example 7-1 Servlet performTask method


public void performTask(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// Parameters
// Get input parameter and keep it on the HTTP session
String customerNumber = req.getParameter("customerNumber");
HttpSession session = req.getSession();

if (customerNumber == null)
customerNumber =
(String) session.getAttribute("customerNumber");
else
session.setAttribute("customerNumber", customerNumber);

// Control logic - Create the new banking facade


Banking banking = new Banking();

// Retrieve customer and related accounts


Customer customer = banking.getCustomer(customerNumber);
Account[] accounts = banking.getAccounts(customerNumber);

// Response - Set the request attributes for future rendering


req.setAttribute("customer", customer);
req.setAttribute("accounts", accounts);

// Call the presentation renderer


getServletContext().getRequestDispatcher("listAccounts.jsp")
.forward(req, resp);
} catch (Exception e) {
req.setAttribute("message", e.getMessage());
req.setAttribute("forward", "index.html");
getServletContext().getRequestDispatcher("showException.jsp")
.forward(req, resp);
}
}

208 WebSphere Studio Application Developer Version 5 Programming Guide


The performTask method is divided into three main sections:
򐂰 The first section deals with the HTTP parameters. This servlet expects to
either receive a parameter called customerNumber (underlined) or none at all.
If the parameter is passed, we store it in the HTTP session for future use. If it
is not passed, we look for it in the HTTP session, because it might have been
stored there earlier. The parameter name equals the text field name in the
index.html page.
򐂰 The second section deals with the control logic. We create a new Banking
facade and use it to get the customer object and the array of accounts for that
customer.
򐂰 Finally, the third and last section sees that the presentation renderer
(listAccounts.jsp) gets the parameters it requires to perform its job
(customer and accounts, both underlined). The parameters are passed in the
request context, because they are no longer needed once this request is
answered.

We could have written the presentation code in the servlet if we wanted to do so.
Instead, we chose to use JSPs, which were specially designed for that purpose.
Servlets do not make very good Web presentation renderers, because writing
HTML code in Java is cumbersome.

Save your changes and close the source editor.

Linking an HTML page to a servlet


Before we write our JSP code, we complete the index.html file by linking it to the
ListAccounts servlet that we have just created. Open the index.html file and
switch to the Design view. Select the form element and open its properties view
by selecting Properties on the form’s context menu.

The form’s action should be the ListAccounts servlet. But you do not have to
type that in yourself. Instead, click ... -> Servlet and select the ListAccounts
servlet from the pop-up list. Remove the Web application context root:
From: /ItsoProGuideBasicWeb/ListAccounts <=== absolute URL
To: ListAccounts <=== relative URL

Finally, make sure that the Post method is selected. The Attributes view is shown
in Figure 7-28.

Chapter 7. Developing Web applications 209


select servlet

Figure 7-28 Form element attributes

You could have added the link to the servlet in the Source view as the action
attribute of the form:
<FORM action="ListAccounts" method="post">

Save the page and close the editor.

Links view
Select index.html file and the Links view. You should see the files (CSS file and
image) and links (servlet, URL) that are used by the HTML file (Figure 7-29).

servlet

Figure 7-29 Links view

Working with JSPs


Now that we have managed to build our first static page and our first servlet
controller, it is time to complete the cycle by writing our first JSP page:
listAccounts.jsp. This page is responsible for presenting the list of accounts
belonging to the given user.

210 WebSphere Studio Application Developer Version 5 Programming Guide


When an application server such as WebSphere Application Server processes a
request that involves a JSP file, it performs the following actions:
򐂰 Compiles the JSP file into executable Java code, if needed.
If a previously compiled JSP class file can be found, and the source file is
older than the compiled file, the application server does not have to recompile
the JSP file.
򐂰 Instantiates the JSP servlet, if needed.
Because JSPs are just like any other servlet, there will probably be just one
instance of each type in memory at the same time (unless they implement the
javax.servlet.SingleThreadModel interface). So, if the JSP has already
been processed in a previous request, chances are that resulting servlet
object is still in memory and can be reused.
򐂰 Sends the request to the JSP servlet for processing.
򐂰 The JSP servlet renders the HTML result which is sent back to the Web client
for output.

JSP files are edited in Page Designer, the very same editor you used to edit the
HTML page. When working with a JSP page, though, Page Designer has
additional elements (JSP tags) that can be used, such as JavaBean references,
expressions, and scriptlets containing Java code.

Creating a JSP
To create a JSP file, select the Web Content folder and select New -> JSP File
to open the new JSP file wizard (Figure 7-30).
򐂰 Because you had the Web Content folder selected when you started the
wizard, the folder field comes filled in for you. Type the file name
(listAccounts.jsp) into the appropriate field. You do not have to type the file
extension, as it will be automatically added for you.
򐂰 We will be using HTML as the markup language, so leave it as is. The options
are the same as when you created a new HTML page.
򐂰 If you select the Create as JSP Fragment check box, this file will be created
as a fragment that can be added to another JSP file. Other JSP files can
include JSP fragments using a JSP include directive. Creating a fragment
causes the resulting file to end in a .jspf or .jsf extension. You will not be
prompted for DOCTYPE information, because a fragment cannot stand alone
as a Web page, and it would invalidate any JSP file that included it.
򐂰 We want the wizard to generate code without using any special models, so let
the model field be set to none. Your other option would be to generate a
Struts JSP page, but that will be left for Chapter 10, “Developing Struts
applications” on page 293.

Chapter 7. Developing Web applications 211


Figure 7-30 New JSP file wizard (page 1)

Click Next to continue to the second page (Figure 7-31).

Figure 7-31 New JSP file wizard (page 2)

212 WebSphere Studio Application Developer Version 5 Programming Guide


The wizard’s second page lets you add tag libraries from a variety of sources. We
do not have any tag libraries on our example, but the steps to add a tag library
would be:
򐂰 Click Add Tag Library to locate a tag library directive (TLD) file or a JAR file
that contains a TLD file. TLD URIs can be located in one of the following
places:
– As a taglibname.tld file in the WEB-INF directory (most common).
– Within a JAR file located in the project lib directory that contains
\WEB-INF\taglibname.tld.
– Within a JAR file external to the project.
– In a loose .tld anywhere in the project.
򐂰 Taglib files are referenced in the Web deployment descriptor (web.xml) file on
the References page.
򐂰 In the Select a tag library dialog, either select one of the available tag
libraries, or click Import to locate and add a tag library to the list, and then
select it. The dialog will automatically populate the informational fields that
describe the tag library and its contents. You must specify a Prefix value. Click
OK to add the tag library.
򐂰 As you add tag libraries, the Available Custom Tags list box displays the
declaration of the tag along with the tag library directive. If the selected TLD
file is not registered in the web.xml file, it will be added automatically.

Note: We will work with tag libraries in Chapter 10, “Developing Struts
applications” on page 293.

We will skip working with tag libraries for now, so just click Next to proceed to the
third page (Figure 7-32).

Chapter 7. Developing Web applications 213


Figure 7-32 New JSP file wizard (page 3)

This page lets you supply page directive information for the JSP file:
򐂰 It allows you to choose the scripting language (Java is the preferred language,
but you can also choose Javascript if you would like), set the imported types
and packages, and configure the set of directive attributes.
If you do not select an attribute’s check box, it means that it will be assigned
the default value, which you can tell by checking the disabled radio group.
򐂰 First of all, add the packages java.util and itso.bank.model to the imports
list by clicking Import Package once for each package.
򐂰 Then, because we do not need a session variable in our JSP page, check the
Create Session Variable box and set its value to false.
Note that the default for a session variable in a JSP is true.

Click Next to continue to the next page (Figure 7-33).

214 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-33 New JSP file wizard (page 4)

The wizard’s fourth page lets you supply the JSP encoding, DOCTYPE, and style
sheet information, just like when we created our HTML page.

Leave the options to their default values and click Next to continue to the last
page (Figure 7-34).

Chapter 7. Developing Web applications 215


Figure 7-34 New JSP file wizard (page 5)

This last page lets you select which JSP method stubs you would like the wizard
to generate, and whether or not to add deployment information to the Web
project's deployment descriptor file.
򐂰 Because we do not need to add behavior to the life-cycle methods, leave both
init and destroy unchecked.
򐂰 Finally, if you select the Add to web.xml check box, the JSP file, along with its
display name, and any URL mappings and initialization parameters
associated with the JSP file, will be automatically included in the Web
project’s deployment descriptor file. We do not want to do that because our
JSP’s client is the ListAccounts servlet, and not an external Web client.

Note: The File Name value provided in the first page of the wizard is
automatically mapped to the Servlet Name value on this page, as well the
URL Pattern mappings. These mappings are not updated if you go back and
change the original value in the File Name field.

Click Finish to complete the wizard and create the file. The JSP file is added to
the Web Content folder and opened for editing.

216 WebSphere Studio Application Developer Version 5 Programming Guide


Note the additional JSP menu item that now can be found in Page Designer’s tool
bar. It helps you with many common tasks when editing JSPs, such as:
򐂰 Declaring and accessing JavaBeans and their properties
򐂰 Inserting declarations, expressions, and scriptlets
򐂰 Inserting forwards and includes
򐂰 Using plug-ins
򐂰 Working with custom tags

Editing a JSP file


In Application Developer you can create JSPs from scratch or use the JSP
wizards to generate code skeletons and then edit them to fit your particular
needs. For now, we do not use the more complex wizards, but you will be able to
experience them later in the book.

You can customize the recently created JSP file by adding your own static
content, just like you would to a regular HTML file. Along with that, you can use
the standard JSP declarations, scriptlets, expressions, and tags, or any other
custom tag that you might have retrieved from the Internet or developed yourself.

Switch to the Design view if you are not already at it. Clear the default text
paragraph that the wizard generated, just like you did with the HTML file. Then
set the page title to RedBank: Customer's Accounts.

Also, just like you did before, add the two column table to hold the bank’s logo.
The left column should contain the RedBank string (with the first three characters
in red). The logo image should be placed on the column to the right.

On a paragraph following the table, enter Someone's Accounts (including the


quote). This paragraph should be formatted as heading 2.

Insert an HTML form right after the heading 2. The form’s action should point to
the AccountDetails servlet, and should be an HTTP post. Configure these
attributes just like we did with the index page (“Linking an HTML page to a
servlet” on page 209).

The form should contain the following elements:


򐂰 A text string reading Please, select the account you would like to work with:,
followed by two line breaks.
򐂰 A list box named accountList (Insert -> Form and Input Fields -> List Box,
enter 3 the number of rows) followed by another two line breaks.
򐂰 A Submit button labeled Submit, followed by a white space.
򐂰 A general button labeled Cancel (Insert -> Form and Input Fields -> Reset
Button).

Chapter 7. Developing Web applications 217


Using JavaScript
When the Cancel button is pressed, we want the browser to send an HTTP get
request to the InvalidateSession servlet. To configure this behavior, we need to
write a little script in JavaScript. Select the button and switch to the Source view.
Your cursor should be now right in front of the input tag that defines the cancel
button:
<INPUT type="button" value="Cancel">

Change this tag so that it looks like this:


<INPUT type="button" value="Cancel" onclick="cancel()">

We are telling the browser to call the cancel function (to be defined in a moment)
when the button notifies the click event.

Find the </HEAD> tag and place your cursor right before. Insert a line break so
that the source will look nice, and manually enter the following script:
<SCRIPT language="JavaScript">
function cancel()
{
window.navigate("InvalidateSession");
}
</SCRIPT>
</HEAD>

As it is the case with source code in other languages, you can also use the code
assist feature to suggest options or complete your JavaScript code.

Inserting a link
Finally, we will create the HTML link to the Redbooks Web site. Switch back to
the Design view and type For more information on ITSO and RedBooks, please
visit our Internet site at the very end of the document. Just like you did before,
select the string Internet site and select Insert -> Link. On the URL field, enter
http://www.redbooks.ibm.com.

The resulting page’s Design view should be looking like Figure 7-35.

218 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-35 listAccounts.jsp file with just static contents

Up to this point we have just inserted static content into the JSP page, nothing
different from what you did when you edited the index.html file. Now it is time for
us to insert the dynamic elements into the page.

First, we need to declare the two JavaBean parameters that will be sent by the
controller servlet (ListAccounts), so that we can use them later on the page.
Their IDs are customer and accounts (see Example 7-1 on page 208).

While in the Design view, place you cursor before the table, or press Ctrl-Home.
Select JSP -> Insert Bean. The dialog in Figure 7-36 is displayed.

Figure 7-36 Insert JSP Bean wizard

Chapter 7. Developing Web applications 219


The ID field is the key which uniquely identifies the bean at the specified scope.
The pull-down menu contains recently used IDs. Because you have not used any
IDs so far, simply type customer.

The customer bean will be passed as a parameter to this page in the request
scope and not as a serialized bean from a file. Select Bean for the type and
Request for the scope.

We do not have to specify the bean’s class, because we do not want an object to
be created from scratch if it is not found in the specified scope. Leave the class
field blank and enter itso.bank.model.Customer in the type field. You can click
Browse to find the bean’s type instead of having to type it.

Click OK to complete the wizard. The following code is added to your JSP page,
right below the <BODY> tag:
<jsp:useBean id="customer" type="itso.bank.model.Customer"
scope="request">
</jsp:useBean>

Tip: An alternative way to add a JavaBean to a JSP page is to find it in the


J2EE Navigator view and drag and drop it on the page. The <jsp:usebean> tag
is inserted for you, but you have to add the id and scope attributes and change
the class attribute to type.

Repeat the above process for the accounts bean. The resulting JSP tag should
be:
<jsp:useBean id="accounts" type="itso.bank.model.Account[]"
scope="request"></jsp:useBean>

The <useBean> tag for an array results in a warning. To remove the warning we
can declare the accounts variable directly. Replace the <useBean> tag with this
code:
<% Account[] accounts = (Account[])request.getAttribute("accounts"); %>

Now that both beans have been declared, we can use them to display dynamic
data to the user. We want to substitute the Someone string for the customer’s
name.

Select the string in the heading 2 paragraph and simply delete it. With the cursor
positioned right before the apostrophe, select JSP -> Insert Get Property and the
dialog shown in Figure 7-37 appears.

220 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-37 Insert a JavaBean property

This dialog presents you with the list of all available beans to be used in the point
of insertion. Find the customer bean, expand it by clicking the plus sign, and
select the firstName property. The rest of the fields should automatically be filled
in for you. Click OK to close the dialog.

Now insert a blank space and repeat the above process for the customer’s last
name. The resulting JSP code added should look like this:
<H2><jsp:getProperty name="customer" property="firstName" />
<jsp:getProperty name="customer" property="lastName" />'s Accounts</H2>

Because this JSP displays a list of accounts for a customer (a customer may
have many accounts), it has to loop through the resulting collection of accounts.
To support this without using external taglibs, you have to insert a scriptlet with
Java code.

Note: Ideally, a JSP page would have no Java code at all, just JSP tags. The
intent of this scripting language is to enable Web designers that might not be
proficient in the Java language to write Web presentation to Java applications.
To a certain extent, this can be achieved without any further complications. So
far we have already used JSP tags but have written no Java code whatsoever.
In certain situations, though, as with loops, we cannot skip using Java
scriptlets unless we choose to use external taglibs, like the Java Standard Tag
Library (JSTL).

Chapter 7. Developing Web applications 221


Switch to the Source view and position your cursor within the <SELECT> tag body.
Select JSP -> Insert Scriptlet. Page Designer will insert the starting and ending
scriptlet tag for you. Enter the following code in the scriptlet body:
<SELECT size="3" name="accountList">
<%
for (int i=0; i < accounts.length; i++) {
Account account = accounts[i];
%>
</SELECT>

Note that the Java code has opened a loop block which but not closed it. We will
look into that in a short while. What we essentially did here was to get an iterator
for the accounts collection, previously declared, start a WHILE loop to iterate
through the account objects in that collection, and finally select the current
account object and assign it to the account variable.

We want this current account to show up as an option in the list box. After the
scriptlet but still within the select body, insert the following HTML tag:
<OPTION value="<%=account.getId()%>"><%=account.getId()%></OPTION>

Note that in the middle of the HTML code we put two identical JSP expressions.
These expressions will be substituted by the account ID at runtime, which is
essential what will be displayed to the user.

Finally, complete the loop by inserting another scriptlet with the loop’s closing
curly braces. The final code should look like this:
<SELECT size="2" name="accountList">
<%
for (int i=0; i < accounts.length; i++) {
Account account = accounts[i];
%>
<OPTION value="<%=account.getId()%>"><%=account.getId()%></OPTION>
<% } %>
</SELECT>

This completes the code for the JSP. You can test the visual aspects of it by
selecting the preview view Page Designer. Figure 7-38 shows the finished JSP
design and preview.

222 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-38 JSP design and preview

The JSP tags are shown as icon boxes. Double-click a JSP tag icon and view the
definition in the Attributes view, or view the content in the Source view.

You can see that the JSP tags are not displayed in the preview pane. Neither are
their results, of course. They can only be obtained by a J2EE application server,
at run time.

Make sure you are at either the design or the Source view and save your work.
Close the source editor.

Chapter 7. Developing Web applications 223


Creating a server for testing
To test a Web application we require a server. Because our project is a J2EE 1.3
project we require a WebSphere Version 5 server (or a Tomcat server).

A server can be created automatically or manually:


򐂰 For automatic server creation, select the ItsoProGuideBasicWeb project and
Run on Server (context). The dialog shown in Figure 7-39 is displayed.

Figure 7-39 Server selection dialog

The default selection is correct and clicking OK defines a server project


named Servers, a server named WebSphere v5.0 Test Environment, and
starts the server. The drawback of this method is that we cannot select a
name for the server and we cannot tailor the server before it starts.
Stop the server, delete it from the Server Configuration view and delete the
Servers project. We want to create a server manually.
򐂰 For manual creation of a server, open the Server perspective and select New
-> Server and Server Configuration. In the dialog (Figure 7-40) enter the
name of the server (for example, ItsoServer), set the folder as
ItsoProGuideServers (this creates the ItsoProGuideServers project), and
select WebSphere version 5.0 -> Test Environment.
Click Next and confirm that you want to create the ItsoProGuideServers
project.
Accept the default port of 9080 and click Finish.
Select the ItsoServer in the Server Configuration view and Add ->
ItsoProGuide (context). This adds the EAR project (with the Web module) to
the server.
The ItsoServer server also appears in the Servers view, from where it can be
started and stopped.

224 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-40 Creating a WebSphere test server

Testing the application


Start the ItsoServer server.

While the server is starting, you can check its initialization message log on the
Console view. If the view is not visible, select Window -> Show View -> Console
from the menu bar. You will know that the server is ready when you read the
message “Server server1 open for e-business“.

Select the ItsoProGuideBasicWeb project and Run on Server (context). When you
run a Web project itself, instead of a single HTML file, then the welcome page is
displayed. Welcome pages are defined in the deployment descriptor (web.xml) on
the Pages page. Usually the index.html file is the first in the list.

Chapter 7. Developing Web applications 225


If you are prompted to select a server, select the ItsoServer and also select Set
server as project default (do not prompt). This stores a server as the default in
the properties of the Web project., where it can be changed at any time.

The Web browser window opens and displays the index page (Figure 7-2 on
page 182). In the customer ID field, type any number from 101 to 106 and submit
the form. The resulting page (Figure 7-3 on page 182) should display the
selected customer’s account list.

Working with filters


Servlet filtering is a new addition to the Servlet 2.3 API. It provides a new type of
reusable object called a filter, that can transform requests and responses on the
fly. You can chain filters together so that a group of filters can act on the input and
output of a specified resource or group of resources.

Filters typically include logging filters, image conversion filters, encryption filters,
and MIME type filters. Although filters are not servlets, their life cycle is very
similar.

Filters are handled in the following manner:


򐂰 The Web container determines which filters must be constructed for the Web
application, before a request causes a Web resource to be accessed.
򐂰 The container instantiates and initializes each filter (if this was not previously
done) by calling the filter’s init method.
򐂰 When the container receives a request for a Web resource, it creates a filter
chain containing the filters associated with the resource.
򐂰 The container invokes the chain’s doFilter method, which in turn invokes
each filter’s doFilter method. A filter’s doFilter method typically:
– Pre-processes the request object, or wraps it with a customized
implementation of ServletRequest or HttpServletRequest to modify
request headers or data.
– Pre-processes the response object, or wraps it with a customized
implementation of ServletResponse or HttpServletResponse to modify
response headers or data.
– Typically invokes the next filter on the chain by calling the chain’s doFilter
method, but may alternatively block the chain. After this step, the filter may
examine the response’s headers.
– Does additional post-processing to the request and response objects.

226 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Finally, after all the filters on the chain have been invoked, the filter chain calls
the originally requested resource.
򐂰 Before a filter can be removed from service, the container must call its
destroy method.

Figure 7-41 shows how the chaining of filters work:

Web Container

Filter 1 Filter 2
doFilter doFilter Resource

doFilter Filter Chain

Figure 7-41 Filter chaining

Creating a filter in Application Developer


We implement a simple filter that audits all the banking transactions by writing an
audit trail to a file. This filter in invoked before the PerformTransaction servlet
gets control.

Note: This is a simple example that uses a file for auditing. Such a design
should not be used in a real application.

To create a new filter in Application Developer, open the J2EE Navigator view of
the ItsoProGuideBasicWeb project.

Create a new package (under Java Source) names itso.basicweb.filter.

Select the itso.basicweb.filter package and New -> Filter from the context
menu to start the New Filter wizard (Figure 7-42).

Chapter 7. Developing Web applications 227


Figure 7-42 Creating a new filter (page 1)

Make sure the correct package (itso.basicweb.filter) is selected.

In the Filter Name field, type TransactionAuditingFilter. Our filter will audit
every transaction that is performed with the bank accounts, logging the
transaction type, time stamp, and parameters, as well as the client’s hostname
and IP address.

Click Next to proceed to the second page (Figure 7-43).

The wizard’s second page lets you select method stubs and deployment
descriptor information.

228 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-43 Creating a new filter (page 2)

The filter has to be added to the Web deployment descriptor. Configure the
initialization parameter by clicking the respective Add. Enter pathname for the
parameter name and c:/transactionAudit.txt for its value.

Finally, we have to set with which servlets this filter should be associated. Click
the respective Add to open the Choose a Servlet dialog. Select
PerformTransaction and click OK.

Click Finish to complete the wizard. The TransactionAuditingFilter.java file is


opened for editing.

Note: To change the filter’s servlet associations or initialization parameters,


open the Web deployment descriptor on the Filters page.

Chapter 7. Developing Web applications 229


Editing the filter
Switch to the Java editor opened on the TransactionAuditingFilter.java file.
The source code of the sample filter is available in:
\sg246957\sampcode\dev-web\filter\TransactionAuditingFilter.java

Add an import statement and declare the following instance variable:


import java.io.RandomAccessFile;
private RandomAccessFile auditFile;

The auditFile property holds a reference to the audit file. Generate its getter
and setter methods by selecting the field in the Outline view and Generate Getter
and Setter from its context menu. Change the generated method access
modifiers from public to private (Figure 7-44):

private RandomAccessFile getAuditFile() {


return auditFile;
}

private void setAuditFile(RandomAccessFile auditFile) {


this.auditFile = auditFile;
}

Figure 7-44 Getter and setter methods for the auditFile property

The audit file should be opened upon the filter initialization. Edit the init method
as shown in Figure 7-45.

public void init(FilterConfig config) throws ServletException {


String pathname = config.getInitParameter("pathname");
try {
setAuditFile(new RandomAccessFile(pathname, "rw"));
getAuditFile().seek(getAuditFile().length());
} catch (IOException e) {
e.printStackTrace());
}
}

Figure 7-45 TransactionAuditingFilter init method

After opening the file for both read and write access, we move the file pointer to
the end, so that the file can be appended instead of overwritten.

Because we opened the file in the init method, we have to close it in the
destroy method (Figure 7-46).

230 WebSphere Studio Application Developer Version 5 Programming Guide


public void destroy() {
try {
getAuditFile().close();
} catch (IOException e) {
e.printStackTrace();
}
}

Figure 7-46 TransactionAuditingFilter destroy method

Finally, edit the filter’s doFilter method as shown in Figure 7-47.

public void doFilter(ServletRequest request, ServletResponse response,


FilterChain chain) throws ServletException, IOException {
String protocol = req.getProtocol();
String address = req.getRemoteAddr();
String host = req.getRemoteHost();
String transaction = req.getParameter("transaction");
String parameters = "";
java.util.Enumeration parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()) {
String name = parameterNames.nextElement().toString();
String value = req.getParameter(name);
parameters += name + "=" + value + ", ";
}
parameters = parameters.substring(0, parameters.length() - 2);
String output = "- " + transaction +
" being performed from " + host + " (" + address +
") using " + protocol + " at " + new java.util.Date() +
" Parameters: " + parameters + "\r\n";

synchronized (getAuditFile()) {
getAuditFile().writeBytes(output);
}
System.out.println(output);

chain.doFilter(request, response);
}

Figure 7-47 TransactionAuditingFilter doFilter method

Save your changes and close the editor. The next time you perform a transaction
with any of the accounts, the audit file c:\transactionAudit.txt is created and
populated. See Figure 7-54 on page 236 for sample output of the filter (and the
listener that we create next).

Chapter 7. Developing Web applications 231


Working with listeners
Life-cycle listeners, now part of the Servlet API, enable you to be notified when
servlet contexts and HTTP sessions are created, destroyed or modified. They
give the application developer greater control over interactions with
ServletContext and HttpSession objects. Servlet context listeners manage
resources at an application level. Session listeners manage resources
associated with a particular client’s HTTP session.

Listeners are available for life-cycle events and for attribute modification events.
The listener developer creates a class that implements the interface
corresponding to the desired listener functionality:
򐂰 javax.servlet.ServletContextListener
Receives javax.servlet.ServletContextEvent events that notify that a
servlet context has just been created or is about to be destroyed.
򐂰 javax.servlet.ServletContextAttributeListener
Receives javax.servlet.ServletContextAttributeEvent events that notify
that an attribute in the servlet context has been added, removed, or modified.
򐂰 javax.servlet.http.HttpSessionListener
Receives javax.servlet.http.HttpSessionEvent events that notify that an
HTTP session object has just been created or is about to be destroyed.
򐂰 javax.servlet.http.HttpSessionAttributeListener
Receives javax.servlet.http.HttpSessionBindingEvent events that notify
that an attribute in an HTTP session has been added, removed, or modified.

Note that the same listener may implement any combination of the above
interfaces. At application startup time, the container uses introspection to create
an instance of the listener class and registers it with the appropriate event
generators.

As an example, we will create a listener that implements both the


HttpSessionListener and HttpSessionAttributeListener interfaces. It will be
called HttpSessionInspector and will print to the standard output detailed HTTP
session event notifications that can be used by the developer to determine:
򐂰 When HTTP sessions are created and destroyed.
򐂰 The size of the HTTP session objects at creation and destruction.
򐂰 When HTTP session attributes are added, removed or modified, and their
sizes.

232 WebSphere Studio Application Developer Version 5 Programming Guide


Creating a listener in Application Developer
To create a listener in Application Developer, open the J2EE Navigator view of
the ItsoProGuideBasicWeb project.

Create a new package (under Java Source) names itso.basicweb.listener.

Select the itso.basicweb.listener package under the Java Source folder and
then select New -> Life-cycle Listener from the context menu to start the New
Life-cycle Listener wizard (Figure 7-48):

Figure 7-48 Creating a new life-cycle listener (page 1)

Make sure the correct package (itso.basicweb.listener) is selected.

In the Listener Name field, type HttpSessionInspector. In the Listener Types


field, select both Http Session Listener and Http Session Attribute Listener. Click
Next to continue to the second page (Figure 7-49):

Chapter 7. Developing Web applications 233


Figure 7-49 Creating a new life-cycle listener (page 2)

All the default values are suitable, just click Finish to complete the wizard. The
listener is created and added to the Web deployment descriptor. A Java editor is
also opened on the listener class Java file.

Editing the listener


Switch to the Java editor that was opened on the HttpSessionInspector.java
file. The source code of the sample listener is available in:
\sg246957\sampcode\dev-web\listener\HttpSessionInspector.java

The first method we will enter calculates an object’s size when serialized. This
method is useful for determining how much space a session or one of its
attributes would take if they would be serialized to a database. Add the size
method as shown in Figure 7-50.

234 WebSphere Studio Application Developer Version 5 Programming Guide


private int size (Object anObject) {
ByteArrayOutputStream array = new ByteArrayOutputStream ();
try {
(new ObjectOutputStream (array)).writeObject(anObject);
return array.size();
} catch (IOException e) {
return -1;
}
}

Figure 7-50 Listener helper method: size

The next helper method that has to be created is called report. It handles the
printing of messages to the standard output (Figure 7-51).

private void report (String reason, HttpSession session, Object value,) {


if (value == null)
System.out.println (reason + ": session #" + session.hashCode() + "
size: " + size(session));
else
System.out.println (reason + ": session #" + session.hashCode() + "
size: " + size(session) + " Attribute size: " + size(value));
}

Figure 7-51 Listener helper method: report

Now enter the life-cycle methods for the HttpSessionListener interface


(Figure 7-52).

public void sessionCreated(HttpSessionEvent arg0) {


report ("Session created", arg0.getSession(), null);
}

public void sessionDestroyed(HttpSessionEvent arg0) {


report ("Session destroyed", arg0.getSession(), null);
}

Figure 7-52 Listener implementation for the HttpSessionListener interface

Finally, enter the methods for the HttpSessionAttributeListener interface


(Figure 7-53).

Chapter 7. Developing Web applications 235


public void attributeRemoved(HttpSessionBindingEvent arg0) {
report ("Attribute " + arg0.getName() + " removed",
arg0.getSession(), arg0.getValue());
}

public void attributeAdded(HttpSessionBindingEvent arg0) {


report ("Attribute " + arg0.getName() + " added",
arg0.getSession(), arg0.getValue());
}

public void attributeReplaced(HttpSessionBindingEvent arg0) {


report ("Attribute " + arg0.getName() + " replaced",
arg0.getSession(), arg0.getValue());
}

Figure 7-53 Listener implementation of the HttpSessionAttributeListener interface

To get rid of all the errors from undefined classes, select Source -> Organize
Imports and the required import statements are added to the code.

Save your changes and close the editor. Run the application to see the results of
your work. The listener’s messages should show up on the Console view.

Figure 7-54 contains an extract from the Console showing the output of both the
filter and the listener.

Session created: session #1152644455 size: 226


Attribute customerNumber added: session #1152644455 size: 249
Attribute size: 10
Attribute accountNumber added: session #1152644455 size: 276
Attribute size: 15
- Deposit being performed from 127.0.0.1 (127.0.0.1) using HTTP/1.1 at
Sun Apr 06 15:23:02 PDT 2003 Parameters: amount=100, transaction=Deposit
- Transfer being performed from 127.0.0.1 (127.0.0.1) using HTTP/1.1 at
Sun Apr 06 15:23:14 PDT 2003 Parameters: destinationAccount=106-6002,
amount=200, transaction=Transfer
Attribute accountNumber replaced: session #1152644455 size: 276
Attribute size: 15
- ListTransactions being performed from 127.0.0.1 (127.0.0.1) using
HTTP/1.1 at Sun Apr 06 15:23:24 PDT 2003 Parameters:
transaction=ListTransactions
Invalidating session
Session destroyed: session #1152644455 size: 276

Figure 7-54 Sample output of filter and listener

236 WebSphere Studio Application Developer Version 5 Programming Guide


Creating Web pages from a JavaBean
Application Developer provides support for generating a working set of pages
and Java classes from a simple JavaBean or a set of JavaBeans. A JavaBean, in
this context, is any Java class that has a public constructor and public getters and
setters for its properties.

Important: The Java classes you select must have zero-argument


constructors, as per the JavaBeans specification, or the resulting generated
code will fail to work correctly.

As we have seen before, JavaBeans usually either implement or represent the


business model tier. The JavaBean wizard will generate the view and control
layers to work with the JavaBeans you select, in accordance to the MVC
architectural pattern.

The JavaBean Web Pages Wizard supports the following activity models:
򐂰 Set bean properties—Create an input form that collects input from users and
stores the resulting data within the properties of a Java bean.
򐂰 Retrieve bean properties—Create a result form that displays a bean's current
property values.
򐂰 Execute a bean's method(s)—Run any number of methods from a bean by
submitting an input form.
򐂰 Execute a bean's method(s) with parameters—Create an input form that
collects data from users, and use this data as input to a bean's methods.
򐂰 Display a method's result—Create a result page that displays the return value
of a method.
򐂰 Combination—Create a set of pages that include any combination of the
above models.

For the sole purpose of demonstrating the wizard, we are going to redo the same
two pages and one servlet we did before (index.html, listAccounts.jsp and
ListAccounts). You will then be able to compare the two approaches.

We create the application in the ItsoProGuideBasicWeb project.

To better organize your code, create a new folder under Web Content named jbwp
(as in JavaBean Web pages).

Chapter 7. Developing Web applications 237


Select the newly created jbwp folder and select File -> New -> Other from the
menu bar. Select the Web -> Java Bean Web Pages option and click Next to
continue. This opens the wizard’s first page, as shown in Figure 7-55.

Figure 7-55 JavaBean Web pages wizard: start

򐂰 The Destination folder field should have come up already filled in, since you
had the folder selected. In the Java package field, type itso.jbwp. We do not
want the code mixed with the old application.
򐂰 The model selection drop-down currently only has one entry: View Bean. This
code generation model uses view helpers, which are Java wrapper classes
that manage all the model interaction.
򐂰 The rest of the dialog is simply informative. Selecting the Files field values
displays a description.

238 WebSphere Studio Application Developer Version 5 Programming Guide


Click Next to proceed to the next page (Figure 7-56).

Figure 7-56 JavaBean Web pages wizard: select bean and methods

򐂰 The second step consists of selecting the JavaBean that will act as the model
for the generated pages, and selecting which of its properties and methods
the pages should be created for.
򐂰 Click Browse to bring up the Choose Java Bean dialog. Type Banking in the
Choose Java Bean field. The dialog presents you with the matching types,
but the list is probably going to be limited to just one occurrence. Select the
appropriate type (Banking) and package (itso.bank.facade) and click OK.
򐂰 The wizard automatically introspects the bean and presents you with the list
of available properties and methods. You do not have to click Introspect
unless you type in the class name directly.
򐂰 Select the getCustomer and getAccounts methods. We only want to retrieve
the customer and its accounts.

Chapter 7. Developing Web applications 239


Click Next to continue to the next page (Figure 7-57).

Figure 7-57 JavaBean Web pages wizard: controller, view beans

򐂰 The third wizard’s page lets you select the style sheets you want associated
with the generated pages. By default, Web Content\theme\Master.css comes
selected, and that is enough for us. You may add, remove, or change the
priority of style sheets by clicking Add, Remove, and the arrow buttons,
respectively.
򐂰 Here you may also select whether or not the wizard should link the given error
page to the generated pages. Note that the wizard will not generate the error
page. It will just declare it in the generated pages’ page directive for you. We
do not need that behavior.
򐂰 The default setting for storing the results is Request, the option that you
should select for this example. Selecting Request means that the method
results will only be available for the duration of the HTTP request. If you want
the results to be preserved for the lifetime of the user session, choose the
Session option. If the results occupy too much memory, this may not be the
best approach.
򐂰 You can then choose how you would like the wizard to generate control layer
code for you. You may want to generate a new controller servlet, to reuse an
existing one, or not to use a controller servlet at all (in which case the wizard
would generate view and control code in the JSPs). Select the Create a new
Front Controller option.

240 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 While you are still on this page, you can choose to have the wizard create a
view bean wrapper for you. This wrapper class allows you to format the result
data for display. If you deselect this option, the wizard accesses data using
the previously chosen bean directly. For our simple example, we do not want
a wrapper.

Click Next to proceed to the fourth page (Figure 7-58).

Figure 7-58 JavaBean Web pages wizard: input page

This page lets you see and configure how the generated input HTML file will look
like:
򐂰 Select the getCustomer method and clear its Label property.
򐂰 Select the customerID item under the getCustomer method and configure its
label to Enter a customer number:
򐂰 Deselect the getAccounts method and customerID under it, we only want one
input field for the customer number.
򐂰 Select the Page tab and set the Page Title field to RedBank.

Chapter 7. Developing Web applications 241


Click Next to proceed to the fifth page (Figure 7-59).

Figure 7-59 JavaBean Web pages wizard: results page

Using this page you can determine and configure how the response JSP will
look:
򐂰 Use the arrows to move getAccounts under getCustomer (if the sequence is
reversed).
򐂰 Select the getCustomer method and clear its Label property.
򐂰 Select the getCustomer result (right under the getCustomer method) and set
its Label property to Customer:.
򐂰 Expand the getCustomer method and select both firstName and lastName
properties. Select each field and change the labels to First name: and Last
name:.
򐂰 Expand the getAccounts method, select it, and clear its label.
򐂰 Select the getAccounts under it and set its label to Accounts: and its layout
style to table (use the drop-down menu).

242 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 The getAccounts result is an array of Account objects. Expand the
getAccounts result.
򐂰 The properties of the Account class are now displayed under getAccounts.
Check the id and balance fields.
򐂰 Select the id and balance fields and change the labels to Account number and
Balance.
򐂰 Configure the page title to RedBank: Customer's Accounts.

Click Next to skip to the wizard’s last page (Figure 7-60).

Figure 7-60 JavaBean Web pages wizard (page 6)

Finally, you have to configure a prefix to be appended before every generated


resource. Simply type ListAccounts and click Finish to complete the wizard.

The following resources were generated:


򐂰 A ListAccountsInputForm.html file in the Web Content\jbwp folder.
򐂰 A ListAccountsResultsForm.jsp file in the Web Content\jbwp folder.
򐂰 A ListAccountsController servlet in the itso.jbwp package. This servlet has
also been registered in the Web module’s deployment descriptor.

Completing the code


Because we only generated one input field for the customer ID, the call to the
getAccounts method has no parameter. We have to add the parameter manually.

Open the ListAccountsResultsForm.jsp file and find the method calls. Change
the getAccounts call:
itso.bank.model.Customer methodResult0 = listAccountsBean.getCustomer
(new java.lang.String(request.getParameter

Chapter 7. Developing Web applications 243


("getCustomer_java_lang_String__customerID")));
itso.bank.model.Account[] methodResult1 = listAccountsBean.getAccounts
(new java.lang.String(request.getParameter
("getCustomer_java_lang_String__customerID")));

Tailoring the generated files


You could make the ListAccountsInputForm.html file look like the original
index.html file.

Rename
Note that if you rename the files, you have to configure the initialization
parameters of the controller servlet (ListAccountsController) in the web.xml
deployment descriptor.

Running the generated application


Select the ListAccountsInputForm.html file and Run on Server (context). The
application is published, the server is started, and the input page is displayed.

Enter a customer number (102) and click Submit. The name of the customer and
the accounts are displayed. A sample run is shown in Figure 7-61.

Figure 7-61 Sample JavaBean application run

244 WebSphere Studio Application Developer Version 5 Programming Guide


Summary
In this chapter we learned about Application Developer’s facilities for creating
static and dynamic Web applications. We created a Web project and imported
existing resources into it. We then created static HTML pages, a cascading style
sheet, servlets, JSPs, filters, and life-cycle listeners to complete the sample
RedBank application, based on the MVC architectural pattern.

We also used the JavaBean Web Pages Wizard to generate a Web application
from a JavaBean.

Chapter 7. Developing Web applications 245


246 WebSphere Studio Application Developer Version 5 Programming Guide
8

Chapter 8. Developing Web


applications with database
access
We have seen how to connect to databases and how to access them from a Java
application. Application Developer contains wizards to allow you to easily access
databases from a Web application. We now examine how to use those wizards,
and how to test the resulting application.

In this chapter, we go over the following topics:


򐂰 Accessing databases from a Web application
򐂰 Defining a data source in the server
򐂰 Testing the database application
򐂰 Accessing a database using DB Beans

© Copyright IBM Corp. 2003. All rights reserved. 247


Accessing databases from a Web application
There are a number of ways that you can access databases from a Web
application. You can write your own Java classes and access the database via
standard JDBC calls. Alternatively, Application Developer supplies a library of
database access beans called DB Beans. These can be used in a JSP through
the <useBean> tag and can also be accessed through a set of JSP tags supplied
in a tag library. An application using DB Beans or tags can be generated for you
by Application Developer using a wizard based on an SQL statement.

Which of these methods you choose depends on the nature of your application
and the complexity of your database access. From the perspective of separating
the layers of your application, using separate JavaBeans for the database access
may be more appropriate because you are not mixing presentation and database
logic in the JSP as you do when using DB Beans or JSP tags.

In the following sections we discuss the wizard that can be used to create a view
bean or a taglib application starting from an SQL statement. We then look a bit
more closely at the DB Beans classes and JSP tags.

Creating a Web project


In this section, we use a new ItsoProGuideDataBaseWeb project:
򐂰 Create a Web project named ItsoProGuideDataBaseWeb by following the
instructions in “Creating a Web project” on page 185.
򐂰 Use the existing ItsoProGuide enterprise application project and the default
context root.
򐂰 On the module dependencies page, select the ItsoProGuideJava.jar file and
click Finish.
򐂰 When prompted to repair the server configuration because a new project was
added to the EAR file, click OK (Figure 8-1).

Figure 8-1 Repair server configuration

248 WebSphere Studio Application Developer Version 5 Programming Guide


Generate Web pages from SQL queries
Application Developer provides a wizard to help you create a set of Web pages
and supporting Java classes starting from an existing or new SQL query. The
wizard generates the required HTML pages, JSPs, and Java classes to quickly
create a working skeleton application without you having to write any code. You
can then expand and modify the generated code to create the finished
application.

To start the wizard, click File -> New -> Other. In the New wizard, select Web in
the left pane and Database Web Pages in the right pane, then click Next.

The first page of the wizard is displayed (Figure 8-2).

Figure 8-2 Create Database Web Pages wizard: select model

The following fields are available on this page:


򐂰 Destination folder—Folder where the generated Web pages are stored.
򐂰 Java package—Package where Java classes are generated.
򐂰 SQL Statement Type—The type of action to perform on the database.

Chapter 8. Developing Web applications with database access 249


򐂰 Model—There are two types of models that you can use:
IBM Database Access Tag Library: Two choices of tag library models are
available: Select Statement and Master Details Pattern.
– The Select Statement generation model creates an input form and a result
table based on the given SQL query
– The Master Details Pattern produces a master results table as well as a
details page that displays more information on a selected row of the
master results table.
Both of these use JSP tag libraries to access the data. JSP tags are
discussed in more detail in “Accessing a database using JSP taglib” on
page 262.
IBM Database Access Java Beans - Master Details Pattern: This model
generates Web pages that access database information using IBM Data
Access Beans to separate the database interaction from the JSP page. For
this example we use this model.

Clicking Next brings up the second wizard page (Figure 8-3).

Figure 8-3 Create Database Web Pages wizard: select SQL statement

You have two choices: use an existing SQL statement, or build a new one:
򐂰 If you already have an existing SQL statement in the statement folder of a
database project, you can select it here and use that to generate the Web
pages.

250 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 If you deselect Use Existing SQL Statement and click Next, you are prompted
to build an SQL statement in the same way as described in “Creating SQL
statements” on page 165.

We select the ListCredits SQL statement that we built in “Using SQL Query
Builder” on page 171 and click Next.

Clicking Next displays the page where you decide how you want to access the
database when the generated application is run (Figure 8-4). You can choose to
use a direct connection or use a data source. For a discussion about these two
different ways of connecting, see “Data source versus direct connection” on
page 141.

Figure 8-4 Create Database Web Pages wizard: connection information

In this case we use the data source connection. We specify the JNDI name of the
data source, which in our case is jdbc/ejbbank.

On the next three wizard pages you can view and change the pages that will be
generated by the wizard.

The first page is the View Bean Data Page, where you can specify the style
sheet, error page, whether to store results in the session or request object, and
whether or not to create a Front Controller, use an existing one, or not use one at
all (Figure 8-5).

Chapter 8. Developing Web applications with database access 251


Figure 8-5 Create Database Web Pages wizard: View Bean Data Page

The Store results option determines where the results from the query should be
stored. You can choose to store them in the session, in which case they will be
available to other pages for the life of the session, or in the request. You should
be aware of potential memory issues if you choose to store a large result set in
the session.

The front controller option decides if a controller servlet is generated or reused.


The controller servlet uses initialization parameters that specify for each action
which JSP to call.

On the following page, you see the HTML input form (Figure 8-6).

252 WebSphere Studio Application Developer Version 5 Programming Guide


Last name

Figure 8-6 Create Database Web Pages wizard: design input form

Here you can make some changes to page and field properties. Notice that the
two input fields are automatically generated. This is where the :type and
:lastname host variable values will come from.

Select each host variable and change the label to the desired text, for example,
Transaction type and Last name.

Once this and the following pages have been generated, you can make further
changes using Page Designer.

The next page shows the master result page. The default is to use a table to
display the result rows from the query (Figure 8-7).

Chapter 8. Developing Web applications with database access 253


Figure 8-7 Create Database Web Pages wizard: design result form

Here you can change the heading of the columns and page properties. If you do
not want to show one or more of the fields retrieved from the query, you can
deselect them in the top left pane. Typically, you would only select a subset of
the fields for the master table.

To change the labels, select the item in the top left pane and make your changes
in the bottom left pane. Typically, you would change the headings of the table to
short descriptive names.

The next page shows the default form for showing details of a selected row in the
details view page (Figure 8-8). You can make the same type of changes here as
on the master table view page to improve the look of the page.

254 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 8-8 Create Database Web Pages wizard: design detail form

Finally, you can specify the default prefix for all generated objects (Figure 8-9).
Clicking Finish generates the Java classes and HTML/JSP pages.

Figure 8-9 Create database Web pages wizard: select prefix

Chapter 8. Developing Web applications with database access 255


Defining a data source in the server
Before we can test the application, we have to set up the data source in the
server. To use a data source, you have to configure the server to recognize it.
For our application, we have to register a data source for the EJBBANK database.

These steps assume that a WebSphere v5.0 Test Environment server has
already been created, as explained in “Creating a server for testing” on
page 224.

Open the Server perspective and edit the server configuration of the ItsoServer:
򐂰 Go to the Data source tab.
򐂰 Under Server Settings, select the Default DB2 JDBC Provider from the JDBC
provider list and click Add next to the data source list. The Create a Data
Source dialog is displayed (Figure 8-10).

Figure 8-10 Create a Data Source dialog

Select DB2 JDBC provider and make sure Version 5.0 data source is selected,
then click Next.

In the Modify Data Source window, as shown in Figure 8-11, enter EJBBANK as the
name and jdbc/ejbbank as the JNDI name. This name has to match the name
used in your application.

256 WebSphere Studio Application Developer Version 5 Programming Guide


Tip: The data source name and the JNDI name can be anything. We
recommend that you use the database name as the data source name and
jdbc/databasename as the JNDI name. See “Installing DB2 UDB” on page 786
for instructions on how to enable JDBC 2.0, which is required for data source
support.

Deselect Use this data source in container managed persistence (CMP). For now
we do not have any EJBs.

required for EJBs

Figure 8-11 Modify a Data Source

Click Next to continue to the next page of the wizard, as shown in Figure 8-12.
On this page, modify the databaseName field to be EJBBANK.

Chapter 8. Developing Web applications with database access 257


Figure 8-12 Create a Data Source - Specify database name

Select databaseName in the Resource Properties list, then enter EJBBANK in the
Value field. This is the only required property.

Click Finish and the data source is defined.

The Data source page of the server configuration is shown in Figure 8-13. Note
that you have to select a driver in the JDBC provider list to see the data sources
defined for that driver.

258 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 8-13 Server configuration with data source

The data source is now defined, so press Ctrl-S to save the server configuration.
If the server was running, it has to be restarted before running the application
that uses the data source.

Testing the database application


To test the generated database application, start the ItsoServer, select the
generated HTML input form (ListCreditsInputForm.html in this example), and
select Run on Server from its context menu.

A sample run is shown in Figure 8-14.

Chapter 8. Developing Web applications with database access 259


Figure 8-14 Sample database application run

Accessing a database using DB Beans


In this section, we explain how to use the DB Beans package to access a
database. The DB Beans classes can be found in the com.ibm.db.beans
package.

260 WebSphere Studio Application Developer Version 5 Programming Guide


To access the DB Beans from Application Developer, the following JAR file must
be available in the Web Content\WEB-INF\lib folder of the folder of the project:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\
dbbeans.jar

Note: The dbbeans.jar file is already in the ItsoProGuideDataBaseWeb project


after using the DB Web Pages wizard.

To import a JAR file into the lib directory of a project:


򐂰 Select the lib folder and Import (context). Select File system, then navigate
to the dbbeans.jar file and import the file.
򐂰 Select the project and Properties (context). Select Java Build Path and on the
Libraries page click Add JARs and select the dbbeans.jar file.

The documentation for the classes in the package can be found in:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\
dbbeans_javadoc.zip

Creating a JSP using DB Beans


After you have imported the package you can use the DB Beans classes by
using <jsp:useBean> to create the bean and then using scriptlets to execute
methods on it.

We begin by creating a new JSP called TestDBBeans.jsp. For more information


on creating a JSP, see “Working with JSPs” on page 210

A simple example of a JSP that executes an SQL statement using the DB Beans
classes is shown in Figure 8-15.

Note: This code was created using Page Designer by visually inserting beans
and scriptlets. To test the JSP, select Run on Server from its context menu.

In this example we use two of the DB Beans classes: DBConnectionSpec, which


handles the database connection, and DBSelect, which wraps an SQL SELECT
statement.

There is a small number of classes in the DB Beans package, and they are
straightforward to use.

Chapter 8. Developing Web applications with database access 261


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META name="GENERATOR" content="IBM WebSphere Studio">
<TITLE>TestDBBeans.jsp</TITLE>
</HEAD>
<BODY>
<H2>Number of rows in CUSTOMER table</H2>
<jsp:useBean id="Connect" class="com.ibm.db.beans.DBConnectionSpec"/>
<jsp:useBean id="SelectStatement" class="com.ibm.db.beans.DBSelect"/>
<% Connect.setDriverName("COM.ibm.db2.jdbc.app.DB2Driver");
Connect.setUrl("jdbc:db2:EJBBANK");
SelectStatement.setConnectionSpec(Connect);
SelectStatement.setCommand("SELECT * FROM ITSO.CUSTOMER");
SelectStatement.execute();
out.println("Row count is: " + SelectStatement.getRowCount());

%>
</BODY>
</HTML>

Figure 8-15 JSP with DB Beans example

The next section describes the JSP tags that have been built on top of the beans
to make it even easier to provide database access functionality to your Web
application.

Accessing a database using JSP taglib


Application Developer provides an alternative to using the DB Beans classes
described above. If you prefer, you can instead use a set of JSP tags built on top
of these classes. It is also possible to mix direct calls to DB Beans and JSP tags.

Note: The code referred to in this section can be generated using the
Database Web Pages wizard and selecting the IBM Database Access Tag
Library - Select Statement model. Refer to “Generate Web pages from SQL
queries” on page 249.

If you decide to use the JSP tags, you should be aware that there are some
restrictions compared to using the beans directly:
򐂰 For any of the JSP SQL actions that require a connection to the database, a
connection is opened when the tag is encountered, and closed after the tag
has been processed. Two actions cannot be performed within the same
transaction scope, or even using the same JDBC connection. The only

262 WebSphere Studio Application Developer Version 5 Programming Guide


exception to this is through the <x:batch> action. Actions inside the body of
the <x:batch> do share the same connection, and optionally, the same
transaction.
򐂰 Using the DB Beans directly, you have complete control over when a
database connection is opened and closed. You also have complete control
over transaction scopes, with the ability to turn AutoCommit on or off and to
do explicit commits or rollbacks.
򐂰 Some of the methods and properties of the DBSelect and DBProcedureCall
beans for handling large result sets are not offered in the JSP SQL actions:
– These methods and properties allow you to limit the number of rows
maintained in memory at any one time and to specify how many rows to
fetch at once when getting additional rows.
– This limitation is necessary because of the above limitation that the
database connection is closed after each JSP SQL action is processed. If
only a subset of the rows is initially fetched into memory, and then the
connection is closed, there is no way to later fetch the remaining rows.
– The JSP SQL actions do provide some support for large result sets via the
maxRows attribute of the <x:select> and <x:procedureCall> actions. This
attribute simply limits the number of rows that are fetched in any one result
set.
– The lockRows property of the DBSelect and DBProcedureCall bean is not
offered via the JSP SQL actions. This property causes a database lock to
be kept on a row in the result set while it is the current row. For a Web
application, it is not likely that you would want to maintain such a lock
across user interactions which could span an arbitrary amount of time.
– Because of the first limitation above, that the database connection is
closed after each JSP SQL action is processed, it is not possible for us to
maintain such a lock when you use the JSP SQL tags. When row locking is
not used, either with the JSP SQL tags or with direct use of the DB Beans,
optimistic locking is still used to prevent you from updating a row if
someone else updates it between the time that you read it and the time
that you attempt to update it.
– A greater variety of methods for moving between rows and between result
sets is available through direct use of the DB Beans than through the JSP
SQL actions.

To use the JSP database tags, you have to import the following two JAR files to
the Java build path into the WEB-INF\lib folder of your project:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\jspsql.jar
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\dbbeans.jar

Chapter 8. Developing Web applications with database access 263


The jspsql.jar file contains the tags and dbbeans.jar contains the actual
classes used to access the database.

Creating a JSP
We now create a TestTagLib.jsp file to use tag libraries. See “Working with
JSPs” on page 210 for details about creating a new JSP.

Open TestTagLib.jsp in Page Designer. You can use the JSP editor to insert the
database tags into your page when you are in the Design view. To be able to use
the custom tags from the database tag library, you first have to do two things:
򐂰 Import the tag library into your Web application as described above.
򐂰 Create the taglib directive in the JSP.

To insert the taglib directive, bring up the context menu on the page in the Design
view and select Page Properties. In the dialog shown select JSP Tags and JSP
Directive - taglib from the Tag Type drop-down menu (Figure 8-16).

Figure 8-16 Insert JSP taglib directive

Click Add to select the tag library to add, and the dialog shown in Figure 8-17 is
displayed.

264 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 8-17 Selecting a tag library

Click Import to locate the jspsql.jar file to import. The Import a Tag Library
dialog opens (Figure 8-18). Click Browse to locate the JAR file:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\jspsql.jar

Figure 8-18 Importing a tag library

Chapter 8. Developing Web applications with database access 265


Be sure to select Add an alias URI so that the tag library is added to the web.xml
file. The entry can be found on the References page.

Click OK to close the dialog. Now the tag library has been imported. Select the
jspsql check box to add it to the JSP (Figure 8-19).

Figure 8-19 Select the jspsql tag library

Select OK twice to close the dialog. The following tag is inserted into your JSP:
<%@taglib uri="jspsql" prefix="dab"%>

The full TestTagLib.jsp is available in:


\sg246957\sampcode\dev-webdb

266 WebSphere Studio Application Developer Version 5 Programming Guide


Building the JSP with custom tags
Now you can add tags to the JSP by selecting JSP -> Insert Custom. You should
see the following dialog (Figure 8-20).

Figure 8-20 Insert custom JSP tags

In the following example we create a JSP that displays a list of transaction


records. We show you some of the main tags that you would use to access the
database. The Application Developer online help contains descriptions for all the
tags that are available.

Note: Application Developer version 5 offers an improved New JSP wizard,


which includes a step to add tag libraries to a newly generated JSP file.

First, we have to create the connection to the database. To do this we use the
<dab:dataSourceSpec> tag. Select dataSourceSpec in the left list, then click
Insert. Click Close, then go to the Source view of the JSP editor. The following
new code has been added:
<dab:dataSourceSpec dataSource="" id="" />

Figure 8-21 shows the correct parameters and values to use for the
<dab:dataSourceSpec> tag. Update the tag in your JSP.

Chapter 8. Developing Web applications with database access 267


<dab:dataSourceSpec id="DSConnect" scope="page"
dataSource='jdbc/ejbbank'/>

Figure 8-21 Establishing a database connection

All the parameters for the connection are retrieved from the data source defined
in the server.

Tip: In the Properties view (Window -> Show View) you can see the properties
of each tag when you place the cursor within the tag.

Once you have established a connection, you can execute the query. Click JSP
-> Insert Custom again, and this time choose select and click Insert. Update the
new select tag to be the same as in Figure 8-22.

<dab:select id="select_master" scope="request" connectionSpec="DSConnect>">


<dab:sql>
SELECT ITSO.TRANSRECORD.TRANSID, ITSO.CUSTOMER.FIRSTNAME,
ITSO.CUSTOMER.LASTNAME, ITSO.TRANSRECORD.ACCID,
ITSO.TRANSRECORD.TRANSAMT
FROM ITSO.CUSTACCT, ITSO.CUSTOMER, ITSO.TRANSRECORD
WHERE ITSO.CUSTACCT.CUSTOMERID = ITSO.CUSTOMER.CUSTOMERID
AND ITSO.CUSTACCT.ACCID = ITSO.TRANSRECORD.ACCID
AND ITSO.TRANSRECORD.TRANSTYPE = 'C'
AND ITSO.CUSTOMER.LASTNAME LIKE :lastname
</dab:sql>
<dab:parameter position = "1" type="CHAR" value="Brown"/>
</dab:select>

Figure 8-22 Executing a select statement in a JSP tag

Here you use the connection created previously to issue the SQL select
statement. The input parameter is specified using the <dab:parameter> tag.

Assuming that you have created an HTML table to display the result, you can
then use <dab:repeat> and <dab:getColumn> to loop through the result set and
display the values. You can either use the insert custom method to get you
started, or enter the code shown in Figure 8-23.

268 WebSphere Studio Application Developer Version 5 Programming Guide


<TABLE border="1">
<TR>
<TH>TransID</TH><TH>Firstname</TH><TH>Lastname</TH>
<TH>Account</TH><TH>Amount</TH>
</TR>
<dab:repeat name="select_master" index="rowNum" over="rows" >
<TR>
<TD>
<dab:getColumn index="1"/>
<INPUT TYPE="hidden" NAME="ITSO_TRANSRECORD_TRANSID<%=rowNum%>"
VALUE='<dab:getColumn index="1"/>'/>
</TD>
<TD>
<dab:getColumn index="2"/>
</TD>
<TD>
<dab:getColumn index="3"/>
</TD>
<TD>
<dab:getColumn index="4"/>
</TD>
<TD>
<dab:getColumn index="5"/>
</TD>
</TR>
<%select_master.next();%>
</dab:repeat>
</TABLE>

Figure 8-23 Displaying result set values

As you can see from the discussion above, both the DB Beans and the
corresponding JSP tags give you an easy and quick way to access relational
data directly from a JSP. As was mentioned earlier, you have to be aware of the
potential problems of combining presentation and business logic in one JSP.

From a model-view-controller perspective, a JSP should ideally only implement


the presentation layer of your application, while the database access should be
handled by JavaBeans. However, if your application is small, or if you are building
a prototype, using the database access facilities described here may be a good
solution.

Chapter 8. Developing Web applications with database access 269


Running the JSP
Figure 8-24 shows the output of the JSP run execution.

Figure 8-24 JSP with DB Beans run

Summary
In this chapter we used the wizards within Application Developer to create
dynamic Web pages using SQL queries. We showed how to access databases
from a Web application, both by using the database Web page wizard and by
creating your own JSPs using tag libraries.

We also described the configuration of a test server with a data source.

270 WebSphere Studio Application Developer Version 5 Programming Guide


9

Chapter 9. Developing applications


with stored procedures
In this chapter, we discusses the following topics:
򐂰 What is a stored procedure?
򐂰 Creating a Java stored procedure
򐂰 Accessing a Java stored procedure
򐂰 Creating a stored procedure with multiple statements

Tip: When building stored procedures with DB2 be sure to use the DB2 app
JDBC driver. Using the BD2 net JDBC driver is unstable and may not work.

© Copyright IBM Corp. 2003. All rights reserved. 271


What is a stored procedure?
A stored procedure is a block of procedural constructs and embedded SQL
statements that are stored in a database and can be called by name. Stored
procedures allow an application program to be run in two parts, one on the client
and the other on the server, so that one client-server call can produce several
accesses to the database. This is good for performance because the traffic
between the client and the server is minimized.

Stored procedures can be written as SQL procedures, or as C, COBOL, PL/I, or


Java programs. In the following sections we will look at how to write and use a
Java stored procedure.

Note: The support for stored procedures varies between different data base
management systems. We are using DB2 stored procedures in the example.

Creating a Java stored procedure


In this section we create a simple stored procedure that takes a customer ID and
returns all customer information. Later we create a Web application that uses the
stored procedure.

Importing the database definition into a Web project


We use a new Web project ItsoProGuideStoredProcWeb for the stored procedure
examples. Create the project by following the instructions in “Creating a Web
project” on page 248.
򐂰 Open the Data perspective and go to the DB Servers view.
򐂰 Select the existing connection Con2 and Reconnect (context). Alternatively,
create a new connection as described in “Creating a database connection” on
page 145 (without a filter to get all the tables).
򐂰 Import the EJBBANK database into the ItsoProGuideStoredProcWeb project.
– Select the EJBBANK and Import to Folder, then select the
ItsoProGuideStoredProcWeb project and click Finish.
– The database is imported into Web Content/WEB-INF/databases.
򐂰 Figure 9-1 shows the Data Definition view in the Data perspective after the
EJBBANK database has been imported.

272 WebSphere Studio Application Developer Version 5 Programming Guide


imported database

folder for stored procedures

Figure 9-1 Data Definition view after importing EJBBANK database

Using the Stored Procedure Wizard


We are now ready to create the stored procedure. Select the Stored Procedures
folder and New -> Java Stored Procedure (or by selecting File -> New -> Other ->
Data -> Java Stored Procedure).

Enter getCustomer as the name of the stored procedure (Figure 9-2).

Figure 9-2 Specify stored procedure name

Chapter 9. Developing applications with stored procedures 273


Click Next and you are taken to the next page in the wizard. Here you specify the
settings and the SQL statement. Click Change to update the SQL statement.

In the SQL Statement window (Figure 9-3), you have several options for entering
an SQL statement:
򐂰 We recommended that you use the SQL Statement Wizard by clicking SQL
Assist (see “Using the SQL Statement Wizard” on page 165).
򐂰 You can enter the statement manually by typing the statement:
SELECT CUSTOMERID, TITLE, FIRSTNAME,
LASTNAME, USERID, PASSWORD
FROM
ITSO.CUSTOMER
WHERE
ITSO.CUSTOMER.CUSTOMERID = :customerID
This statement gets all fields from the customer table given a customer ID.
򐂰 We use one SQL statement (you can click Add to enter multiple statements).
򐂰 Click OK when done.

Figure 9-3 Specifying the SQL statement for the stored procedure

274 WebSphere Studio Application Developer Version 5 Programming Guide


Back in the wizard, the new SQL statement is shown in the statement text box. In
the remainder of this page of the wizard, you can add code fragments that you
wish to include in the generated stored procedure.

Click Next to go to the next page of the wizard, where you specify parameters for
the stored procedure (Figure 9-4):
򐂰 If you used SQL Assist to create the SQL statement, the parameter is already
filled in.
򐂰 If you typed the SQL statement, you have to create the parameter manually
by clicking Add and specifying In (as mode), customerID (as name), and
INTEGER (as SQL type).

Figure 9-4 Specify parameters for the stored procedure

Click Next to continue to the next page (Figure 9-5):


򐂰 Enter itso.storedproc as the Java package for the stored procedure.
򐂰 We leave the default values in the other fields. The Jar ID field is filled in by
default with a value containing the current time stamp.
򐂰 Do not select Build, we will build the stored procedure later.

Chapter 9. Developing applications with stored procedures 275


Figure 9-5 Specify options, such as Java Package, for stored procedure

Click Next, and a summary of the stored procedure is shown (Figure 9-6).

Figure 9-6 Summary of the new stored procedure before it is created

Click Finish to create the stored procedure. You can see the getCustomer stored
procedure in the Stored Procedures folder.

276 WebSphere Studio Application Developer Version 5 Programming Guide


The generated Java stored procedure code is shown in Figure 9-7. You can
double-click getCustomer to open the Java editor.

/**
* JDBC Stored Procedure ITSO.getCustomer
* @param customerID
*/
package itso.storedproc;

import java.sql.*; // JDBC classes

public class GetCustomer


{
public static void getCustomer ( int customerID,
ResultSet[] rs1 )
throws SQLException, Exception
{
// Get connection to the database
Connection con = DriverManager.getConnection
("jdbc:default:connection");
PreparedStatement stmt = null;
boolean bFlag;
String sql;

sql = "SELECT CUSTOMERID, TITLE, FIRSTNAME, "


+ " "
+ " LASTNAME, USERID, PASSWORD"
+ " "
+ " FROM"
+ " "
+ " ITSO.CUSTOMER"
+ " "
+ " WHERE"
+ " "
+ " ITSO.CUSTOMER.CUSTOMERID = ?";
stmt = con.prepareStatement( sql );
stmt.setInt( 1, customerID );
bFlag = stmt.execute();
rs1[0] = stmt.getResultSet();
}
}

Figure 9-7 getCustomer Java stored procedure

Chapter 9. Developing applications with stored procedures 277


Building the stored procedure
After a stored procedure is written locally, you must build it on the database
server. This uploads and compiles the procedure to the database server:
򐂰 Select the getCustomer stored procedure in the Data Definition view and Build
from the context menu.
򐂰 If you are prompted to create a new connection, select the Use Existing
Connection check box, select an existing connection in the combo box and
click Finish.
򐂰 Figure 9-8 shows the DB Output view, which contains the result of the build.

Figure 9-8 DB Output view with build output of stored procedure

Here we see that the build was successful. The GetCustomer class is compiled
and placed into a JAR file, and the JAR file is installed in the target database.

Tip: You can see stored procedures in the DB2 database system by opening
the Control Center.

278 WebSphere Studio Application Developer Version 5 Programming Guide


Executing the stored procedure
Application Developer provides a test facility for stored procedures:
򐂰 Select the getCustomer stored procedure in the Data Definition view and Run
from the context menu.
򐂰 The Run Settings dialog is displayed (Figure 9-9). Enter a customer ID, for
example 104, and click OK.

Figure 9-9 Run Settings dialog

򐂰 The output of the stored procedure is shown in the DB Output view


(Figure 9-10).

Figure 9-10 Output from running getCustomer stored procedure

We have now created a simple procedure that takes an input argument (a


customer ID) and returns the details about that customer from the database.

Tip: You can make changes to the stored procedure by selecting Properties
(context).

Chapter 9. Developing applications with stored procedures 279


Accessing a Java stored procedure
Once you have loaded a stored procedure into the database, it can be used from
an application. The code fragment below shows an example of how to call the
stored procedure:
CallableStatement cs = con.prepareCall("{call ITSO.GetCustomer(?)} ");
cs.setString(1, "104");
ResultSet rs = cs.executeQuery();
while (rs.next()) {
// get the data from the row
String firstName = rs.getString("firstName");
......
}

The ? is a place holder for a parameter. The second line sets 104 as the value for
the parameter. Following that, the stored procedure is executed and the results
are obtained from the result set.

Using a main program


We provide a main program called GetCustomerMain that you can import into the
ItsoProGuideStoredProcWeb project from:
\sg246957\sampcode\dev-proc\GetCustomerMain.java

Import the code into a new itso.storedproc.main package. A neat way to run
the main program in the Web application is by using the universal test client:
򐂰 Start the ItsoServer.
򐂰 Select the GetCustomerMain program and Launch Universal Test Client
(context).
򐂰 A Web browser with the universal test client opens with an instance of
GetCustomerMain created (Figure 9-11).
򐂰 Select the GetCustomerMain instance to expand.
򐂰 Select the main method.
򐂰 Click Expand to expand the String array the parameter.
򐂰 Click Add to create an entry.
򐂰 Enter a customer ID, for example, 104.
򐂰 Click Invoke.
򐂰 The result output is in the Console view.

280 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 9-11 Using the universal test client to run a main program

Generate a JavaBean to access the stored procedure


Application Developer provides a wizard to generate a JavaBean that accesses a
stored procedure:
򐂰 Create a itso.storedproc.bean package under Java Source.
򐂰 Select the getCustomer stored procedure in the Data Definition view and
Generate JavaBean (context).
򐂰 In the wizard (Figure 9-12):
– Click Browse to locate the ItsoProGuideStoredProcWeb/Java Source
folder.
– Click Browse to locate the itso.storedproc.bean package.
– Enter GetCustomberBean as the JavaBean to be generated.
– Select Stored procedure returns a result set and Generate a helper class.
– Click Next.

Chapter 9. Developing applications with stored procedures 281


Figure 9-12 Generate a JavaBean: class specification

򐂰 On the next page, describe the result set (Figure 9-13):


– Select the CUSTOMER table and the first six columns. Do not select the
ADDRESS column to match the SQL statement.
– Click Next.

Figure 9-13 Generate a JavaBean: describe result set

282 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 For connection information (Figure 9-14) select Use Data Source Connection
and Inside the execute () method and provide user ID and password. Click
Next.

Figure 9-14 Generate a JavaBean: connection information

򐂰 The last page (Figure 9-15) is a confirmation page that shows the methods
that are generated. Click Finish.

Figure 9-15 Generate a JavaBean: generated methods

Chapter 9. Developing applications with stored procedures 283


Two classes are generated:
򐂰 GetCustomerBeanRow—Provides access to one row of the result set.
򐂰 GetCustomerBean—Executes the stored procedure and provides a method to
retrieve an array of GetCustomerBeanRow objects.

Using the JavaBean


The generated JavaBean, GetCustomerBean, can be used in a servlet or JSP to
execute the stored procedure and access the result set.

A simple JSP to execute the JavaBean is shown in Figure 9-16. The code is
available in:
\sg246957\sampcode\dev-proc\RunGetCustomerBean.jsp

<BODY>
<H1>JSP -> JavaBean -> Stored Procedure</H1>
<jsp:useBean id="getCustomer"
class="itso.storedproc.bean.GetCustomerBean"></jsp:useBean>

<% getCustomer.execute( new Integer(106) ); %>

<% itso.storedproc.bean.GetCustomerBeanRow row = getCustomer.getRows()[0];


%>
<TABLE border="1">
<TR><TH align="left">ID</TH>
<TD><%= row.getCUSTOMER_CUSTOMERID() %></TD></TR>
<TR><TH align="left">Title</TH>
<TD><%= row.getCUSTOMER_TITLE() %></TD></TR>
<TR><TH align="left">Firstname</TH>
<TD><%= row.getCUSTOMER_FIRSTNAME() %></TD></TR>
......
</TABLE>
</BODY>

Figure 9-16 Simple JSP to execute the JavaBean with the stored procedure

The GetCustomerBean is instantiated using a <useBean> tag. The stored


procedure is executed and the first row of the result set (there is only one) is
retrieved and displayed.

Note that the customer ID is passed as a constant and no error checking is


performed. In a real application the code would be more complex.

Tip: Restart the enterprise application in the server after making changes to
the Web application deployment information.

284 WebSphere Studio Application Developer Version 5 Programming Guide


Using the JSP tag library
Stored procedures can also be executed through the jspsql tag library. See
“Accessing a database using JSP taglib” on page 262 for a description.

To make the tag library available for the Web application, we have to import the
JAR file into the lib directory and add the tag library to the deployment
descriptor:
򐂰 Select the ItsoProGuideStroedProcWeb\Web Content\WEB-INF\lib folder and
Import (context). Select File system, then locate the directory:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars
򐂰 Select only the jspsql.jar file and click Finish.
򐂰 Open the deployment descriptors (web.xml). On the References page, select
the JSP tag libraries tab. Click Add and select the jspsql tag library. Save the
deployment descriptor.

Figure 9-17 shows a sample JSP that uses the tag library to execute the stored
procedure. The code is available in:
\sg246957\sampcode\dev-proc\RunStoredProcedure.jsp

<%@taglib uri="jspsql" prefix="dab"%>


......
<BODY>
<H1>JSP with Stored Procedure Call</H1>
<dab:dataSourceSpec id="DSConnect" scope="page" dataSource='jdbc/ejbbank' />
<dab:procedureCall id="getCust" connectionSpec="DSConnect" scope="request">
<dab:sql>
{ CALL ITSO.GETCUSTOMER(:customerID) }
</dab:sql>
<dab:parameter parmName="customerID" type="INTEGER" mode="in" value="104"
/>
</dab:procedureCall>
<TABLE border="1">
<TR><TH align="left">ID</TH>
<TD><dab:getColumn name="getCust" index="1" /></TD></TR>
<TR><TH align="left">Title</TH>
<TD><dab:getColumn name="getCust" index="2" /></TD></TR>
<TR><TH align="left">Firstname</TH>
<TD><dab:getColumn name="getCust" index="3" /></TD></TR>
......
</TABLE></BODY>

Figure 9-17 JSP with tag library to execute stored procedure

Chapter 9. Developing applications with stored procedures 285


Generate JavaBean Web pages
You can use the Create Web Pages from a JavaBean wizard to build the input
and output pages to test the JavaBean that calls the stored procedure.

This wizard is described in “Creating Web pages from a JavaBean” on page 237,
therefore we only provide short instructions here to run through the wizard:
򐂰 Select New -> Other -> Web -> JavaBean Web Pages.
򐂰 Select /ItsoProGuideStoredProcWeb/Web Content as destination and
itso.storedproc.web as package.
򐂰 Select itso.storedproc.bean.GetCustomerBean as the bean. Click Introspect
if necessary.
򐂰 Select the rows property (the result of the stored procedure) and the execute
method (to run the stored procedure).
򐂰 Select Create a new front controller.
򐂰 Tailor the input page with:
– Title: Execute Stored Procedure
– Prompt: Enter a customer ID:
򐂰 Tailor the result page with:
– Title: Stored Procedure Results
– Label for rows property: Customer
– Expand rows, select the six properties (all except class), and set short
labels for all the properties (Title, Lastname, UserID, Password, ID,
Firstname)
򐂰 Leave GetCustomerBean as prefix and click Finish to generate the code. You
get a servlet, an HTML input page, and a result JSP:
GetCustomerBeanController.java
GetCustomerBeanInputForm.html
GetCustomerBeanResultsForm.jsp

To test the generated application, restart the enterprise application (select the
ItsoServer and Restart Project -> ItsoProGuide) or restart the server.

Select the GetCustomerBeanInputForm.html file and Run on Server. Enter a


customer ID and click Submit. A sample run is shown in Figure 9-18.

286 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 9-18 Running the generated Web application

Creating a stored procedure with multiple statements


Here we want to create a stored procedure that transfers money between two
accounts. Therefore, we have to execute two SQL statements in sequence, one
to withdraw money from one account, and one to deposit money into another
account.

To create this stored procedure:


򐂰 In the Data perspective, select the Stored Procedures folder and New ->
Stored Procedure.
򐂰 Enter transferMoney as name.
򐂰 On the definition page, select None for result sets and SP_JAVA_HDR.FRAGMENT
for the header fragment. Click Change to enter the SQL statements.

Chapter 9. Developing applications with stored procedures 287


򐂰 In the SQL statement dialog (Figure 9-19) enter the first SQL statement as:
UPDATE ITSO.ACCOUNT
SET BALANCE = (BALANCE - :amount)
WHERE ACCID = :account1
AND BALANCE > :amount
򐂰 Click Add to get space for another SQL statement and enter:
UPDATE ITSO.ACCOUNT
SET BALANCE = (BALANCE + :amount)
WHERE ACCID = :account2
򐂰 Click OK and then click Next.

Figure 9-19 Stored procedure with two statements

򐂰 In the Parameters dialog, one parameter named whichQuery is predefined.


The generated code assumes that you want to run one of the two statements.
We will have to run both. We will take care of this in the generated code.
򐂰 Define these parameters (Figure 9-20):
– In: account1, VARCHAR, 8
– In: account2, VARCHAR 8
– In: amount, DECIMAL, 8.2
– Out: success, INTEGER

288 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 9-20 Parameters for the stored procedure

򐂰 You can skip the rest of the dialog and click Finish.

Edit the generated code


The generated Java class TransferMoney uses the whichQuery parameter to
decide which statement to execute. We have to change the code to execute both
statements and to set the return value.

Our changes are as follows:


򐂰 Remove the whichQuery parameter.
򐂰 Remove the switch and case statements.
򐂰 Create variables for both SQL statements.
򐂰 Run both statements in sequence.
򐂰 Set the result as the sum of the changed rows (a result of 2 would be a
success).

The changed method is shown in Figure 9-21.

Chapter 9. Developing applications with stored procedures 289


public static void transferMoney ( int whichQuery,
String account1,
String account2,
java.math.BigDecimal amount,
int[] success )
throws SQLException, Exception
{
// Get connection to the database
Connection con = DriverManager.getConnection("jdbc:default:connection");
PreparedStatement stmt = null;
PreparedStatement stmt2 = null;
int updateCount = 0;
int updateCount2 = 0;
boolean bFlag;
String sql, sql2;
switch (whichQuery)
{
case 0:
sql = "UPDATE ITSO.ACCOUNT"
+ " SET BALANCE = (BALANCE - ?) "
+ " WHERE ACCID = ? "
+ " AND BALANCE > ?";
stmt = con.prepareStatement( sql );
stmt.setBigDecimal( 1, amount );
stmt.setString( 2, account1 );
stmt.setBigDecimal( 3, amount );
bFlag = stmt.execute();
rs1 = stmt.getResultSet();
updateCount = stmt.executeUpdate();
break;
case 1:
sql2 = "UPDATE ITSO.ACCOUNT"
+ " SET BALANCE = (BALANCE + ?) "
+ " WHERE ACCID = ?";
stmt2 = con.prepareStatement( sql2 );
stmt2.setBigDecimal( 1, amount );
stmt2.setString( 2, account2 );
bFlag = stmt.execute();
rs1 = stmt.getResultSet();
updateCount2 = stmt2.executeUpdate();
break;
default:
sql = "SELECT PROCSCHEMA, PROCNAME FROM SYSCAT.PROCEDURES";
stmt = con.prepareStatement( sql );
}
updateCount = stmt.executeUpdate();
// Set return parameter
success[0] = updateCount + updateCount2;
}

Figure 9-21 Updated stored procedure with two SQL statements

290 WebSphere Studio Application Developer Version 5 Programming Guide


Build and execute
Build the stored procedure by selecting Build from the context menu.

Test the procedure by selecting Run. Enter 106-6001, 106-6002, and 100.00 as
parameters. The DB Output view (Figure 9-22) shows the result value in the
Parameters tab.

Figure 9-22 Stored procedure run

Tip: The database is not updated by default. Select the transferMoney stored
procedure and Run Settings (context). On the Options tab you can select
Commit changes to the database.

Using a JSP
We provide the RunTranfer.jsp to execute the transferMoney stored procedure.
The core code is shown in Figure 9-23.

<dab:dataSourceSpec id="DSConnect" scope="page" dataSource='jdbc/ejbbank' />


<dab:procedureCall id="transfer" connectionSpec="DSConnect" scope="request">
<dab:sql>
{ CALL ITSO.TRANSFERMONEY (:account1, :account2, :amount, :success) }
</dab:sql>
<dab:parameter parmName="account1" type="VARCHAR" mode="in"
value="106-6002" />
<dab:parameter parmName="account2" type="VARCHAR" mode="in"
value="106-6001" />
<dab:parameter parmName="amount" type="DECIMAL" mode="in"
value="100.00" />
<dab:parameter parmName="success" type="INTEGER" mode="out" />
</dab:procedureCall>
......
Amount: <dab:getParameter name="transfer" parmName="amount" /><br>
Result: <dab:getParameter name="transfer" parmName="success" />

Figure 9-23 JSP to execute the transfer stored procedure

Chapter 9. Developing applications with stored procedures 291


Summary
In this chapter we developed two stored procedures, one with a result set and
one that updates the database.

We also showed how stored procedures can be invoked through JavaBeans and
JSPs.

292 WebSphere Studio Application Developer Version 5 Programming Guide


10

Chapter 10. Developing Struts


applications
In this chapter we introduce you to the Jakarta Struts framework and Application
Developer’s support for building Struts-based Web applications.

The chapter describes how to:


򐂰 Create a Web project with Struts support
򐂰 Create a Web diagram and lay out the components of the application
򐂰 Implement form beans, JSPs, and actions
򐂰 Use the Struts configuration file editor
򐂰 Test the application

© Copyright IBM Corp. 2003. All rights reserved. 293


What is Struts?
Struts is an open source framework for building Web applications according to
the model-view-controller (MVC) architectural pattern. Struts is part of the
Jakarta project, sponsored by the Apache Software Foundation.

By using Struts you can get a clean separation between the presentation and
business logic layers of your application. Struts also speeds up Web application
development by providing an extensive JSP tag library, parsing and validation of
user input, error handling, and internationalization support.

The scope of this chapter is not to teach you the Struts framework in detail, but to
show how to use Application Developer’s Struts tools for building a Struts Web
application. To learn more about the Struts framework, please refer to the official
Jakarta project Struts home page and the official Struts user guide at:
http://jakarta.apache.org/struts
http://jakarta.apache.org/struts/userGuide/introduction.html

There is also a number of very good Struts tutorials available on the Internet.

Note: Application Developer 5.0 includes support for Struts Version 1.02 and
Version 1.1 beta 2. At the time of writing, the latest version of the Struts
framework is version 1.1 Release Candidate 1.

MVC architectural pattern


The model-view-controller architectural pattern was conceived in the mid-1980's
by developers of the Smalltalk-80 GUI library. It has since then been extensively
applied in most object oriented user interface and application control toolkits,
as is the case with Struts, and has been improved to respond to specific platform
requirements, such as J2EE. It has also been generalized as a pattern for
implementing the separation of concerns among application layers in general,
and not only the three originally proposed layers.

According to the MVC pattern, a software component (an application, a module,


and so forth) should separate its business logic (the model) from its presentation
(the view). There are many reasons for this requirement, among which are these
facts:
򐂰 You may have more than one view of the same model. If both the business
logic and its presentation were built together, adding an additional view would
cause considerable disruptions and increase the component's complexity. A
good example of a model with two views would be a banking application that
can be accessed through both the Internet and mobile phones.

294 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 You do not want to have to change the model every time you modify the view.
The view is definitely dependent on the model, for it presents specific aspects
of the model to the user. It makes no sense, though, to have the model
depend on the view. Building both together dramatically increases the
chances of this happening, and of you having to change the model every time
you implement a small change to the view.

This separation can be achieved through the layering of the component into:
򐂰 The model layer, responsible for implementing the business logic.
򐂰 The view layers, each responsible for rendering the user interface (be it
graphical or not) to a specific client type and in a specific fashion.

With these two layers, we can implement the business logic and present it to the
user. That solves only half of the problem. We would also like to be able to
interact with the model. The implementation of this interaction is better left to a
third layer, called controller.

In the following sections we discuss some of the properties of each of these


layers.

Model
The model layer manages the application domain’s concepts, both behavior and
state. It responds to requests for information about its state and responds to
instructions to change its state.

Just like any software component, the model should have a well-defined and an
as simple as possible public interface. This is usually achieved through the use of
a facade. The intent of facades is to provide a simple and unified interface to the
otherwise complex model that lies behind it. By doing so, we reduce the
dependencies between the model classes and its clients. Less dependencies
mean more freedom to adapt to new requirements.

Note: Facade is a documented design pattern. For more information, refer to


Design Patterns: Elements of Reusable Object-Oriented Software.

As an example, consider an appliance with which you are certainly familiar: a


television set. You will probably agree that changing TV channels is quite a
simple task. Now ask yourself these questions:
򐂰 Do you know how the television set represents channels internally?
򐂰 Do you know exactly what goes on when you change TV channels?
򐂰 Do you think you should know these things?

Chapter 10. Developing Struts applications 295


Chances are that you have answered no to all of the questions above. What is
the advantage of you not knowing how TVs represent their data and implement
their operations? That way you can buy a new TV, which does these things
internally in a completely different way, and you could still change channels.

Figure 10-1 shows the model layer with its encapsulated business domain
objects and the exposed facade object.

Model

Façade

Figure 10-1 Model layer

Please note that the model does not have any dependences on views or
controllers.

View
The view layer implements a rendering of the model. The responsibility of the
view is to know what parts of the model’s state are relevant for the user, and to
query the model for that information. The view retrieves the data from the model
or receives it from the controller, and displays it to the user in a way the user
expects to see it.

Controller
The controller’s responsibility is to capture user events and to determine which
actions each of these events imply, depending on both the user’s and the
application’s state. This usually involves verifying pre- and post-conditions.
These actions can then be translated to messages to the model and view layers,
as appropriate.

296 WebSphere Studio Application Developer Version 5 Programming Guide


Dependencies between MVC layers
Figure 10-2 shows the dependencies allowed in the MVC pattern. Note that the
less dependencies your layers have, the easier it will be for the layers to respond
to requirement changes.

A B <=> A depends on B

Controller View

Model

Figure 10-2 Dependencies allowed in the MVC pattern

So, to summarize, the MVC pattern is really about separation.

MVC framework with Struts


Struts provides these components to develop applications using MVC
(Figure 10-3):
Model Struts does not provide model classes. The business logic must
be provided by the Web application developer as JavaBeans or
EJBs.
View Struts provides action forms to create form beans that are used
to pass data between the controller and view. In addition, Struts
provides custom JSP tag libraries that assist developers in
creating interactive form-based applications using JSPs.
Application resource files hold text constants and error message,
translated for each language, that are used in JSPs.
Controller Struts provides an action servlet (controller servlet) that
populates action forms from JSP input fields and then calls an
action class where the developer provides the logic to interface
with the model.

Chapter 10. Developing Struts applications 297


View Controller Model
Tag libraries

Action

: JSP
ActionServlet Action Model

: ActionForm
Action

configuration
Application file Action
Resources

Struts Support

Figure 10-3 Struts components in the MVC architecture

A typical Struts Web application is composed of these components:


򐂰 A single servlet (extending org.apache.struts.action.ActionServlet)
implements the primary function of mapping a request URI to an action class.
Before calling the action class, it populates the form bean associated to the
action with the fields from the input JSP. If specified, the action servlet also
requests the form bean to validate the data. It then calls the action class to
carry out the requested function. If form bean validation fails, control is
returned to the input JSP so the user can correct the data. The action servlet
is configured by an XML configuration file that specifies the environment and
the relationship between the participating components.
򐂰 Multiple JSPs that provide the end-user view. Struts comes with an extensive
tag library to make JSP coding easier. The JSPs display the information
prepared by the actions and requests new information from the user.
򐂰 Multiple action classes (extending org.apache.struts.action.Action) that
interfaces with the model. When an action has performed its processing, it
returns an action forward object which determines the view that should be
called to display the response. The action class prepares the information
required to display the response, usually as a form bean, and makes it
available to the JSP. Usually the same form bean that was used to pass
information to the action is used also for the response, but it is also common
to have special view beans tailored for displaying the data. An action forward
has properties for its name, address (URL) and a flag specifying if a forward

298 WebSphere Studio Application Developer Version 5 Programming Guide


or redirect call should be made. The address to an action forward is usually
hard coded in the action servlet configuration file but can also be generated
dynamically by the action itself.
򐂰 Multiple action forms (extending org.apache.struts.action.ActionForm) to
hold the data retrieved from the JSPs. The action forms are generic
Javabeans with getters and setters for the input fields available on the JSPs.
Usually there is one form bean per Web page, but you can also use more
coarse-grained form beans holding the properties available on multiple Web
pages (this fits very well for wizard-style Web pages). If data validation is
requested (a configurable option) the form bean is not passed to the action
until it has successfully validated the data. Therefore the form beans can act
as a sort of firewall between the JSPs and the actions, only letting valid data
into the system.
򐂰 One application resource file per language supported by the application holds
text constants and error messages and makes internationalization easy.

Figure 10-4 shows the flow of information for an interaction in a Struts Web
application.

: Web user : ActionServlet : Action : ActionForm : JSP


(Browser)

HTTP setXxx()
validate()

execute() getXxx()

setXxx()
"forward"

forward()

getXxx()

Figure 10-4 Struts request sequence

A request from a Web browser reaches the Struts ActionServlet. If the action
that will handle the request has a form bean associated with it, Struts creates the
form bean and populates it with the data from the input form. It then calls the
validate method of the form bean. If validation fails, the user is returned to the
input page to correct the input. If validation succeeds, Struts calls the action’s
execute method. The action retrieves the data from the form bean and performs
the appropriate logic. Actions often call session EJBs to perform the business

Chapter 10. Developing Struts applications 299


logic. When done, the action either creates a new form bean (or other
appropriate view bean) or reuses the existing one, populates it with new data,
and stores it in the request (or session) scope. It then returns a forward object to
the Struts action servlet, which forwards to the appropriate output JSP. The JSP
uses the data in the form bean to render the result.

Note: In Struts version 1.0 the execute method of the Action class was called
perform.

Application Developer support for Struts


Application Developer provides specific support for Struts-based Web
applications:
򐂰 A Web project can be configured for Struts. This adds the Struts run time (and
dependent JARs), tag libraries, and action servlet to the project, and creates
skeleton Struts configuration and application resources files. Application
Developer 5.0 provides support both for Struts 1.02 and 1.1 beta 2, selectable
when setting up the project.
򐂰 A set of component wizards to define action form classes, action classes with
action forwarding information, and JSP skeletons with the tag libraries
included.
򐂰 A configuration file editor to maintain the control information for the action
servlet.
򐂰 A graphical design tool to edit a graphical view of the Web application from
which components (forms, actions, JSPs) can be created using the wizards.
This graphical view is called a Web diagram. The Web diagram editor
provides top-down development (developing a Struts application from
scratch), bottom-up development (that is, you can easily diagram an existing
Struts application that you may have imported) and meet-in-the-middle
development (that is, enhancing or modifying an existing diagrammed Struts
application).
򐂰 Web Structure view that provides a hierarchical (tree-like) view of the
application. This view shows the artifacts, such as Web pages and actions,
and you can expand the artifacts to see their attributes. For example, an
action can be expanded to see its forwards, which can then be expanded to
see its links. This is useful for understanding specific execution paths of your
application. The Web Structure view is available in the Web perspective.
򐂰 Page Designer support for rendering the Struts tags, making it possible to
properly view Web pages that use the Struts JSP tags. This support is
customizable using Application Developer’s Preferences settings.

300 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Validators to validate the Struts XML configuration file and the JSP tags used
in the JSP pages.

Developing a Web application using Struts


To show how to use the Application Developer Struts tools, we rewrite the
RedBank Web application we developed in “Sample application: RedBank” on
page 180 using the Struts framework.

The application is a banking application that allows a customer to enter his or her
customer number, select an account to work with, and then to perform four
different transactions: list the transactions for the selected account, deposit,
withdraw, and transfer money. The back-end of the application is, for sake of
simplicity, implemented as simple JavaBeans. We will implemented the back-end
using EJB technology in Chapter 12, “Developing EJB applications” on page 373.

Because the Struts framework provides us with the controller and view parts of a
Web application, but not the model, we will reuse the model from the RedBank
application and simply show you how to replace its controller and view with
Struts.

To create our Web application with Struts:


򐂰 We create a new Web project with Struts 1.1 beta 2 support.
򐂰 We import the parts of the existing RedBank application that we will reuse.
򐂰 We create a Web diagram where we lay out all the JSPs, form beans, and
actions that make up the application, and connect them to define the
application flow.
򐂰 We implement the components one by one.
򐂰 Finally, we do some customization using the Struts configuration file editor
and then launch the application in the built-in WebSphere Test Environment.

Note: Because this chapter focuses on Application Developer’s Struts tools


and wizards (more than the architecture and best practices of a Struts
application) we try to use the Struts tools and wizards as much as possible
when creating our application.

After having used the wizards to create some components (JSPs, form beans,
actions) you may be able to create new components even quicker by copying
and pasting from your existing components than by using all the wizards.

Chapter 10. Developing Struts applications 301


Creating a Struts Web project
Before we can start implementing the Struts application we create a Web project
with Struts support:
򐂰 Create a new Web project by selecting File -> New -> Web project and enter
ItsoProGuideStrutsWeb as the name of the project. Select Add Struts support
and then click Next (Figure 10-5).

Figure 10-5 Creating a Web project with Struts support

Note: If you create a Web project as part of creating an Enterprise


Application Project you will not be given the option to add Struts support at
that time. You will have to add the Struts support afterwards by selecting
Properties from the Web project’s context menu and check the Add Struts
support option there.

򐂰 Add the project to the existing ItsoProGuide enterprise application project.


Leave ItsoProGuideStrutsWeb as the context root and click Next
(Figure 10-6).

302 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 10-6 Web project settings

򐂰 On the Module Dependencies page, select the ItsoProGuideJava.jar project


to create a classpath reference to the model that we reuse and click Next
(Figure 10-7).

Figure 10-7 Specify module dependencies

Chapter 10. Developing Struts applications 303


򐂰 On the Struts Settings page, select Override default settings:
– Change the Struts version to 1.1 (beta2).
– Enter itso.strutsweb as the Default Java package prefix.
– Leave itso.strutsweb.resources as the Java package for the resource
bundle.
– Leave ApplicationResources as the resource bundle name.
– Click Finish (Figure 10-8).
Click OK when prompted to repair the server configuration. This action adds
the new Web project to the server configuration.

we used the Struts


beta support

Figure 10-8 Setting Struts properties

The new Web project is configured with:


򐂰 An application resources file:
Java Source\itso.strutsweb.resources.ApplicationResources.properties
򐂰 An action servlet (in web.xml)
򐂰 A configuration file (struts-config.xml) and six tag libraries
(struts-xxxx.tld) in Web Content\WEB-INF
򐂰 The Struts runtime classes (struts.jar and dependent JAR files) in Web
Content\WEB-INF\lib.

304 WebSphere Studio Application Developer Version 5 Programming Guide


Notes:
򐂰 If you create a Web project with Struts 1.02 support, there will be only one
JAR file (struts.jar) in the lib directory, because Struts 1.02 includes all
dependent classes in this single JAR. In Struts 1.1 these classes are now
split into multiple JAR files.
򐂰 Although not necessary for our simple application, you would probably
want to upgrade the Struts JAR file to a later version than the 1.1 beta 2
shipping with Application Developer 5.0. At the time of writing, the latest
version of Struts is 1.1 Release Candidate 1.
򐂰 The Struts action servlet is configured (in web.xml) to intercept all requests
with a URL ending in .do (the servlet mapping is *.do). This is common for
Struts applications, but equally common is using a servlet mapping of
/action/* to intercept all URLs beginning with /action.

Copying the facade


We will use the same model and facade as in Chapter 7, “Developing Web
applications” on page 179. The easiest way to get the facade is by copying:
򐂰 Select the itso.bank.facade package in the ItsoProGuideBasicWeb project
and Copy from the context menu.
򐂰 Select the Java Source folder in the ItsoProGuideStrutsWeb project and
Paste from the context menu.

Alternatively you can create the itso.bank.facade package manually and import
the Banking class from the \sg246957\sampcode\dev-struts\initial\facade
directory.

Importing RedBank Web content


We want to mirror the image and style sheet of the ItsoProGuideBasicWeb project
in the new ItsoProGuideStrutsWeb project:
򐂰 Open the Web perspective, J2EE Navigator view, select the
ItsoProGuideStrutsWeb\Web Content directory and Import (context).
򐂰 Select File system as source to import from and then click Next.
򐂰 Click Browse and locate:
\sg246957\sampcode\dev-struts\initial\Web Content
򐂰 Expand the Web Content directory and select the check box next to it.
򐂰 Click Finish (Figure 10-9).

Chapter 10. Developing Struts applications 305


Figure 10-9 Importing sample code

Updating ApplicationResources.properties
The wizard created an empty ApplicationResources.properties file for us and
we have to update it with the texts and messages for our application.

While developing Struts applications, you will usually find yourself having this file
open, because you will typically add messages to it as you go along writing your
code. Figure 10-10 shows an extract of this file.

306 WebSphere Studio Application Developer Version 5 Programming Guide


# Optional header and footer for <errors/> tag.
errors.header=<P><font color="#ff0000"><strong><ul>
errors.footer=</ul></strong></font></P>
error.missing.customerId=<li>You must enter your customer ID.
error.missing.accountNumber=<li>You must select an account to work with.
...
error.invalid.customerId=<li>Invalid customer ID. Please try again.
error.invalid.amount=<li>Invalid amount. Please correct your entry.
...
text.pageTitle=ITSO Bank
text.welcome=Welcome to the ITSO Bank
text.customersAccounts={0}'s Accounts
...
...
prompt.enterCustomerId=Please, enter your customer ID:
prompt.account=Select the account:
prompt.transaction=Select the transaction:
...

Figure 10-10 ApplicationResources.properties (extract)

򐂰 In the Web perspective, expand Java Source and then open the
itso.strutsweb.resources.ApplicationResources.properties file.
򐂰 Replace then contents of the file with the contents in:
\sg246957\sampcode\dev-struts\initial\ApplicationResources.properties
򐂰 Press Ctrl-S to save the file and then close the editor.

The exception classes we use extend the itso.bank.exception.BankException


class and have a method called getMessageKey. This method returns the key for
the error message so that we can retrieve the clear text message from the
ApplicationResources.properties file when an error has occurred. An example
of the getMessageKey method is:
public String getMessageKey() {
return "error.customerDoesNotExistException";
}

Creating the Struts Web diagram


We take a top-down approach to design the Web application by laying out all the
components in a Web diagram:
򐂰 Select the WEB-INF folder and New -> Other -> Web -> Struts -> Web diagram.
Click Next. Enter strutsbank as the file name and click Finish.

Chapter 10. Developing Struts applications 307


򐂰 The Web diagram editor opens on the strutsbank.gph file (.gph is the file
type for Web diagrams).
򐂰 Notice the icons in the tool bar:

The icons on the right are to place new components into the empty diagram.
The icons are connections, actions, form beans, JavaBeans, JSPs,
sub-diagrams, and Struts modules.

Adding the components


Use the icons in the toolbar to add four JSP pages, three actions, and two form
beans on the empty surface (Figure 10-11):
򐂰 When you drop a JSP page or an action, you can change its name to the
name shown in Figure 10-11.
򐂰 When you drop a form bean, you are prompted for a name and scope. Enter
customerInfoForm and transactionForm as names and select request as
scope.

Figure 10-11 Web diagram with initial components

Components in gray are not yet implemented, meaning they are only available in
the Web diagram and not as an underlying file such as a Java class or JSP.

308 WebSphere Studio Application Developer Version 5 Programming Guide


Designing the application flow
When the components are laid out, it is time to connect them to define the flow of
the application. Figure 10-12 shows the layout with connections.

Figure 10-12 Web diagram with components connected

򐂰 Select index.jsp and select Connection (context). A line appears connecting


index.jsp to the mouse cursor. Click the listAccounts action to complete the
connection. A dotted line appears from index.jsp to listAccounts. (You can
also use the Connection icon and click the two items to connect.)
򐂰 Connect listAccounts.jsp to the accountDetails action, the
accountDetails.jsp to the performTransaction action, and the
listTransactions.jsp to the accountDetails action.
򐂰 Connect the listAccounts action to listAccounts.jsp. Connecting an action
to a JSP page creates a forward, and you are prompted to enter a name for it.
Overtype <new> with the name success. The listAccounts action can then
lookup the listAccounts.jsp by referring to the name success.
򐂰 Connect the accountDetails action to the accountDetails.jsp and enter
success as the name for this forward as well.
򐂰 The performTransaction action uses four different forwards depending on
which transaction was performed:
– Connect the performTransaction action to listTransactions.jsp and call
this forward listTransactions.

Chapter 10. Developing Struts applications 309


– Add three forwards from performTransaction back to accountDetails.jsp
and call the forwards deposit, withdraw, and transfer, respectively.
򐂰 Connect the customerInfoForm to the listAccounts action and also to the
accountDetailsAction. The customerInfoForm is used by both actions.
򐂰 Connect the transactionForm to the performTransaction action.
򐂰 Save the Web diagram by pressing Ctrl-S.

Tip: You can select a component in the diagram and from the context menu
select:
򐂰 Change Path to change the name of a JSP or action
򐂰 Edit the forward name to change the name of a connection
򐂰 Change Description to add descriptive text to any components

To improve the layout of the application flow, you can drag components to
another spot and you can rearrange connections by dragging their middle
point.

Implementing the Struts Web diagram


When the Web diagram is laid out, it is time to start implementing the
components. This can be done in a different order, and the support you get from
Application Developer’s Struts tools depends on the order you choose:
򐂰 You can implement the form beans first. When you later implement the JSPs,
you can choose which fields from the form beans should be present on the
pages.
򐂰 You can implement the JSPs first. When you later implement the form beans,
you can choose which fields from the JSP pages should be added to the form
beans as properties.

We choose to implement the form beans first to have full control over their
contents and structure.

Developing the form beans


We start by implementing the customerInfoForm form bean:
򐂰 Double-click the customerInfoForm form bean in the Web diagram. This
opens up the New ActionForm Class dialog as shown in Figure 10-13.

310 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 10-13 New ActionForm Class wizard

Application Developer automatically generates a Struts form bean class


called itso.strutsweb.forms.CustomerInfoForm and implement skeleton
methods for its reset and validate methods. The default values in the dialog
are fine, so click Next to proceed.
򐂰 On the next page we can select the fields from the JSPs we want to include in
the form bean. Because we do not yet have any implemented JSPs, we
cannot use this feature, so just click Next (Figure 10-14).

Chapter 10. Developing Struts applications 311


Figure 10-14 Selecting fields from JSPs

򐂰 On the third page of the wizard we can enter the fields we want our form bean
to hold. Click Add and add each of the following fields (Figure 10-15):
customerNumber String
customerName String (firstname lastname)
accountNumber String (after selection)
accountNumbers String[] (list retrieved from customer)
validateKey String (1 or 2, which action)

Figure 10-15 Adding form bean fields

Click Next.

Note: Make sure you press Enter after entering the text in each field.
Otherwise, when you click Next, Application Developer may not include the
last field you updated.

312 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 On the next page (Figure 10-16) you are prompted to add a mapping for the
form bean to the Struts configuration file. Accept the defaults and click Finish.

Figure 10-16 Adding struts-config.xml mapping

The form bean wizard creates a new Java class extending the
org.apache.struts.action.ActionForm class and opens it up in the editor.
򐂰 Replace the validate method (not the whole class) with the code shown in
Figure 10-17. The code is available in:
\sg246957\sampcode\dev-struts\initial\forms\CustomerInfoForm.txt

public ActionErrors validate( ActionMapping mapping,


HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
// Validate the customerNumber
if ("1".equals(validateKey)) {
if (customerNumber == null || customerNumber.trim().length() == 0)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.missing.customerId"));
else if (customerNumber.trim().length() != 3)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalid.customerId"));
}

// Validate the accountNumber - defer to action class


if ("2".equals(validateKey)) {}

return errors;
}

Figure 10-17 CustomerInfoForm validate method

Chapter 10. Developing Struts applications 313


Because we use this form bean on multiple input pages, we have to know
which of the fields should be validated. We use the validateKey string for this
purpose. On the JSPs where this form bean is used, we pass an appropriate
value for the validateKey so we can validate the data entered on that
particular page only.
The validate method in a Struts form bean acts as a kind of firewall between
the input pages and the Struts actions, only letting validated data into the
actions. The validate method is useful for performing simple validation such
as verifying that data has actually been submitted, has the correct length, and
so forth. However, it is not the appropriate place to do more advanced
validation, such as calling an EJB to validate that a customer number really
exists. That type of validation is best carried out by the actions themselves.
The validate method returns an org.apache.struts.action.ActionErrors
object with the keys for the errors it has found. This is used by the JSPs to
inform the user that an entry has to be corrected.
When done, save and close the CustomerInfoForm class.
򐂰 Implement the transactionForm form bean using the same method. This
class should be called TransactionForm and have the following fields:
action String (ListTransactions, Deposit, ...)
amount String (for deposit, withdraw, transfer)
destinationAccount String (for transfer only)
accountID String (to remember)
accountBalance String (to remember)
transactions itso.bank.model.TransRecord[]
(retrieved for an account)
Make sure the form is added to struts-config.xml with the mapping name
transactionForm.
򐂰 Add an import statement:
import itso.bank.util.AmountConverter;
򐂰 Replace the definition of the action field at the beginning of this class with the
following line:
private String action = "ListTransactions";
This will make Struts select the List Transactions option in the
accountDetails.jsp page so that it will be the default.
򐂰 Set the default value also in the reset method:
action ="ListTransactions";
򐂰 Replace the validate method with the code shown in Figure 10-18. The code
is available in:
\sg246957\sampcode\dev-struts\initial\forms\TransactionForm.txt

314 WebSphere Studio Application Developer Version 5 Programming Guide


public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if (action != null && action.trim().length() != 0) {


if ("Deposit".equals(action)
|| "Withdraw".equals(action)
|| "Transfer".equals(action)) {

if (amount == null || amount.trim().length() == 0)


errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.missing.amount"));
else
try {
java.math.BigDecimal a = AmountConverter.fromString(amount);
if (a.compareTo( new java.math.BigDecimal(0.00) ) <= 0)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalid.amount"));
} catch (Exception e) {
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalid.amount"));
}
}

if ("Transfer".equals(action)) {
if (destinationAccount == null
|| destinationAccount.trim().length() == 0)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.missing.destinationAccount"));
}
}
return errors;
}

Figure 10-18 TransactionForm validate method

This method uses the action string to determine what fields should be
validated.
򐂰 Press Ctrl-S to save this class and then close the Java editor.

Chapter 10. Developing Struts applications 315


When the form beans are implemented, they show up colored in the Web
diagram. The next step is to implement the Web pages.

Note: If deleting a component from the Web diagram, you are prompted
whether you also want to delete the underlying resource. Underlying resource
here refers to the mapping in the struts-config.xml file, not the implemented
component itself. This means that if you delete a form bean and also delete
the underlying resource, it will remove the form bean from the Web diagram
and its mapping from the struts-config.xml file. It will not, however, delete
the Java source or class file for the form bean. If you then add a new form
bean with the same name to the Web diagram and attempt to implement it, the
Finish button that you must click to create the component is deactivated in the
wizard. This is due to the fact that this class already exists, it was not deleted.

Developing the JSPs


We start by implementing the index.jsp page:
򐂰 Double-click the index.jsp page. This opens up the New JSP File dialog as
shown in Figure 10-19. The defaults are fine, so click Next.

Figure 10-19 New JSP File wizard

316 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 On the tag libraries page (Figure 10-20), you can add the tag libraries that the
JSP requires. The wizard has already added the two most commonly used
Struts tag libraries, html and bean. Our index.jsp page does not require any
other tag libraries, so click Next.

Figure 10-20 Add tag libraries

򐂰 On the tag directive page, select Create Session Variable and true
(Figure 10-21). Click Next.

Figure 10-21 JSP page directive

Chapter 10. Developing Struts applications 317


򐂰 On the next two dialogs in the wizard, you can click Next and use the defaults.
These dialogs are not Struts-dependent, so we do not explain them here. For
information about these dialogs, refer to “Creating a Web project” on
page 185.
򐂰 On the Form Field Selection page (Figure 10-22), you are asked to supply the
name of the form bean from which index.jsp should get its fields, and specify
which fields to use.
Select the customerInfoForm form bean from the pull-down menu, select the
customerNumber, and validateKey fields. The customerNumber will be an input
field and the validateKey a hidden field that is passed to the validation
routine.
Click Next.

Figure 10-22 Choosing form bean fields for index.jsp

򐂰 On the next dialog (see Figure 10-23) you can design the input form used on
the index.jsp page. Unfortunately this feature does not use the Struts tag
libraries to its fullest.
For example, if you enter customerNumber as the label for a field, what you
really would like in the JSP is <bean:message key="customerNumber"/>, so
that the corresponding text from the ApplicationResources.properties file is
displayed. The result produced by the wizard, however, is the exact text you
enter.

318 WebSphere Studio Application Developer Version 5 Programming Guide


Therefore, for the customerNumber field:
– Label: <bean:message key="prompt.enterCustomerId"/>
– Size: 20
For the validateKey field:
– Label: blank
– Initial value: 1
– Field type: hidden
Click Finish.

Figure 10-23 Designing input fields

The index.jsp is created and opened in the Page Designer.

As you can see in the editor, the wizard has inserted the two Struts tag libraries
we requested:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

Chapter 10. Developing Struts applications 319


It has also created an input form that prompts for the customer number and
submits it to the listAccounts action for processing:
<html:form action="/listAccounts">
<TABLE border="0">
<TBODY>
<TR>
<TH></TH>
<TD><html:hidden property='validateKey' value='1' /></TD>
</TR>
<TR>
<TH><bean:message key="prompt.enterCustomerId" /></TH>
<TD><html:text property='customerNumber' size='20' value='' /></TD>
</TR>
<TR>
<TD><html:submit property="submit" value="Submit" /></TD>
<TD><html:reset /></TD>
</TR>
</TBODY>
</TABLE>
</html:form>

The Struts <html:form> tag is used to generate the body of the input form. The
<html:text>, <html:submit>, and <html:reset> tags generate the fields and
buttons.

In the Tasks view you see an error:


Target /listAccounts does not exist in the following modules: /

This is because the form’s action refers to the listAccounts action that we have
not yet developed. This error will be fixed when we implement listAccounts.

Note: If you do not see the errors in the tasks view, it may be due to your
filtering settings in the Tasks view.

Tailoring the JSP


The index.jsp that our application uses is a little more complex than the
index.jsp page the wizard has generated for us:
򐂰 This JSP defines the two Struts tag libraries that we use:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
򐂰 It then defines the start of the HTML section using the following tag:
<html:html>
򐂰 Change the <TITLE> tag to:
<TITLE><bean:message key="text.pageTitle"/></TITLE>

320 WebSphere Studio Application Developer Version 5 Programming Guide


This tag takes the mandatory parameter key which refers to the message in
the ApplicationResources.properties file that should be inserted. The
<bean:message> tag automatically converts any non-printable characters into
their HTML representation (for example, the ampersand character is
converted into &amp;).

Tip: You can use the JSP -> Insert Custom option to select any custom
tags from the Struts tag library. For example, for the heading:
򐂰 Select the message tag in the bean library and click Insert.

In the Properties view, set the key value to text.pageTitle.

򐂰 Under the <BODY> tag, add the RedBank text and image in the same way as in
the index.html file in “Using the Page Designer” on page 196:
<TABLE border="0">
<TBODY>
<TR>
<TD>
<H1><FONT color="red">Red</FONT>Bank</H1>
</TD>
<TD><IMG border="0" src="images/itso.gif" width="50"
height="40"></TD>
</TR>
</TBODY>
</TABLE>
򐂰 Add a heading 2 with:
<H2><bean:message key="text.welcome"/></H2>
򐂰 After the header, you can display error messages by using the <html:errors>
tag:
<html:errors></html:errors>
This tag displays the error messages returned as an ActionErrors object by a
form bean’s validate method (or placed in the request scope by an action). In
the ApplicationResources.properties file we have defined the following
special keys that applies basic formatting for the error messages:
errors.header=<P><font color="#ff0000"><strong><ul>
errors.footer=</ul></strong></font></P>
If these two keys are present, the <html:errors> tag inserts their content just
before and after the actual error messages. This makes our errors appear as
an unordered list and in red color. In the ApplicationResources.properties
file we prefix each error message with <li> so they are displayed as a
bulleted list.

Chapter 10. Developing Struts applications 321


򐂰 The <html:hidden> tag is used to supply the additional validateKey
parameter we need to determine which fields to validate:
<html:hidden property="validateKey" value="1"/>
򐂰 The <html:text> tag is used to populate the input field with the contents of
the corresponding field from the CustomerInfoForm form bean:
<html:text property="customerNumber" size="20"/>
򐂰 The submit button of the form is rendered using the <html:submit> tag:
<html:submit property="submit" value="Submit" />
We can use the <bean:message> tag to supply a label from the resources:
<html:submit><bean:message key="text.submit"/></html:submit>
򐂰 Add a footing after the form:
<P><bean:message key="text.footer"/></P>

The complete JSP is shown in Example 10-1.

Example 10-1 Complete index.jsp


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html>
<HEAD>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="true" %>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet" type="text/css">
<TITLE><bean:message key="text.pageTitle"/></TITLE>
</HEAD>
<BODY>
<TABLE border="0">
<TBODY>
<TR>
<TD>
<H1><FONT color="red">Red</FONT>Bank</H1>
</TD>
<TD><IMG border="0" src="images/itso.gif" width="50" height="40"></TD>
</TR>
</TBODY>
</TABLE>
<H2><bean:message key="text.welcome"/></H2>
<html:errors></html:errors>
<html:form action="/listAccounts">
<TABLE border="0">
<TBODY>
<TR>

322 WebSphere Studio Application Developer Version 5 Programming Guide


<TH></TH>
<TD><html:hidden property='validateKey' value='1' /></TD>
</TR>
<TR>
<TH><bean:message key="prompt.enterCustomerId" /></TH>
<TD><html:text property='customerNumber' size='20' value='' /></TD>
</TR>
<TR>
<TD><html:submit><bean:message key="text.submit"/></html:submit></TD>
<TD><html:reset /></TD>
</TR>
</TBODY>
</TABLE>
</html:form>
<P><bean:message key="text.footer"/></P>
</BODY>
</html:html>

Application Developer Struts tools also provide real-time rendering of the Struts
tags. Switch to the Design view of the Page Designer to see what the JSP will
look like (Figure 10-24).

Figure 10-24 Rendering Struts tags in Design view

򐂰 Save and close the index.jsp file.

Chapter 10. Developing Struts applications 323


򐂰 Compare your code with the sample code in:
\sg246957\sampcode\dev-struts\solution\jsp\index.jsp

Note: The rendering of the Struts tags can be customized using the Window
-> Preferences -> Web tools -> Struts tools -> Page Designer Struts Support
dialog. The options available are self-explanatory so we do not cover them
here.

The listAccounts.jsp, accountDetails.jsp, and listTransactions.jsp files


are all implemented using the same method. However, listAccounts.jsp and
listTransactions.jsp require an additional Struts tag library, the logic library.
򐂰 Implement these pages in the same way as you did with index.jsp.
򐂰 When you reach the second page of the New JSP File dialog (see
Figure 10-20 on page 317), click the Add Tag Library button.
򐂰 On the Select a Tag Library page, select the /WEB-INF/struts-logic.tld tag
library and enter logic as its prefix. Then click OK (Figure 10-25).

Figure 10-25 Add Struts logic tag library

324 WebSphere Studio Application Developer Version 5 Programming Guide


Implementing the listAccounts JSP
Here are short instructions for the listAccounts JSP:
򐂰 Start the wizard, add the logic tag library, and proceed to the form fields.
򐂰 Select the customerInfoForm.
򐂰 Select the validateKey, accountNumber, and customerName properties.
– accountNumbers—Field type: radio, label:
<bean:message key="prompt.account" />
– validateKey—Field type: hidden, no label, initial value 2
– customerName—Field type: hidden, no label
򐂰 Create the JSP and the editor opens.
򐂰 Find the <jsp:useBean> tag for the customerInfoForm and replace the line
with the following:
<bean:define id="customerInfoForm" name="customerInfoForm"
type="itso.strutsweb.forms.CustomerInfoForm" />
򐂰 Change the title:
<TITLE><bean:message key="text.pageTitle"/></TITLE>
򐂰 Create a heading with the customer’s name:
<H2><bean:message key="text.customersAccounts"
arg0="<%=customerInfoForm.getCustomerName()%>" /></H2>
򐂰 Display error messages after the heading:
<html:errors/>
򐂰 Note the <logic:iterate> loop that was created for the accountNumbers
array:
<logic:iterate id="accountNumbers_id" name="customerInfoForm"
property="accountNumbers">
<TR>
<TD><html:radio property='accountNumbers_id.accountNumbers' />
</TD>
</TR>
</logic:iterate>
The property points to the accountNumbers array. The iteration loops through
the array and creates an object with the ID accountNumbers_id. For each
iteration a radio button is created. However, the property reference that is
generated is wrong (we want to store the selected account in the
accountNumber attribute), and a radio button must have a value attribute.
򐂰 Change the generated loop by including the type (String[]) of the array. For
the radio buttons we set the property to accountNumber, the value to the

Chapter 10. Developing Struts applications 325


account number (accountNumbers_id), and the text after the button also to the
account number, but retrieved using the <bean:write> tag. Note that the
<bean:write> tag cannot be used inside the value attribute.
<logic:iterate id="accountNumbers_id" name="customerInfoForm"
property="accountNumbers" type="java.lang.String">
<TR>
<TD><html:radio property='accountNumber'
value='<%= accountNumbers_id %>' />
<bean:write name="accountNumbers_id" />
</TD>
</TR>
</logic:iterate>
򐂰 Add a value to the customerName hidden field:
<html:hidden property='customerName'
value='<%= customerInfoForm.getCustomerName()%>' />
򐂰 Change the Submit and Reset buttons to:
<TD><html:submit><bean:message key="text.submit"/></html:submit></TD>
<TD><html:cancel><bean:message key="text.cancel"/></html:cancel></TD>
򐂰 Add the standard heading and footing.
򐂰 Compare your code with the sample code in:
\sg246957\sampcode\dev-struts\solution\jsp\listAccounts.jsp

Implementing the accountDetails JSP


Here are short instructions for the accountDetails JSP:
򐂰 Start the wizard, no logic tag library is required, and proceed to the form
fields.
򐂰 Select the transactionForm.
򐂰 Select all properties except transactions, and order them in this sequence
(use the arrows to resequence the properties):
– action—Field type: radio, initial value: ListTransactions,
label: <bean:message key="prompt.transaction" />
– amount—Field type: text, size: 20,
label: <bean:message key="prompt.amount" />
– destinationAccount—Field type: text, size: 20,
label: <bean:message key="prompt.destinationAccount" />
– accountID—hidden, no label, initial value:
<%= transactionForm.getAccountID() %>
– accountBalance—hidden, no label, value:
<%= transactionForm.getAccountBalance() %>

326 WebSphere Studio Application Developer Version 5 Programming Guide


The two hidden fields save the ID and balance values.
򐂰 Create the JSP and the editor opens.
򐂰 Define the transactionForm as a <bean:define> tag at the top (JSP -> Insert
Bean):
<bean:define id="transactionForm" name="transactionForm"
type="itso.strutsweb.forms.TransactionForm" />
This is not done automatically (as with the previous JSPs) because the
transactionForm is not attached to the accountDetails action.
򐂰 Add an import for the AmountConverter bean to the <%@ page> tag:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="true"
import="itso.bank.util.AmountConverter" %>
Note: The import could have been specified in the create JSP wizard, but the
wizard fails at code generation when an import is added.
򐂰 Change the title:
<TITLE><bean:message key="text.pageTitle"/></TITLE>
򐂰 Create a heading with the account number:
<H2><bean:message key="text.accountMaintenance"
arg0='<%= transactionForm.getAccountID() %>'/>
</H2>
򐂰 Display the balance after the heading:
<P><B><bean:message key="text.currentBalance" />
<%=AmountConverter.fromDecimal( AmountConverter.fromString
( transactionForm.getAccountBalance() ) )%></B></P>
򐂰 Display error messages after the heading:
<html:errors/>
򐂰 Change the first table row to include all the radio buttons for the actions (only
the first one was generated), and add the texts after the buttons:
<TH><bean:message key="prompt.transaction"/></TH>
<TD>
<html:radio property='action' value='ListTransactions'/>
<bean:message key="text.listTransactions" /><br>
<html:radio property='action' value='Deposit'/>
<bean:message key="text.deposit" /><br>
<html:radio property='action' value='Withdraw'/>
<bean:message key="text.withdraw" /><br>
<html:radio property='action' value='Transfer'/>
<bean:message key="text.transfer" />
</TD>

Chapter 10. Developing Struts applications 327


򐂰 Remove the value='' from the following two lines (the Struts tags
automatically add this if the property requested has a value that should be
used to prefill a field):
<TD><html:text property='amount' size='20' value='' /></TD>
...
<TD><html:text property='destinationAccount' size='20' value='' /></TD>
򐂰 Change the Submit and Reset buttons to:
<TD><html:submit><bean:message key="text.submit"/></html:submit></TD>
<TD><html:cancel><bean:message key="text.cancel"/></html:cancel></TD>
򐂰 Add the standard heading and footing.
򐂰 Compare your code with the sample code in:
\sg246957\sampcode\dev-struts\solution\jsp\accountDetails.jsp

Implementing the listTransactions JSP


Here are short instructions for the listTransactions JSP:
򐂰 Start the wizard, add the logic tag library, and proceed to the form fields.
򐂰 Select the transactionForm.
򐂰 Select only the transactions property (it is an array of TransRecord beans)
and set the label to blank.
򐂰 Expand the transactions property (Figure 10-26), select each of the three
attributes (check box), set the type to static text (pull-down) and the label to:
– <bean:message key="text.type" /> for type
– <bean:message key="text.amount" /> for amount
– <bean:message key="text.date" /> for date

Note:
The sequence of the
attributes cannot be
changed using the
arrow buttons

Figure 10-26 Selecting attributes of the transactions array

328 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Create the JSP and the editor opens.
򐂰 Find the <jsp:useBean> tag for the transactionForm and replace the line with
the following:
<bean:define id="transactionForm" name="transactionForm"
type="itso.strutsweb.forms.TransactionForm" />
򐂰 Add an import for the TransRecord and the AmountConverter beanto the <%@
page> tag:
<%@ page ...
import="itso.bank.model.TransRecord, itso.bank.util.AmountConverter"
%>
򐂰 Change the title:
<TITLE><bean:message key="text.pageTitle"/></TITLE>
򐂰 Create a heading and a title for the table:
<H2><bean:message key="text.accountNo"/>
<bean:write name="transactionForm" property="accountID"/></H2>
<P><bean:message key="text.transactionsSorted"/>
򐂰 Display error messages after the heading:
<html:errors/>
򐂰 The result table that is generated is functional and could be left as is. Here are
some possible improvements:
– Remove the outer table (leave the generated buttons).
– Set a border for the inner table.
– Add a column with the transaction number. This requires an indexID in the
<logic.iterate> tag.
– Center the type and right justify the amount. Add a $ sign to the amount.
– Change the Submit button into a Back button after the inner table:
<html:submit><bean:message key="text.back"/></html:submit>
– Remove the Reset button.
The table code should look like this (changes are in bold face):
<TABLE border="1">
<TBODY>
<TR>
<TR>
<TH><bean:message key="text.transactionId"/></TH>
<TH><bean:message key="text.type" /></TH>
<TH><bean:message key="text.amount" /></TH>
<TH><bean:message key="text.date" /></TH>
</TR>

Chapter 10. Developing Struts applications 329


<logic:iterate id="transactions_id" name="transactionForm"
property="transactions" indexId="index">
<TR>
<TD align="center"><%= index.intValue()+1 %></TD>
<TD align="center"><bean:write name='transactions_id'
property='transType' /></TD>
<TD align="right">$<bean:write name='transactions_id'
property='transAmt' /></TD>
<TD><bean:write name='transactions_id'
property='timeStamp' /></TD>
</TR>
</logic:iterate>
</TBODY>
</TABLE>
<P><html:submit><bean:message key="text.back"/></html:submit></P>
򐂰 Add the standard heading and footing.
򐂰 Compare your code with the sample code in:
\sg246957\sampcode\dev-struts\solution\jsp\listTransactions.jsp

Struts logic tag


The Struts logic tag is used to perform functions like iterating over collections
(<logic:iterate>), checking if a form bean is present (<logic:present>),
making conditional statements (<logic:equal>, <logic:lessThan>,
<logic:greaterThan>) and performing string comparisons (<logic:match>).

The tool generates the tag for collections to iterate over the results in two of our
Web pages. For example:
<logic:iterate id="transactions_id" name="transactionForm"
property="transactions" indexId="index"
type="itso.bank.model.TransRecord">

The <logic:iterate> tag takes a number of parameters:


򐂰 The name parameter (transactionForm) is used to select the form bean that
holds the collection to iterate over.
򐂰 The property parameter (transactions) is the attribute that retrieves the
collection from the form bean.
򐂰 The collection to iterate over can be an array, a java.util.Vector, or a
java.util.Collection (a Set is a special collection).
򐂰 The type parameter is used to define the type of the elements in the
collection. The <logic:iterate> tag will then cast the elements it retrieves to
this type. We could add type=”itso.bank.model.TransRecord" to the tag, but
it is not required for our code.

330 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 The element is stored in a bean specified by the id parameter
(transactions_id). We can then use this bean name to retrieve the
information we need.
Inside the iterate clause we use the <bean:write> tag to display the
properties of the bean instance from the collection.
<bean:write name="transactions_id" property="timeStamp"/>
򐂰 The optional indexID parameter defines a variable that gives access the
iteration number:
<%= index.intValue()+1 %>
Although the Struts tag libraries do a good job of keeping your JSPs free from
Java scriptlets and Java code there are times when you still need to resort to
simple Java code snippets.
򐂰 Finally the logic clause is closed with the </logic:iterate> tag.

When all JSPs are implemented you should have the Web diagram shown in
Figure 10-27.

Figure 10-27 Web diagram with JSPs implemented

To complete the application, we also need the three actions, as described in the
following sections.

Chapter 10. Developing Struts applications 331


Developing the actions
Action classes are implemented using the same method as other artifacts.
򐂰 Double-click the listAccounts action in the Web diagram. This opens the
New Action Mapping wizard (Figure 10-28).
This page is used to provide the required information in the
struts-config.xml file about this action. However, because we have already
supplied all necessary information the wizard needs in the Web diagram, all
fields are already filled in for us. Therefore simply click Next.

Figure 10-28 Specify Action mapping information

332 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 The next page (Figure 10-29) is used to generate the action class itself. The
wizard has proposed a name which is based on the name of the action we
gave it in the Web diagram. This is fine so just click Finish to let the wizard
generate the class.

Figure 10-29 Generate action class

The ListAccountsAction class opens in the Java editor. The Struts wizard
has provided us with skeleton code for normal action behavior. The main
method of a Struts action is the execute method. This is the method that
Struts calls to invoke this action and this is where we provide our logic.

Note: Struts 1.0 uses the perform method instead of execute.

򐂰 Add a few import statements:


import javax.servlet.http.HttpSession;

Chapter 10. Developing Struts applications 333


import itso.bank.exception.*;
import itso.bank.facade.*;
import itso.bank.model.*;
import java.util.*;
򐂰 Replace the execute method with the contents in:
\sg246957\sampcode\dev-struts\initial\actions\ListAccountsAction.txt.
The code is shown in Figure 10-2.

Example 10-2 ListAccountsAction execute method


public ActionForward execute( ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
// return value
CustomerInfoForm customerInfoForm = (CustomerInfoForm) form;
try {
// Get input parameter customerNumber and keep it on the HTTP session
String customerNumber = customerInfoForm.getCustomerNumber();
HttpSession session = request.getSession();
if (customerNumber == null)
customerNumber = (String) session.getAttribute("customerNumber");
else
session.setAttribute("customerNumber", customerNumber);
session.removeAttribute("accountNumber");

// Create the new banking façade, get Customer and Accounts


Banking banking = new Banking();
Customer customer = banking.getCustomer(customerNumber);
Account[] accounts = banking.getAccounts(customerNumber);

// Populate the CustomerInfo Form Bean for display


customerInfoForm.setCustomerName( customer.getFirstName()+"
"+customer.getLastName());
String[] accountNumbers = new String[accounts.length];
for (int i=0; i<accounts.length; i++)
accountNumbers[i] = accounts[i].getId();
customerInfoForm.setAccountNumbers( accountNumbers );
// set first account number to check the first radio button
// customerInfoForm.setAccountNumber( accountNumbers[0] );

// Store the bean in the correct scope


if ("request".equals(mapping.getScope()))
request.setAttribute(mapping.getName(), customerInfoForm);
else
session.setAttribute(mapping.getName(), customerInfoForm);

334 WebSphere Studio Application Developer Version 5 Programming Guide


} catch (CustomerDoesNotExistException e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.customerDoesNotExistException"));

} catch (Exception e) {
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error.genericException"));
}

if (!errors.empty()) {
saveErrors(request, errors);
forward = mapping.getInputForward();
} else {
forward = mapping.findForward("success");
}

// Finish with
return (forward);
}

This action class follows the normal sequence most action classes do:
򐂰 It first creates ActionError and ActionForward objects to hold the keys for
any errors that may occur and the forward that will be returned to Struts at the
end of the method. The forward determines the page to be displayed next.
򐂰 It then retrieves the form bean that Struts has populated before calling the
execute method. The form bean is populated with all properties that Struts
could retrieve from the input form and has a getter/setter on the form bean.
򐂰 The action then performs similar business logic as the ListAccounts servlet
from the RedBank application (that is, retrieve the accounts for this customer).
򐂰 After the business logic is performed, the action stores the information
necessary to display the resulting JSP in the form bean and then places this
form bean into the request or session scope, depending on what was
configured in the Struts configuration file. In our case we used the request
scope for this.
򐂰 Should any exceptions occur (for example, the customer number entered
does not exist) a new ActionError object is created with the key
corresponding to the error message, and this ActionError is added to the
ActionErrors object. An ActionErrors object can therefore hold multiple
ActionError objects, each describing a specific error condition.
򐂰 Finally, the method checks if any errors were added to the ActionErrors
object and, if so, saves the ActionErrors object to the request so the Struts
<html:errors> tag can find and display them. It also determines the forward
that control should be passed to. In case of an error we return to the input

Chapter 10. Developing Struts applications 335


page (we will soon define the input page for our actions) for correction and if
successful we progress to the forward called success.
򐂰 If an action should return null as its forward, this tells Struts that the rendering
of the page has already been performed by the action itself and that no JSP
needs to be displayed.
򐂰 Save the ListAccountsAction.java file and close the Java editor.

Note: The two commented lines (in italic) can be used to pre-select the
account number in the selection list. This way we could make sure that an
account number would always be selected. We did not want to do this here, as
we wanted to show you how to use the validate method instead.

Implement the other action classes


Implement the two action classes, AccountDetailsAction and
PerformTransactionAction, using the same method. Copy the Java code from
the \sg246956\sampcode\dev-struts\initial\actions directory and paste into
the corresponding action class you create.

When you have implemented all the components on the Web diagram, there
should be no errors in the Task view.

Before we have a fully working application we need to add a few more forwards.
We will do that using the Struts configuration file editor.

Using the Struts configuration file editor


Application Developer provides an editor for the Struts configuration file,
\WEB-INF\struts-config.xml. Using this editor you can add new form beans and
actions and customize the their attributes. You can also directly edit the XML
source file should you prefer to do it by hand instead of using the wizards.

We will use this editor to add a forward called cancel to the accountDetails and
performTransaction actions. This forward is used by the actions to determine
where to go in case the user clicks Cancel.

We also specify the input attribute for all our actions. This attribute specifies
which page should be displayed if the validate method of a form bean found
errors. Usually you want to display the input page where the user entered the
data so they can correct their entry.
򐂰 Double-click the Web Content\WEB-INF\struts-config.xml file to open the
configuration file editor.

336 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 The editor has tabs to navigate between the different Struts artifacts (actions,
form beans, global forwards, data sources) it supports.
򐂰 Make sure the Actions tab is displayed and then select the /listAccounts
action. In the Input field enter /index.jsp (Figure 10-30).

Figure 10-30 Specifying action input attribute

򐂰 Select the accountDetails action and specify /listAccounts.do as the input


attribute for this action. We recreate the list of accounts if errors occur.
򐂰 Scroll down and click New to Specify forwards. This opens the Create New
Forward dialog as shown in Figure 10-31. Enter cancel as the name and
/index.jsp as the path for this forward. Then click OK to close this window.

Note: The Redirect check box allows you to select if a redirect or forward
call should be made. A forward call keeps the same request with all
attributes it contains and just passes control over to the path specified. A
redirect call tells the browser to make a new HTTP request which creates a
new request object (and you lose any attributes set in the original request).

A forward call does not change the URL in the browser’s address field, as it
is unaware that the server has passed control to another component. With
a redirect call, however, the browser updates the URL in its address field to
reflect the requested address.

Chapter 10. Developing Struts applications 337


Figure 10-31 Creating new Forward

򐂰 Use the same method to specify /accountDetails.jsp as the input attribute


for the performTransaction action and add a new forward called cancel with a
path of /listAccounts.do.

Note: You can redirect or forward also to other actions. It does not
necessarily have to be a JSP. The cancel forward can point to either
/listAccounts.do (the action) or /listAccounts.jsp (the JSP).

Going to the JSP may require that the form bean is in the session instead
of the request.

򐂰 When done, press Ctrl-S to save the configuration file.


򐂰 Now click the XML Source tab on the editor to take a look at the Struts
configuration file we have created during this session (Figure 10-32).

338 WebSphere Studio Application Developer Version 5 Programming Guide


<struts-config>
<!-- Data Sources -->
<data-sources>
</data-sources>

<!-- Form Beans -->


<form-beans>
<form-bean name="customerInfoForm" type="itso.strutsweb.forms.CustomerInfoForm">
</form-bean>
<form-bean name="transactionForm" type="itso.strutsweb.forms.TransactionForm">
</form-bean>
</form-beans>

<!-- Global Exceptions -->


<global-exceptions>
</global-exceptions>

<!-- Global Forwards -->


<global-forwards>
</global-forwards>

<!-- Action Mappings -->


<action-mappings>
<action name="customerInfoForm" path="/listAccounts" scope="request"
type="itso.strutsweb.actions.ListAccountsAction" input="/index.jsp">
<forward name="success" path="/listAccounts.jsp"></forward>
</action>

<action name="customerInfoForm" path="/accountDetails" scope="request"


type="itso.strutsweb.actions.AccountDetailsAction"
input="/listAccounts.do">
<forward name="success" path="/accountDetails.jsp"></forward>
<forward name="cancel" path="/index.jsp"></forward>
</action>

<action name="transactionForm" path="/performTransaction" scope="request"


type="itso.strutsweb.actions.PerformTransactionAction"
input="/accountDetails.jsp">
<forward name="withdraw" path="/accountDetails.jsp"></forward>
<forward name="transfer" path="/accountDetails.jsp"></forward>
<forward name="deposit" path="/accountDetails.jsp"></forward>
<forward name="listTransactions" path="/listTransactions.jsp"></forward>
<forward name="cancel" path="/listAccounts.do"></forward>
</action>
</action-mappings>

<!-- Message Resources -->


<message-resources parameter="itso.strutsweb.resources.ApplicationResources"/>
</struts-config>

Figure 10-32 Struts configuration file (struts-config.xml)

Chapter 10. Developing Struts applications 339


As you can see, the Struts tools have defined our two form beans in the
<form-beans> section and our three actions in the <action-mappings> section.
Our JSPs, however, are not specified in the Struts configuration file, they are
completely separate form the Struts framework (only the forwarding information
is kept in the configuration file). At the end of the file is the name of the
application resources file where our texts and error messages are stored.

The Struts configuration editor does roundtrip editing, so if you edit something in
the XML view it is reflected in the other views.

The forwards we use are local to each action, meaning that only the action
associated with the forward can look it up. In the <global-forwards> section you
can also specify global forwards that are available for all actions in the
application. Normally you have a common error page to display any severe error
messages that may have occurred in your application and that prevents it from
continuing. Pages like these are good targets for global forwards and so are any
other commonly used forward. Local forwards override global forwards.
򐂰 You can now close the configuration file editor.
򐂰 As we have now added a few more forwards we should update the Web
diagram to show them as well. If the Web diagram is not open, open it by
double-clicking \Web Content\WEB-INF\strutsbank.gph. In the Web diagram
select the listAccounts action and Draw -> Draw Selected From its context
menu. Select “input” --> /index.jsp as shown in Figure 10-33 and click OK.

Figure 10-33 Selecting a forward to draw

This draws a red line from the listAccounts action back to index.jsp,
indicating the input page.
򐂰 For the accountDetails and performTransaction actions, draw both the input
and cancel paths. This draws a red line indicating the input page and a black
line indicating a normal forward for each of these two actions.
򐂰 Select the lines and drag the small dot in the middle of the line to avoid the
lines from crossing over other components in the Web diagram.

340 WebSphere Studio Application Developer Version 5 Programming Guide


When finished, you should have the Web diagram as shown in Figure 10-34.

Figure 10-34 Completed Web diagram for Struts application

򐂰 Save the Web diagram by pressing Ctrl-S.

We are now ready to test our application using the built-in WebSphere Test
Environment.

Chapter 10. Developing Struts applications 341


Notes:
򐂰 It is recommended that all requests for JSPs go through an action class so
that you have control over the flow and can prepare the view beans (form
beans) necessary for the JSP to display properly. Struts provides simple
forwarding actions that you can use to accomplish this. However, your
users can still bypass your actions and access the JSPs directly, which is
not what you want. One way of making sure that your users cannot access
the JSPs directly is to place them under the WEB-INF directory which,
according to the J2EE specifications, is not directly accessible. A good
place to put your JSPs (other than index.jsp) is \WEB-INF\jsp. However, if
you put them there, the Application Developer Struts tools do not seem to
find them either, so you will not get the same support when developing your
application. You could, however, keep your JSPs in the root of the Web
Content directory during development to get full support from Application
Developer and then— when you are getting ready to package and ship
your application—move them to a protected directory under WEB-INF. If
properly designed (and not links hard coded) it should just be a simple
search and replace action in the Struts configuration file.
򐂰 In our example we do not perform any customization on the Struts action
servlet (org.apache.struts.action.ActionServlet). If you have to do any
initialization (for example initialize data sources) you would want to create
your own action servlet, extending the ActionServlet class, and override
the init and destroy methods. You would then also modify the
\WEB-INF\web.xml file and replace the name of the Struts action servlet
with the name of your action servlet class.
򐂰 When adding Struts 1.1 beta 2 support the JAR file jdbc2_0-stdext.jar is
added to the Web Content\WEB-INF\lib directory. This file contains classes
from the javax.sql package and comes with Struts 1.1. However, these
classes are also shipped with WebSphere Application Server. If the Struts
supplied classes are in the lib directory, they take precedence over the
WebSphere classes. We have seen problems with these classes and using
WebSphere data sources. If you experience any JDBC-related problems,
try removing this file and see if it helps.

Testing the application


To run the application using Application Developer’s built-in test environment,
select Run on Server from the context menu of the ItsoProGuideStrutsWeb
project. When launched, it should look similar to the RedBank application that it
is based on.

342 WebSphere Studio Application Developer Version 5 Programming Guide


A sample run is shown in Figure 10-35.

Figure 10-35 Sample run of the Struts application

Chapter 10. Developing Struts applications 343


One thing that differs, however, is the response you get if you do not enter the
requested data. For example, if you select to transfer money between two
accounts, but you do not enter either the amount or the destination account
number, the validate method of the transactionForm form bean will report these
two errors and you will be returned to the accountDetails.jsp page to correct
the problem (Figure 10-36).

Figure 10-36 Sample run of the Struts application with errors

Summary
In this chapter we built a simple Web application using the Struts framework. We
reused the model from the Web application we built in Chapter 7, “Developing
Web applications” on page 179, but replaced the controller and view parts with
the Struts framework.

We tried to use Application Developer’s Struts tools and wizards as much as


possible to show you what they can do.

344 WebSphere Studio Application Developer Version 5 Programming Guide


11

Chapter 11. Developing XML


applications
This chapter introduces you to Application Developer’s XML capabilities and
discusses how to work with some of these XML features.

Note that some parts of this chapter have been taken from an existing IBM
Redbook:
The XML Files: Development of XML/XSL Applications Using WebSphere
Studio Version 5, SG24-6586.

This book provides more detailed information and examples of developing


XML/XSL applications using Application Developer.

This chapter describes the following topics:


򐂰 XML overview and technologies
򐂰 Application Developer XML tools

© Copyright IBM Corp. 2003. All rights reserved. 345


XML overview and technologies
Today, the extensible markup language (XML) is starting to become a key piece
of software infrastructure. The main idea is extremely simple. It is a text based
language like HTML, but is rigidly enforced, and therefore, can be built upon
easily. XML was designed to describe data and to focus on the data, unlike
HTML which was designed to display data. XML was created to structure and
store data.

XML and XML processor


XML is tag-based, but XML tags are not predefined in XML. You have to define
your own tags. XML uses a document type definition (DTD) or an XML schema to
describe the data.

XML documents follow strict syntax rules. For more information regarding XML
consult the W3C Web Site:
http://www.w3.org/XML

See the following Web Site for XML syntax rules:


http://www.w3.org/TR/rdf-syntax-grammar/

However, to create, read and update XML documents, you need an XML
processor or parser. At the heart of every XML application is an XML processor
that parses an XML document, so that the document elements can be retrieved
and transformed into a presentation understood by the target client. The other
responsibility of the parser is to check the syntax and structure of the XML
document.

There are a number of validating or non-validating parsers. The following list


shows some of the most common processors and parsers:
򐂰 Xerces (XML parsers)
򐂰 Xalan (XSLT style sheet processors)
򐂰 IBM XML Parser for Java (XML4J)
򐂰 SAX2
򐂰 JAXP

DTD and XML schema


DTDs and XML schemas are both used to describe structured information,
however, in the last two years the acceptance of XML schemas has gained
momentum. Both DTDs and schemas are building blocks for XML documents
and consist of elements, tags, attributes, and entities.

346 WebSphere Studio Application Developer Version 5 Programming Guide


XML schema is more powerful than DTD. Here are some advantages of XML
schemas over DTDs:
򐂰 They define data types for elements and attributes, and their default and fixed
values. Some of the data types can be of string, decimal, integer, boolean,
date, time, or duration.
򐂰 They apply restrictions to elements, by stating minimum and maximum
values, (for example, on age from 1 to 90 years), or restrictions of certain
values (for example, redbooks, residencies, redpieces with no other values
accepted, such as in a drop-down list box). Restrictions can also be applied to
types of characters and their patterns (for example, only accepting values ‘a’
to ‘z’ and also specifying that only three letters can be accepted). The length
of the data can also be specified (for example passwords must be between 4
They and 8 characters.)
򐂰 They specify complex element types. Complex types may contain simple
elements and other complex types. Restrictions can be applied to the
sequence and the frequency of their occurrences. These complex types can
then be used in other complex type elements.
򐂰 Since schemas are written in XML, they are also extensible. This also implies
that the learning curve for learning another language has been eliminated, the
available parsers need not be enhanced, transformation can be carried out
using XSLT, and also, its manipulation can be carried out using XML DOM.
򐂰 With XML schemas being extensible, they can be re-used in other schemas,
we can reference multiple schemas from the same document, and we also
have the ability to create our own data types from standard data types.

Note: DTDs consists of elements such as text strings, text strings with other
child elements, and a set of child elements. DTDs offer limited support for
types and namespaces, and the syntax in DTDs is not XML.

Schema and style using XSLT and XSL


The extensible style language (XSL) is a language defined by the W3C for
expressing style sheets. It has three parts:
򐂰 XSL transformations (XSLT), which is used for transforming XML documents.
򐂰 the XML path language (XPath), which is a language used to access or refer
to parts of an XML document.
򐂰 XSL-FO, which is a vocabulary for specifying formatting semantics.

A transformation in XSLT must be a well-formed document and must conform to


the namespaces in XML, which can contain elements that may or may not be

Chapter 11. Developing XML applications 347


defined by XSLT. XSLT-defined elements belong to a specific XML namespace. A
transformation in XSLT is called a style sheet.

XSL uses an XML notation and works on two principles: pattern matching and
templates. It operates on an XML source document and parses it into a source
tree, it applies the transformation of the source tree to a result tree, and then it
outputs the result tree to a specified format. In constructing the result tree, the
elements can be reordered or filtered, and also, other structures can be added.
The result tree can be completely different from the source tree.

XML namespaces
Namespaces are used when there is a need for elements and attributes of the
same name to take on a different meaning depending on the context in which
they are used. For instance, a tag called <TITLE> takes on a different meaning,
depending on whether it is applied to a person or a book.

If both entities (a person and a book) need to be defined in the same document,
for example, in a library entry which associates a book with its author, we need
some mechanism to distinguish between the two and apply the correct semantic
description to the <TITLE> tag whenever it is used in the document.

Namespaces provide the mechanism that allows us to write XML documents


which contain information relevant to many software modules.

XPath
The XML path language (XPath) is used to address parts of an XML document.
An XPath expression can be used to search through an XML document, and
extract information from the nodes (any part of the document, such as an
element or attribute) in it. There are four different kinds of XPath expressions:
򐂰 Boolean—Expression type with two possible values
򐂰 Node set—Collection of nodes that match an expression's criteria, usually
derived with a location path
򐂰 Number—Numeric value, useful for counting nodes and for performing
simple arithmetic
򐂰 String—Text fragment that may come from the input tree, processed or
augmented with general text

An XPath expression returns a certain node set, which is a collection of nodes.


The following is a sample XPath expression:
/ACCOUNT_TABLE/ACCOUNT/ACCID

348 WebSphere Studio Application Developer Version 5 Programming Guide


This expression selects any elements named ACCID (account ID), which are
children of ACCOUNT elements, which are children of ACCOUNT_TABLE elements,
which are children of the document root.

Application Developer XML tools


Application Developer provides a comprehensive visual XML development
environment. The tool set includes components for building DTDs, XML
schemas, XML, and XSL files. The XML development tools of Application
Developer are:
򐂰 XML editor
򐂰 XML schema editor
򐂰 XSL editor
򐂰 DTD editor
򐂰 XPath expression wizard
򐂰 XSL debugging and transformation
򐂰 XML to XML mapping editor
򐂰 XML and relational data
򐂰 Relational database to XML mapping (visual DAD builder)

Only some of these editors are described in these chapter. Refer to Application
Developer’s help manual for more detailed information regarding XML tools and
editors.

Tools demonstrated in this chapter


This chapter covers only a few XML tools of Application Developer. We
demonstrate how to create XML files, and we introduce you to some of
Application Developers XML generators. The following topics are discussed:
򐂰 Creating a new XML file from scratch
򐂰 Creating an XML schema
򐂰 Generating a DTD from XSD
򐂰 Generating an XML file from an XML schema
򐂰 Creating an XSL file
򐂰 Transforming XML files
򐂰 Debugging XSL
򐂰 Generating JavaBeans from DTD or XSD

Note: We do not create a fully XML enabled application here. This chapter
only shows some XML capabilities of Application Developer where we create
and work with XML files.

Chapter 11. Developing XML applications 349


Setting up your sample project
To demonstrate some of Application Developer’s XML tools, we set up a new
project. Therefore, we created a new Web project called ItsoProGuideXmlWeb,
part of the ItsoProGuide enterprise application. You can consult Chapter 7,
“Developing Web applications” on page 179 to learn how to create a new Web
project.

Once this is done, we create a Java package and name it itso.xml (see
“Creating Java packages” on page 99 for more information).

We also create a new folder in the WEB-INF folder and name the folder xml where
we store an XML schema file. The new Web project skeleton displayed in the
J2EE Navigator view should now look like shown in Figure 11-1.

Figure 11-1 Sample project skeleton

Creating a new XML file from scratch


In this section we create a new XML file from scratch to demonstrate the
capabilities of the XML editor. It can be used to edit the contents of new XML
files, either created from scratch or from existing DTDs, or XML schemas. You
can also use it to edit XML files, associate them with DTDs or schemas, and
validate them.

To create a new file from scratch, use the New XML wizard. Switch to the XML
perspective, select File -> New -> XML and select the Create XML file from
scratch option from the dialog and click Next (Figure 11-2).

350 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 11-2 Create new XML File dialog

In the next dialog, make sure that the project ItsoProGuideXmlWeb with the folder
Web Content\xml has been selected, type a name in the File name field (in this
example we use the default name NewFile.xml) and click Finish. The XML file is
created and the XML editor is automatically opened.

Refer to “XML perspective” on page 67 for a description of the views, including


the XML editor. The XML editor has two main tabs, Design and Source
(Figure 11-3):

Figure 11-3 XML editor views

You can use the Source view to view and work with a file’s source code directly.
The Source view has many text editing features, such as:
򐂰 Syntax highlighting
򐂰 Unlimited undo and redo of changes
򐂰 Content assist
򐂰 User-defined macros
򐂰 Node selection indicator

Chapter 11. Developing XML applications 351


The Design view displays the XML document as a tree, enabling you to
manipulate the document by adding, removing, and editing tree nodes. This also
makes navigation easier. In the left column of the Design view, we see the
elements, attributes, and other nodes of the XML document's tree. The right
column is used to display the values associated with these nodes.

After you have created the new XML file, add some elements with values to the
XML file. Figure 11-4 shows the code of the file including the root element named
ACCOUNT and seven child elements.

<?xml version="1.0" encoding="UTF-8"?>


<ACCOUNT>
<ACCID>101-1001</ACCID>
<BALANCE>80.00</BALANCE>
<INTEREST>4</INTEREST>
<ACCTYPE>CHECKING</ACCTYPE>
<DISCRIMINATOR>C</DISCRIMINATOR>
<OVERDRAFT>200.00</OVERDRAFT>
<MINAMOUNT></MINAMOUNT>
</ACCOUNT>

Figure 11-4 Sample XML code

To add an element to an XML file, you can do any of these things:


򐂰 Add the element by typing it into the source editor
򐂰 Open the context menu from the document type declaration tag in the Design
view and select Add After -> New Element
򐂰 Open the context menu from the document type declaration tag in the Outline
view and select Add After -> New Element

Figure 11-5 shows the context menu of the document type declaration tag.

Figure 11-5 Add New Element to the XML file

352 WebSphere Studio Application Developer Version 5 Programming Guide


A new dialog box comes up and you have to enter an element name. In this
example we enter ACCOUNT as our root element for this XML file (Figure 11-6).

Figure 11-6 New Element dialog

To add elements to the ACCOUNT element, select the element and Add Child ->
New Element. Add the seven child elements to the ACCOUNT element.

Once you have added all elements to the XML file, you can use the Design view
to add its values. Figure 11-7 shows the Design view with the highlighted ACCID
element. You can see that a value for this element has been entered in the
second column.

Figure 11-7 XML Design view for sample file

Creating an XML schema


In this section we create a new XML schema file based on the ACCOUNT table of
the sample DB2 database.

See also “Generate DDL and XML schema files” on page 151 for more
information about creating XML schema files for data objects.

Chapter 11. Developing XML applications 353


Generating an XML schema
To create the XML schema file for a table, simply follow these steps:
򐂰 Open the Data perspective.
򐂰 While connected to the EJBBANK sample database (select the Con2 connection
and Reconnect from the context menu), open the context menu of the table
ITSO.ACCOUNT in the DB Servers view and select Generate XML Schema.
򐂰 Select the folder Web Content/WEB-INF/xml of the ItsoProGuideXmlWeb
project, leave the suggested name ACCOUNT.xsd in the File name field and
click Finish to create the XML schema file.

The source editor opens the newly created schema file ACCOUNT.xsd
(Example 11-1).

Example 11-1 XML schema file ACCOUNT.xsd


<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ibm.com/EJBBANK/ITSO"
xmlns:EJBBANKITSO="http://www.ibm.com/EJBBANK/ITSO">
<element name="ACCOUNT_TABLE">
<complexType>
<sequence>
<element ref="EJBBANKITSO:ACCOUNT" minOccurs="0"
maxOccurs="unbounded"/>
</sequence>
</complexType>
<key name="ACCOUNT_PRIMARYKEY">
<selector xpath="EJBBANKITSO:ACCOUNT"/>
<field xpath="ACCID"/>
</key>
</element>
<element name="ACCOUNT">
<complexType>
<sequence>
<element name="ACCID">
<simpleType>
<restriction base="string">
<length value="8"/>
</restriction>
</simpleType>
</element>
<element name="BALANCE" type="decimal"/>
<element name="INTEREST" type="integer"/>
<element name="ACCTYPE">
<simpleType>
<restriction base="string">
<length value="8"/>

354 WebSphere Studio Application Developer Version 5 Programming Guide


</restriction>
</simpleType>
</element>
<element name="DISCRIMINATOR">
<simpleType>
<restriction base="string">
<length value="1"/>
</restriction>
</simpleType>
</element>
<element name="OVERDRAFT" type="decimal"/>
<element name="MINAMOUNT" type="decimal"/>
</sequence>
</complexType>
</element>
</schema>

Close the Data perspective and switch back to the XML perspective as we
continue with the sample using the XML features.

XML schema editor


Application Developer allows you to view and edit XML and XML related files in
different views. For an XML schema you can use the Outline view and the XML
schema editor with three tabs:
򐂰 Design
򐂰 Source
򐂰 Graph

The Graph view is used for working with schema files and provides a graphical
way to browse and edit your schema. You can click the + or - signs to navigate
through the schema and learn more about its structure (Figure 11-8).

You can use the pop-up menu for each node to add content that is appropriate.

Chapter 11. Developing XML applications 355


Figure 11-8 Graph view

XML generators
Application Developer provides a number of XML generators. Using these tools,
you can generate XML schemas, XML files from other components (for example,
JavaBeans or an SQL statement), and also generate components from XML files
and XML schemas. Here is a list of XML generators:
򐂰 Generating an XML schema from a DTD
򐂰 Generating JavaBeans from a DTD
򐂰 Generating an HTML form from a DTD
򐂰 Generating an XML file from a DTD
򐂰 Generating a DTD file from an XML schema
򐂰 Generating JavaBeans from an XML schema
򐂰 Generating XML/XSL from JavaBeans
򐂰 Generating an XML file from an XML schema
򐂰 Generating a relational table definition from an XML schema
򐂰 Generating an XML schema from a relational table
򐂰 Generating HTML documentation from XML schemas
򐂰 Creating a DTD file from one or more XML files
򐂰 Creating an XML schema file from an XML file

356 WebSphere Studio Application Developer Version 5 Programming Guide


In the following sections we demonstrate a few of these generators.

Generating a DTD from XSD


Application Developer offers the developer the ability to transform your XSD file
into a DTD file or a DTD file into an XSD file.

We use the new XSD file to generate a DTD. Having the ACCOUNT.xsd file, we can
generate the corresponding DTD file using the generator. To demonstrate how to
create a DTD file from an existing XSD file, follow these steps:
򐂰 Select the file ACCOUNT.xsd.
򐂰 Select Generate -> DTD from the context menu.
򐂰 Select the folder to store the file. In this example we use the Web
Content\WEB-INF\xml folder in our project.
򐂰 Click Finish.

The DTD file ACCOUNT.dtd is created and opened in editor. Based on a DTD file,
you can create XML, HTML, XML schema files, and also JavaBeans. Figure 11-9
shows the code of the DTD file ACCOUNT.dtd.

<?xml version="1.0" encoding="UTF-8"?>


<!ELEMENT ACCOUNT_TABLE (ACCOUNT*)>
<!ELEMENT ACCOUNT
(ACCID,BALANCE,INTEREST,ACCTYPE,DISCRIMINATOR,OVERDRAFT,MINAMOUNT)>
<!ELEMENT BALANCE (#PCDATA)>
<!ELEMENT INTEREST (#PCDATA)>
<!ELEMENT OVERDRAFT (#PCDATA)>
<!ELEMENT MINAMOUNT (#PCDATA)>
<!ELEMENT ACCID (#PCDATA)>
<!ELEMENT ACCTYPE (#PCDATA)>
<!ELEMENT DISCRIMINATOR (#PCDATA)>

Figure 11-9 DTD file ACCOUNT.dtd

Validate XML files


Another useful feature is the incremental validation feature. At any point during
your development of an XML document, you can invoke the validate process to
validate the file.

Validating files means that Application Developer determines whether the current
state of the file is semantically valid. Any errors will be displayed in the Tasks

Chapter 11. Developing XML applications 357


view. Application Developer provides the following validators for the XML
technology:
򐂰 DTD validator
򐂰 XML schema validator
򐂰 XML validator
򐂰 XSL validator

You could change the validation settings of Application Developer by selecting


Window -> Preferences and select Validation from the left pane. A new page
displays where you can change options regarding validation (Figure 11-10).

Figure 11-10 Validation preferences

You can start validating a file by opening its context menu and selecting Validate
<file type>, where <file type> is the currently selected file. If you want to validate
the ACCOUNT.xsd schema file, simply open the context menu and select Validate
XML Schema (Figure 11-11).

358 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 11-11 Validate XML schema

A new dialog box opens and informs you if the file is valid or not.

Generating an XML file from an XML schema


To generate an XML file from an XML schema, open the context menu from the
XML schema file ACCOUNT.xsd and select Generate -> XML File.

A new dialog comes up where you can change the location and the file name for
the XML file. Select the WEB-INF\xml folder and use the suggested name
ACCOUNT.xml and click Next to open the Create XML File dialog (Figure 11-12).

Chapter 11. Developing XML applications 359


Figure 11-12 Create XML File from XML schema dialog

Select ACCOUNT_TABLE as the root element of the XML file and select Create
required and optional content to create optional information in addition to the
minimum amount of information.

The XML schema information section contains information about the target
namespace of the XML schema, its prefix, and the schema location.

Click Finish to create the XML file. The XML file is created and opened in the
editor. Figure 11-13 shows the source of the file.

<?xml version="1.0" encoding="UTF-8"?>


<EJBBANKITSO:ACCOUNT_TABLE xmlns:EJBBANKITSO="http://www.ibm.com/EJBBANK/ITSO"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ibm.com/EJBBANK/ITSO WEB-INF/xml/ACCOUNT.xsd ">
<EJBBANKITSO:ACCOUNT>
<ACCID>ACCID</ACCID>
<BALANCE>0.0</BALANCE>
<INTEREST>0</INTEREST>
<ACCTYPE>ACCTYPE</ACCTYPE>
<DISCRIMINATOR>DISCRIMINATOR</DISCRIMINATOR>
<OVERDRAFT>0.0</OVERDRAFT>
<MINAMOUNT>0.0</MINAMOUNT>
</EJBBANKITSO:ACCOUNT>
</EJBBANKITSO:ACCOUNT_TABLE>

Figure 11-13 ACCOUNT.xml file: not valid

360 WebSphere Studio Application Developer Version 5 Programming Guide


After creating the XML file, the Tasks view shows three errors, because the
values of the elements ACCID, ACCTYPE, and DICRIMINATOR are not valid.

The reason for this is that the default values added to the new XML file do not
match with the restrictions defined in the XML schema file ACCOUNT.xsd.

Change the values of the three elements as shown in Figure 11-14 and save the
file. The changed lines are highlighted in bold.

<?xml version="1.0" encoding="UTF-8"?>


<EJBBANKITSO:ACCOUNT_TABLE
xmlns:EJBBANKITSO="http://www.ibm.com/EJBBANK/ITSO"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.ibm.com/EJBBANK/ITSO
WEB-INF/xml/ACCOUNT.xsd ">
<EJBBANKITSO:ACCOUNT>
<ACCID>101-1001</ACCID>
<BALANCE>0.0</BALANCE>
<INTEREST>0</INTEREST>
<ACCTYPE>CHECKING</ACCTYPE>
<DISCRIMINATOR>C</DISCRIMINATOR>
<OVERDRAFT>0.0</OVERDRAFT>
<MINAMOUNT>0.0</MINAMOUNT>
</EJBBANKITSO:ACCOUNT>
</EJBBANKITSO:ACCOUNT_TABLE>

Figure 11-14 ACCOUNT.xml file: valid

After you have generated an XML file you could, based on that file, generate an
XML application (for example an XML validation application by using the context
menu of the XML file and select Generate -> XML Application), a DTD or XML
schema file, and even data for an existing databases.

Note: Application Developer 5 also introduces the XML Signature wizard. You
can create a digital signature for your XML file using the XML Signature
wizard. You must either use an existing certificate or create a new certificate to
create a digital signature. To launch the XML Signature wizard, open the
context menu of an XML file and select XML Security -> Digital Signature.

Chapter 11. Developing XML applications 361


Creating an XSL file
An XSL file is a style sheet that can be used to transform XML documents into
other document types and to format the output.

Next we create a new XSL file from scratch and transform the XML document
ACCOUNT.xml by using the XSL style sheet to generate an HTML file.

To create a new XSL file, follow these instructions:


򐂰 In the Workbench, select File -> New -> Other -> XML -> XSL and click Next.
򐂰 A new dialog comes up where you select the project and folder for the new
XSL file and enter a file name (Account.xsl) in the appropriate field as shown
in Figure 11-15. Note, that the name of the XSL file must have a .xsl
extension.

Figure 11-15 New XSL File dialog

򐂰 Click Next to select an XML file and associate it with the XSL file. By
associating an XSL file explicitly with an XML file, you do not have to specify
the XML file every time you want to transform or debug the XML and XSL files
(Figure 11-16).

362 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 11-16 Select XML file for XSL dialog

Click Finish to create the file. The new XSL file is opened in the XSL editor.
Figure 11-17 shows the skeleton of the file.

<?xml version="1.0" encoding="UTF-8"?>


<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0"
xmlns:xalan="http://xml.apache.org/xslt">
</xsl:stylesheet>

Figure 11-17 Skeleton of a new XSL file

One way to add code to the XSL file is to type it directly into the source editor, but
you can also use the XSL wizards to add code to the XSL. These wizards can be
found by expanding the XSL menu in Application Developer as shown in
Figure 11-18.

Chapter 11. Developing XML applications 363


XSL menu with
code wizards

Figure 11-18 XSL menu

To prepare the style sheet that can be used to generate a HTML file, we have to
add some HTML code. First we add an HTML template. This basically generates
an HTML code skeleton and add it to the XSL file.

To use the HTML Template wizard, place the cursor in a new line right after the
stylesheet tag (Figure 11-19) and select XSL -> HTML Template from the menu
bar. Note that Application Developer immediately adds the HTML code to the file
without bringing up a dialog.

Figure 11-19 Place cursor in XML editor

A new code fragment has been added to the XSL file, as shown in Figure 11-20.

364 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 11-20 HTML template code in XSL file

Next, delete the <xsl:apply-templates/> line from the code and place the cursor
in this line (Figure 11-21).

Figure 11-21 XSL code ready for insert

Note: In the absence of a select attribute, the xsl:apply-templates


instruction processes all of the children of the current node including text
nodes. Next we add a select attribute, which can be used to process nodes
selected by an expression instead of all children. Therefore we remove this
instruction.

Chapter 11. Developing XML applications 365


In the menu bar select XSL -> HTML Table to bring up the HTML Table wizard to
add a HTML table that displays the content of an XML file in a table when
applying the XSL to the XML file (Figure 11-22).

Note: As we have specified the corresponding XML file, when creating the
style sheet, Application Developer does not bring up the XML file selection
dialog. This would be the case if no XML file had been selected when creating
new style sheets.

Figure 11-22 Add a table to the XSL

Expand EJBBANKITSO:ACCOUNT_TABLE and select the EJBBANKITSO:ACCOUNT node.


We want to display all accounts later when we apply this style sheet. Also select
the check box Include Header. This option includes a for each element inside
the content node.

366 WebSphere Studio Application Developer Version 5 Programming Guide


Note: By selecting the nodes in the XSL tree, the preview pane at the bottom
of the dialog changes accordingly. There you can verify the HTML code which
would be added to the XSL file when confirming the dialog.

Click Next to open the dialog where you can change the properties of the HTML
table. You can change properties like color, border, and width of the table. In this
example we are not doing this, and we click Finish to add the table to the XSL
file. Figure 11-23 shows the code which is added to the XSL file.

<table>
<tr>
<th>ACCID</th>
<th>BALANCE</th>
<th>INTEREST</th>
<th>ACCTYPE</th>
<th>DISCRIMINATOR</th>
<th>OVERDRAFT</th>
<th>MINAMOUNT</th>
</tr>
<xsl:for-each select="/EJBBANKITSO:ACCOUNT_TABLE/EJBBANKITSO:ACCOUNT">
<tr>
<td><xsl:value-of select="ACCID"/></td>
<td><xsl:value-of select="BALANCE"/></td>
<td><xsl:value-of select="INTEREST"/></td>
<td><xsl:value-of select="ACCTYPE"/></td>
<td><xsl:value-of select="DISCRIMINATOR"/></td>
<td><xsl:value-of select="OVERDRAFT"/></td>
<td><xsl:value-of select="MINAMOUNT"/></td>
</tr>
</xsl:for-each>
</table>

Figure 11-23 Added HTML table to style sheet

Note: As this is just a simple example of a style sheet, it has not been nicely
formatted. You can do this by changing the HTML tags in the Source view
appropriate to your needs.

Now we finished creating a simple XSL style sheet which is based on the
ACCOUNT.xml file. By applying this file to the XML file, a list of all accounts found in
the XML file is generated.

Chapter 11. Developing XML applications 367


Transforming XML files
You can apply an XSL file to an XML file and create either a new XML file, a new
HTML file, or a new text file.

Note: You should only apply an XSL file to an XML file and attempt to create
an HTML file if the style sheet you are using is designed to provide HTML
output. Otherwise, an empty or incorrect HTML file will be created.

If you select only an XSL file or XML file, and select Apply XSL from the pop-up
menu, a wizard will open, prompting you to select an XML or XSL file from the
Workbench or from the Internet using HTTP.

If you select an XML or XSL from HTTP, you must specify its URI. Only an XSL
transformation will be run on the selected file. Because the file is not available in
the Workbench, the debugger cannot be opened. It can only be transformed and
the results displayed.

To apply an XSL file to an XML file and create a new HTML file, select an XML
and an XSL file (press the CTRL key to select both files) and Apply XSL -> As
XML (context).

Figure 11-24 shows the selected files and the context menu where you can
transform the file.

Figure 11-24 Apply XSL as HTML

368 WebSphere Studio Application Developer Version 5 Programming Guide


The XSL Debug perspective opens and now you can either view the generated
file or debug the XSL style sheet.

If you now go back to the XML perspective, you see that Application Developer
has created a new HTML file and named it ACCOUNT_Acount_transform.html.
When you open the HTML file in the Design tab it should look like Figure 11-25.

Figure 11-25 HTML file design

By changing the HTML tags in the style sheet, you can format this HTML file
more nicely.

Debugging XSL
Application Developer’s XSL debugging and transformation tool records the
transformation that is generated by the Xalan processor. The Xalan processor is
an XSLT processor that transforms XML files into HTML, text, or other XML file
types.

For more information on the Xalan processor, refer to the following Apache Web
site:
http://xml.apache.org/xalan-j/

The XSL debugging and transformation tool enables you to visually step through
an XSL transformation script. Figure 11-26 shows the XSL Debug perspective
with its views.

Chapter 11. Developing XML applications 369


Figure 11-26 XSL Debug perspective

The Sessions view displays any sessions you have run (that is, any XSL files you
have applied to XML files). You can use the Sessions view to step through an
XSL transformation script, highlighting the transformation rules as they are fired.

The Sessions view provides the following actions:


򐂰 To step forward, click the Step forward icon
򐂰 To step backwards, click the Step backward icon
򐂰 To reset the file, click the Restart from beginning icon
򐂰 To run to breakpoint, click the Run to breakpoint icon
򐂰 To open the transformation output, which is the result file, in a Web browser,
click the Open the browser on the transformation result icon

You can click the Globe icon to view the result HTML file. Again, if you switch
back to the XML perspective you notice that a new file named, in this case,
named ACCOUNT_Account_transform.html has been created.

370 WebSphere Studio Application Developer Version 5 Programming Guide


Generating JavaBeans from DTD or XSD
In this section we generate JavaBeans from the existing XML schema file. To do
this, open the context menu of the ACCOUNT.xsd file and select Generate -> Java
Beans (Figure 11-27).

Figure 11-27 Generate Java Beans dialog

The Java root folder has to be specified in the Container field. In the Package
field we enter itso.xml as we would like to store the JavaBeans in this package.

In the Root element field select ACCOUNT and make sure the check box Generate
sample test program is selected. This generates a runnable JavaBean which
shows you how to use the beans you have created.

Click Finish to generate the JavaBeans. The following files are created in the
itso.xml package:
򐂰 ACCOUNT_TABLE.java—represents the complex type <ACCOUNT_TABLE>.
򐂰 ACCOUNTFactory.java—provides methods for creating Java beans for
elements in the XML document.
򐂰 ACCOUNT.java—represents the complex type <ACCOUNT>.
򐂰 Sample.java—creates and saves an XML document, loads the XML
document and prints its content in the Console view

Next, switch to the Java perspective and modify the createACCOUNT method of the
Sample.java file and change the parameter of the setACCID, setACCTYPE, and
setDISCRIMINATOR statements as shown in Figure 11-28.

Chapter 11. Developing XML applications 371


Without the changes you get three errors displayed in the Tasks View when
running this sample class, because these elements (ACCID, ACCTYPE, and
DISCRIMINATOR) would not match with the corresponding schema file.

void createACCOUNT()
{
iACCOUNT.setACCID("101-1001");
iACCOUNT.setBALANCE("0.0");
iACCOUNT.setINTEREST(0);
iACCOUNT.setACCTYPE("Checking");
iACCOUNT.setDISCRIMINATOR("C");
iACCOUNT.setOVERDRAFT("0.0");
iACCOUNT.setMINAMOUNT("0.0");
}

Figure 11-28 createACCOUNT method of the Sample.java file

Now you can run the sample class. See “Running your programs” on page 103
for more information about how to run a Java application.

Note that after running the sample application a new file, ACCOUNTSample.xml, is
created in the Web Content\WEB-INF\xml folder. This file contains the element
values specified in the createACCOUNT method of the sample Java file.

Tip: You have to select the xml folder and Refresh (context) to see the
generated file.

Summary
In this chapter we have explained and demonstrated some XML tools of
Application Developer. As the XML topic is to complex to be covered in only one
chapter, we could not demonstrate everything Application Developer provides.

We have shown how to create a new XML file, a new XSL style sheet, and how to
generate an XML schema based on a relational database table.

More information
In the IBM Redbook The XML Files: Development of XML/XSL Applications
Using WebSphere Studio Version 5, SG24-6586, more detailed information is
provided regarding developing XML/XSL applications using Application
Developer. It also contains examples using Application Developer Version 5.

372 WebSphere Studio Application Developer Version 5 Programming Guide


12

Chapter 12. Developing EJB applications


This chapter introduces the Enterprise JavaBeans and shows Application
Developer’s support for creating, maintaining, and testing such components.

In this chapter we develop a few entity beans, relationships between the entity
beans, a session bean, and a front-end Web application.

This chapter provides only a condensed description of the EJB architecture and
a few examples. For complete coverage of EJBs, refer to the IBM Redbook, EJB
2.0 Development with WebSphere Studio Application Developer, SG24-6819.

© Copyright IBM Corp. 2003. All rights reserved. 373


Introduction
Enterprise JavaBeans (EJB) is an architecture for server-side, component-based
distributed enterprise applications written in Java.

Since its introduction a few years ago, the technology has gained momentum
among platform providers and enterprise development teams. This is because
the EJB component model simplifies the development of business components
that are:
򐂰 Secure—Certain types of applications have security restrictions that have
previously made them difficult to implement in Java. For example, certain
insurance applications must restrict access to patient data in order to meet
regulatory guidelines. Until the advent of enterprise beans, there was no way
to restrict access to an object or method by a particular user. Previously,
restricting access at the database level, and then catching errors thrown at
the JDBC level, or by restricting access at the application level by custom
security code, would have been the only implementation options.
However, enterprise beans now allow method-level security on any enterprise
bean or method. Users and user groups can be created which can be granted
or denied execution rights to any EJB or method. In WebSphere, these same
user groups can be granted or denied access to Web resources (servlets,
JSPs and HTML pages), and the user IDs can be in a seamless way passed
from the Web resources to the EJBs by the underlying security framework.
Not only that, but the authenticated credentials may also be forwarded to
other systems, possibly legacy systems (compatible LTPA clients).
򐂰 Distributed—Enterprise JavaBeans automatically provide distribution
capabilities to your application, allowing for the building of enterprise-scale
systems. In short, this means that your system’s modules can be deployed to
many different physical machines and many separate OS processes to
achieve your performance, scalability, and availability requirements. Better
yet, you may start small with just a single process and grow to as many
different machines as you want without ever having to touch your code.
򐂰 Persistent—Making an object persistent means preserving its state (the
values of its variables) even after the termination of the system that created
that object.
In most cases, the state of a persistent object is stored in a relational
database. Unfortunately, the OO and relational paradigms differ a lot from
each other. Relational models have limited modeling capabilities, for they
have no way to represent behavior, encapsulation, or complex relationships
like inheritance. Additionally, SQL data types do not exactly match Java data
types, leading to conversion problems. All these problems may be
automatically solved when using EJBs.

374 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Transactional—Transactions give us four fundamental guarantees: atomicity,
consistency, isolation and durability (ACID). Atomicity means that delimited
sets of operations have to be executed as a single unit of work. If any single
operation fails, the whole set must fail as well. Consistency then guarantees
us that no matter what the transaction outcome is, the system is going to be
left in a consistent state. Isolation means that even though you may have
many transactions being performed at the same time, your objects will be
under the impression that these transactions occur one after the other. Finally,
durability means that the effects of transactions are to be persistent. Once
committed, they cannot be rolled-back.
Enterprise beans support multiple concurrent transactions with commit and
rollback capabilities across multiple data sources in a full two-phase
commit-capable environment for distributed transactions.
򐂰 Scalable—Over the past several years customers have found that fat-client
systems simply do not scale to the thousands or millions of users that
Web-based systems may have. At the same time, software distribution
problems have led to a desire to “trim down” fat clients. The 24-hour,
seven-day-a-week nature of the Web has also made uptime a crucial issue for
businesses. However, not everyone needs a system designed for 24x7
operation or that is able to handle millions of concurrent users. We should be
able to design a system so that scalability can be achieved without sacrificing
ease of development, or standardization.
So, what customers need is a way to write business logic that can scale to
meet these kinds of requirements. WebSphere’s EJB support can provide this
kind of highly scalable, highly available system. It does this by utilizing the
following features:
– Object caching and pooling—WebSphere Application Server
automatically pools enterprise beans at the server level, reducing the
amount of time spent in object creation and garbage collection. This
results in more processing cycles being available to do real work.
– Workload optimization at server— WebSphere Application Server
Network Deployment features EJB server cluster management. Using
Network Deployment, you can create server groups that span nodes. In
addition, you can configure and run multiple instances (called clones) of a
WebSphere server on one machine, taking advantage of multiprocessor
architectures. You can administer a set of nodes running WebSphere
servers using a single administration facility. A setup using multiple nodes
improves availability and prevents a single point of failure in the application
server.
– Cloning supports automatic failover— With several clones available to
handle requests, it is more likely that failures will not damage throughput
and reliability. With clones distributed to various nodes, an entire machine

Chapter 12. Developing EJB applications 375


can fail without producing devastating consequences. All of these features
happen without specifically being programmed into the system. No
changes to the server-side code are necessary to take advantage of this
kind of scalability.
򐂰 Portable—A key issue nowadays is achieving platform and vendor
independence. The EJB architecture, which is an industry standard
component architecture, can help achieve this goal. EJBs developed for the
J2EE platform can be deployed to any compliant application servers. This
promise has been demonstrated at the June 1999 JavaOne conference
where the same car dealer application was deployed on multiple application
servers, from multiple vendors. While in the short-term it is often easier and
faster to take advantage of features that may precede standardization,
standardization provides the best long-term advantage.

The architecture reduces the complexity of developing business components by


providing automatic (non-programmatic) support for such system level services,
thus allowing developers to concentrate on the development of business logic.
Such focus can bring an amazing competitive advantage to businesses.

Figure 12-1 shows a view of the EJB architecture.

Remote
Client
Remote View

EJB EJB
Home Object

EJB
Local
Home
Local EJB Component
Client EISs
EJB
Local
Object Container

Local View EJB Server

Java Virtual Machine

Figure 12-1 View of the EJB architecture

In the sections that follow we briefly explain each of these elements.

376 WebSphere Studio Application Developer Version 5 Programming Guide


EJB server
An EJB server is the part of an application server that hosts EJB containers. It is
sometimes referred to as an Enterprise Java Server (EJS).

The EJB server provides the implementation for the services common to all
EJBs. The EJB server’s responsibility is to hide the complexities of these
services from the component requiring them. The EJB specification outlines
seven services that must be provided by an EJB server:
򐂰 Naming
򐂰 Transaction
򐂰 Security
򐂰 Persistence
򐂰 Concurrency
򐂰 Life cycle
򐂰 Messaging

Bear in mind that the EJB container and the EJB server are not very clearly
separated constructs from the component point of view. EJBs do not interact
directly with the EJB server (there is no standard API to do so), but rather do so
through the EJB container. So, from the EJBs’ perspective, it appears as if the
EJB container is in fact providing those services, when in fact it might not. The
specification defines a bean-container contract, but not a container-server
contract, so determining who actually does what is a little ambiguous and
platform dependent.

EJB container
The EJB container functions as a run-time environment for enterprise beans by
managing and applying the primary services that are needed for bean
management at run time. In addition to being an intermediary to the services
provided by the EJB server, the EJB container will also provide for EJB instance
life cycle management and EJB instance identification. EJB containers create
bean instances, manage pools of instances, and destroy them.

Containers are transparent to the client — there is no client API to manipulate the
container, and there is no way for a client to tell in which container an enterprise
bean is deployed.

One of the container’s primary responsibilities is to provide the means for remote
clients to access components that live within them. Remote accessibility enables
remote invocation of a native component by converting it into a network
component. EJB containers use the Java RMI interfaces to specify remote
accessibility to clients of the EJBs.

Chapter 12. Developing EJB applications 377


The responsibilities that an EJB container must satisfy can be defined in terms of
the primary services. Specific EJB container responsibilities are described here:
Naming The container is responsible for registering the unique
lookup name in the JNDI namespace when the server starts
up, and binding the appropriate object type into the JNDI
namespace.
Transaction The EJB container may handle the demarcation of
transactions automatically, depending on the EJB type and
the transaction type attribute, both described in the EJB
module’s deployment descriptor. When the container
demarcates the transactions, applications can be written
without explicit transaction demarcation code (i.e. begin,
commit, rollback).
Security The container provides a security domain for enterprise
beans. The container is responsible for enforcing the security
policies defined at the deployment time whenever there is a
method call, through access control lists (ACL). An ACL is a
list of users, the groups they belong to, and their rights, and it
ensures that users access only those resources and perform
those tasks for which they have been given permission.
Persistence The container is also responsible for managing the
persistence of a certain type of bean (discussed later in this
chapter) by synchronizing the state of the bean’s instance in
memory with the respective record in the data source.
Concurrency The container is responsible for managing the concurrent
access to components, according to the rules of each bean
type.
Life cycle The container controls the life cycle of the deployed
components. As EJB clients start sending requests to the
container, the container dynamically instantiates, destroys,
and reuses the beans as appropriate. The specific life cycle
management that the container performs is dependent upon
the type of bean. The container may ultimately provide for
some resource utilization optimizations, and employ
techniques for bean instance pooling.
Messaging The container must provide for the reliable routing of
asynchronous messages from JMS clients to
message-driven beans (MDB).

378 WebSphere Studio Application Developer Version 5 Programming Guide


Note: Asynchronous messaging is a new feature in the EJB 2.0 specification.
It essentially requires J2EE 1.3 compatible application server to provide two
things:
򐂰 Support of message-driven EJBs
򐂰 Support for internal messaging service

To be compliant with EJB 2.0, WebSphere Application Server Version 5 now


provides both of these, and so does Application Developer Version 5. The
internally embedded JMS messaging that is provided with the application
server is actually a lightweight implementation of IBM’s WebSphere MQ.

EJB components
EJB components run inside an EJB container, the run-time environment. The
container offers life-cycle services to these components, and provides them with
an interface to the EJB server. It also manages the connections to the enterprise
information systems (EISs), including databases and legacy systems.

Interfaces
For client objects to send messages to an EJB component, the component must
provide a view. A view is a client interface to the bean, and may be local or
remote. A local view can be used only by local clients (that reside in the same
JVM as the server component) to access the EJB. A remote view, on the other
hand, allows any client (possibly distributed) to access the component.

The idea of local interfaces is new to EJB 2.0, and is motivated by the fact that
remote calls are more expensive than local calls. Which one to use is influenced
by how the bean itself is to be used by its client, because local and remote depict
the client’s view of the bean. An EJB client may be an external (remote) client,
such as a servlet running on another process, or may be an internal (local) client,
such as another EJB.

Chapter 12. Developing EJB applications 379


Note: Even though a component may expose both a local and a remote view
at the same time, this is typically not the case. EJBs that play the role of
facades usually offer only a remote interface. The rest of the components
generally expose only a local interface.

In remote invocation, method arguments and return values are passed by


value. This means that the complete objects, including their non-transient
reference graphs, have to be serialized and sent over the network to the
remote party, which reconstructs them as new objects. Both the object
serialization and network overhead can be a costly proposition, ultimately
reducing the response time of the request.

On the other hand, remote interfaces have the advantage of being location
independent. The same method can be called by a client that is inside or
outside of the container.

Which interfaces to use, classes to extend, and other rules of bean construction
are governed by the type of bean you choose to develop. A quick introduction to
the types of enterprise beans and their uses is presented here.

EJB types
There are three main types of EJBs: entity beans, session beans, and
message-driven beans (Figure 12-2).

EJB

Synchronous Asynchronous

Entity Session Message-Driven

CMP BMP Stateless Stateful

Figure 12-2 EJB types

380 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Entity beans—Entity beans are modeled to represent business or domain
specific concepts, and are typically the nouns of your system, such as
customer and account. They usually represent data (entities) stored in a
database, for they are persistent.
Two flavors of entity beans govern how the persistency behavior will be
managed: either by the container, through container-managed persistence
(CMP), or by the bean itself, through bean-managed persistence (BMP).
򐂰 Session beans—A session bean is modeled to represent a task or workflow
of a system, and to provide coordination of those activities. It is commonly
used to implement the facade of EJB modules. Although some session beans
may maintain state data, this data is not persistent—it is just conversational.
Additionally, there are two flavors of session beans. Stateless session beans
are beans which maintain no conversational state, and are pooled by the
container to be reused. Stateful session beans are beans that keep track of
the conversational state with a specific client. Thus, they cannot be shared
among clients.
򐂰 MDBs—Like session beans, message-driven beans may also be modeled to
represent tasks. However, they are invoked by the receipt of asynchronous
messages, instead of synchronous ones. The bean either listens for or
subscribes to messages that it is to receive.

Although the classifications above (CMP versus BMP, and stateful versus
stateless) are often referred to as types of EJBs, they are not really different
types in the sense that there are no new classes or interfaces to represent these
types. They are still just entity or session beans. Rather, how the container
manages these beans is what makes them different. All information regarding the
way the container has to handle these different bean flavors is managed in the
deployment descriptor.

Entity and session beans are accessed synchronously through a remote or local
EJB interface method invocation. This is referred to as synchronous invocation,
because there is a request, and a (blocking) wait for the return. Clients of EJBs
invoke methods on session and entity beans. An EJB client may be an external
construct like a servlet (remote) or an another EJB within the same JVM (local).

The message-driven bean is not accessible through remote or local interface.


The only way for an EJB client to communicate with a message-driven bean is by
sending a JMS message. This is an example of asynchronous communication.
The client does not invoke the method on the bean directly, but rather, uses JMS
constructs to send a message. The container delegates the message to a
suitable message-driven bean instance to handle the invocation.

Chapter 12. Developing EJB applications 381


Interfaces and classes
An EJB component consists of the following primary elements, depending on the
type of bean:
򐂰 EJB bean class—Contains the bean’s business logic implementation.
Bean classes must implement one of the enterprise bean interfaces
(javax.ejb.SessionBean, javax.ejb.EntityBean,
javax.ejb.MessageDrivenBean), depending on the bean type.
Message-driven beans must also implement the javax.jms.MessageListener
interface, to allow the container to register the bean as a JMS message
listener and to call it back when a new message arrives.
򐂰 EJB component interface—Declares which of the bean’s business methods
should be exposed to the bean’s public interface. Clients will use this interface
to access such methods. Clients may not access methods that are not
declared in this interface. The component interface is also called the EJB
object, because of the javax.ejb.EJBObject interface that it extends.
򐂰 EJB home interface—Declares which bean’s life-cycle methods (to create,
find and remove beans instances) are available to clients, functioning very
much like a factory. The home interface is also called the EJB home, because
of the javax.ejb.EJBHome interface that it extends.
򐂰 Primary key class—Entity beans may also have a primary key class.
Instances of this class uniquely identify an instance of the entity type in the
database. Even though not formally enforced, primary key classes must also
correctly implement the equals and hashCode methods. As you will see,
Application Developer takes care of that for you.

Relationships
Container-managed relationships (CMRs) are among the most significant new
features added by the EJB 2.0 specification. Associations are a key component
of object-oriented software development and non-trivial object models can form
complex networks with these relationships. The EJB 2.0 specification adds
associations to the EJB programming model and requires that the container be
responsible for their maintenance.

The container automatically manages the state of CMP entity beans. This
management includes synchronizing the state of the bean with the underlying
database when necessary and also managing any CMRs with other entity beans.
The bean developer is relieved of writing any database specific code and,
instead, can focus on business logic.

There are three main types of association relationships:


򐂰 One-to-one—In a one-to-one (1:1) relationship, a CMP entity bean is
associated with a single instance of another CMP entity bean. If you come up

382 WebSphere Studio Application Developer Version 5 Programming Guide


with a one-to-one composition or aggregation relationship, remember to
check if you are not, in fact, modeling the same concept as two different
entities.
򐂰 One-to-many—In a one-to-many (1:m) relationship, a CMP entity bean is
associated with multiple instances of another CMP entity bean. For example,
an Account bean could be associated with multiple instances of a
TransRecord bean.
򐂰 Many-to-many—In a many-to-many (m:m) relationship, multiple instances of
a CMP entity bean are associated with multiple instances of another CMP
entity bean. For example, a Customer bean may be associated with multiple
instances of an Account bean, and a single Account bean may, in turn, be
associated with many Customer beans.

Component-level inheritance is still not in the EJB 2.0 specification, even though
it is planned for future releases. In the meantime, WebSphere Application Server
V5 and Application Developer V5 support it in a non-standard way.

EJB Query Language (EJB QL)


Another major enhancement of EJB 2.0 is EJB QL. With this new query
language, custom finder methods can be expressed at the entity attribute level
(that is, the EJB model), instead of tables and columns (the underlying
implementation in a relational database).

EJB QL queries are defined in the deployment descriptor and the EJB provider
generates the SQL statements for actual database access from the EJB QL. As
an example, this query retrieves customers that have accounts with a large
balance:
select object(c) from Customer c, in(c.accounts) a where a.balance > ?1

This EJB QL statement is independent of the database implementation. It follows


a CMR relationship from Customer to Account and queries the account balance.
Finder methods specified using EJB QL are portable to any EJB 2.0
environment.

EJB QL can be used for custom finder methods that return one or multiple EJB
objects (remote or local). In addition, EJB QL can be used for so called select
methods, which are internal to the implementation and not visible to clients.
Select methods can be used to accumulate data and return either EJB objects or
CMP or CMR fields or collections of any of those.

Chapter 12. Developing EJB applications 383


Sample Application: RedBank
In this chapter, we are going to reuse the design of the RedBank application,
described in “Developing Web applications” on page 179. This time, though, we
will use EJBs to implement the business model, instead of regular JavaBeans.
The rest of the application’s layers (control and view) still apply exactly as
designed, even though we will have to make some small changes to the facade
to make it work with EJBs instead of JavaBeans.

In Figure 12-3 you can see the model layer’s updated design.

Web Project EJB Project

Business Model
Customer

Banking BankEJB m:m

1:m
Account TransRecord
Facade

JavaBean Session bean ---------------------- Entity beans -------------------------


Figure 12-3 EJB module design

If you compare this model to the Web application model shown in Figure 5-21 on
page 111, you can see that the coordinator (Bank) has been replaced with a
session EJB (BankEJB). This EJB has a remote interface and uses container
demarcated transactions. Without any extra code, we are able to count on
transaction management for our operations.

Finally, our business entities (Customer, Account, and TransRecord) are


implemented as CMP entity beans with local interfaces, as opposed to regular
JavaBeans. By doing so, we automatically gain persistence, security, and
transaction management services.

On the other hand, this also implies that the control and view layers will not be
able to reference these entities directly, because they may be placed in a
different JVM. This time around, only the session bean (BankEJB) will be able to
access the business entities through their local home interfaces.

384 WebSphere Studio Application Developer Version 5 Programming Guide


Note: In general, the session bean is called the facade. In our design we use
a JavaBean and a session bean to function as the facade. This isolates the
Web application completely from the model implementation. Only the
JavaBean part of the facade must be changed to interact with the session
bean facade instead of another model implementation.

You may be asking yourself, then why we do not expose a remote interface for
our entity beans as well? The problem with doing that is twofold. First, in such a
design, clients would probably make many remote calls to the model in order to
resolve each client request. This is not a recommended practice because remote
calls are much more expensive than local ones. Finally, allowing clients to see
into the model breaks the layer’s encapsulation, promoting unwanted
dependencies and coupling.

Fortunately, this problem has a well-known documented solution: the data


transfer object (DTO) design pattern (refer to EJB Design Patterns, by FLoyd
Marinescu), also known as value object and transfer object). The idea is to limit
inter-layer data sharing to serializable JavaBeans, thus avoiding remote
references. This DTO can be created by the session facade or by a builder object
(according to the builder design pattern) on its behalf, in case the building
process is too complicated or needs validation steps.

Figure 12-4 shows the application component model and the flow of events, so
that you can see the big picture.

HTTP RMI/IIOP
Web Client 1 Control Facade 2 Facade
3
4 Entity
5
7 Model

View 6 EJB Module

Web Module DTO


EJB Container

Web Container
Application Server

Figure 12-4 Application component model and workflow

Chapter 12. Developing EJB applications 385


1. The first event that occurs is the HTTP request issued by the Web client to the
server. This request is answered by a servlet in the control layer, also known
as the front controller, which extracts the parameters from the request. The
servlet sends the request to the appropriate control JavaBean. This bean
verifies if the request is valid in the current user and application states.
2. If so, the control layer sends the request through the JavaBean facade to the
session EJB facade. This involves using JNDI to locate the session bean’s
home interface and creating a new instance of the bean.
3. The session EJB executes the appropriate business logic related to the
request. This includes having to access entity beans in the model layer.
4. The facade creates a new DTO and populates it with the response data.
5. The front controller servlet sets the response DTO as a request attribute and
forwards the request to the appropriate JSP in the view layer, responsible for
rendering the response back to the client.
6. The view JSP accesses the response DTO to build the user response.
7. The result view, possibly in HTML, is returned to the client.

Please note that the intent of this chapter is to introduce you to the Application
Developer’s tools that make the development of EJBs and enterprise applications
possible. Together we will work only on a single session bean and three entity
beans. The rest of the application has already been developed and will be made
available to you, so that you can dig into it if you would like to.

Creating an EJB project


In Application Developer, you create and maintain Enterprise JavaBeans and
associated Java resources in EJB projects. The environment has facilities that
help you deal with all three types of EJBs, define relationships (association and
inheritance), and create resources such as access beans, converters and
composers. Within an EJB project, these resources can be treated as a portable,
cohesive unit.

Note: Converters and composers are used for non-standard relational


mapping. A converter allows you to transform a user-defined Java type to an
SQL type back and forth. Composers are used when entity attributes have
multi-column relational representations.

An EJB module typically contains components that work together to perform


some business logic. This logic may be self-contained, or access external data
and functions as needed. It should be comprised of a facade and the model. The

386 WebSphere Studio Application Developer Version 5 Programming Guide


facade is usually implemented using one or more remote session beans. The
model is commonly implemented with related local entity beans and
message-driven beans.

In this chapter we develop three entity beans, two relationships, and a session
bean. We require a J2EE EJB project to support our tasks. To create an EJB
project, select File -> New -> EJB Project. The dialog in Figure 12-5 is displayed.

Figure 12-5 Create an EJB project wizard (page 1)

The wizard’s first page asks you to supply the version of the EJB specification
you want to use in your project. Since this is a brand new project, we want the
latest version available. Select the Create 2.0 EJB Project option and click Next
to continue to the second page (Figure 12-6).

Figure 12-6 Create an EJB project wizard (page 2)

Chapter 12. Developing EJB applications 387


The second page lets you specify the project’s name, directory and associated
enterprise application project. Type ItsoProGuideEJB in the Project name field
and leave the directory to the default value.

We use the existing ItsoProGuide project as enterprise application. Alternatively


we could create a new one. Select Existing and click Browse to find the project.
Select it and click OK.

Click Next. On the Module Dependencies page, select the


ItsoProGuideJava.jar utility JAR file as a dependency (Figure 12-7).

Figure 12-7 Module dependency of EJB project

Click Finish to complete the creation of the EJB project.

If you already had the enterprise application project added to a server


configuration, Application Developer displays the Repair Server Configuration
dialog. Simply click OK to continue.

Data transfer objects and helper classes


We will use the Customer, Account, and TransRecord objects of the utility project
as our data transfer objects (DTOs). In addition we use the exception and the
AmountConverter classes.

388 WebSphere Studio Application Developer Version 5 Programming Guide


Implementing the model with entity beans
Our first step towards implementing the RedBank’s model with EJBs is creating
the entity beans: Customer, Account, and TransRecord (Figure 12-8).

Business Model
Customer

BankEJB m:m

1:m
Facade Account TransRecord

Figure 12-8 Business entities

Creating the entity beans


We implement the three entity beans in sequence.

Define the Customer bean


Switch to the J2EE perspective and select the EJB project you have just created
in the J2EE Hierarchy view. Select File -> New -> Enterprise Bean (Figure 12-9).

Figure 12-9 Enterprise Bean Creation

Select the ItsoProGuideEJB project from the list.

Note: If you select the ItsoProGuideEJB project and New -> Enterprise Bean
(context), the project is prefilled.

Chapter 12. Developing EJB applications 389


Click Next to continue (Figure 12-10).

Figure 12-10 Creating an entity bean (page 1)

The three entity beans that we are creating have container-managed persistence
fields and comply with the EJB 2.0 specification. Select the Entity bean with
container-managed persistence (CMP) fields and CMP 2.0 Bean options.

Type the bean name (Customer), leave the source folder to the default value
(ejbModule), and enter the default package (itso.ejb.model.entity). Click Next
to continue (Figure 12-11):
򐂰 This page lets you select the supertype (allowing you to define the inheritance
structures, not covered any further in this book), type names, binding name
(the name through which the bean is going to be referenced by its clients),
which views you would like to create, and finally the key class and CMP
attributes.
򐂰 Most of the time the suggested values for the binding name and the type
names (derived from the bean name) are good, so you do not have to worry
about them.
򐂰 According to our design, entity beans should have only local interfaces, so
make sure not to select the Remote client view check box. Application
Developer knows about this good practice, so it will only select Local client
view by default.

390 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-11 Creating an entity bean (page 2)

Add the CMP attributes by clicking Add (Figure 12-12).

Figure 12-12 Create a CMP attribute

Chapter 12. Developing EJB applications 391


This dialog lets you specify the characteristics of the new CMP attribute you
would like to add to the entity bean. Enter the attribute’s name and type.
Alternatively, you can browse the type by clicking Browse.

If the attribute is an array, select the Array check box and specify the number of
the dimensions for it.

By selecting the Key field check box, you indicate that the new field should be
part of the entity’s unique identifier. You may declare as many attributes as you
want to perform this role. Application Developer is very smart here. If you specify
just one key attribute of an object type, it will declare that type as the key class in
Figure 12-11). If you select an attribute of a non-object type (like int or double),
or if you select more than one key attribute, the environment will automatically
create a new key class for you, implement all its methods (including equals and
hashCode), and declare it as the key class.

Note: If you do not define at least one key CMP attribute, errors will exist for
the new enterprise bean. You can correct them later by adding CMP key
attributes.

The two last check boxes let you indicate if you want to promote the new attribute
(through its getter and setter) to either the remote or the local interfaces, or to
both. The availability of these options depends on which client views you
selected.

For the Customer bean, add the fields stated in Table 12-1. If you click Apply, the
attribute will be added and the dialog will stay open.

Table 12-1 Customer bean’s CMP attributes


Name Type Key Local Interface

id int Yes N/A

title String No Yes

firstName String No Yes

lastName String No Yes

Click Close only after adding the last attribute and clicking Apply. You are brought
back to the wizard, which should look like Figure 12-13.

392 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-13 Creating an entity bean (page 2) after adding CMP attributes

Note the check box Use the single key attribute type for the key class. If you have
one key attribute and it is a normal Java type, such as String, Integer, Float,
BigDecimal, and so forth, then a separate key class is not required.

Key wrapper classes are required for the simple data types (int, float, char), for
JavaBeans, and if there is more than one key attribute.

Click Next to continue to the wizard’s last page (Figure 12-14).

Chapter 12. Developing EJB applications 393


Figure 12-14 Creating an entity bean (page 3)

In this page you can specify the superclass to the bean class, and declare which
interfaces should the remote and local interfaces extend.

Note: The bean superclass has nothing to do with the EJB inheritance
mechanism supported by Application Developer and WebSphere Application
Server. It is simply a way to declare regular Java inheritance for the bean
class.

Click Finish to complete the creation of your new entity bean.

Define the Account and TransRecord beans


Repeat the same process for the other two CMP 2.0 entity beans, Account and
TransRecord, according to the data on Table 12-2 and Table 12-3. Make sure to
select Use the single key attribute type for the key class.

Table 12-2 Account bean CMP attributes


Name Type Key Local Interface

id String Yes N/A

balance java.math.BigDecimal No No

type String No No

394 WebSphere Studio Application Developer Version 5 Programming Guide


Table 12-3 TransRecord bean CMP attributes
Name Type Key Local Interface

timeStamp java.util.Date Yes N/A

transType String No Yes

transAmt java.math.BigDecimal No Yes

Our transaction record objects do not have a natural primary key. As you know,
we must come up with an artificial unique identifier in order to be able to store
such objects in a relational database. For simplicity, we chose to create a new
java.util.Date object and set it as the primary key when transaction record
objects are created. The approach works just fine in our sample environment, but
could fail in the real world. If the application is deployed to two servers in a
cluster, for instance, both can try to create a new transaction record at the very
same time. This would lead to an error due to duplicate primary keys.

Note: It is common to find entities that do not have a natural unique identifier.
The EJB 2.0 specification touches this problem when it introduces the
unknown primary key class for CMP entity beans (10.8.3). The problem is that
WebSphere Application Server Version 5 does not implement this part of the
specification—you have to roll your own solution.

There are basically two approaches to the problem. The first is to have the
backend database generate the unique identifiers. This is feasible because
even though you may have as many application servers as you may like, the
data pertinent to a single entity will hopefully be stored in just one database.
The downside to this approach is that every time an entity is created, a
database table must be locked in order to generate the ID, and thus becomes
a bottleneck of the process.

The second approach would be to generate the universally unique identifiers


(UUIDs, unique even among distributed systems) in the application server tier.
This is a little tricky, but can be accomplished. One way to do it is to come up
with a utility class that generates the UUIDs based on a unique JVM identifier,
the machine's IP address, the system time and an internal counter. This
technique is usually much more efficient than having the backend database
generate UIDs because it does not involve table locking.

Chapter 12. Developing EJB applications 395


Complete entity model
At the end, your J2EE Hierarchy view should look like Figure 12-15.

primary key attribute

attribute

home interface

component interface

bean class

key class

Figure 12-15 J2EE Hierarchy view of entity beans

As you can see, for each entity bean, we have a primary key attribute (there
could be more than one), regular attributes, a home and a component interface
(both local), the bean class, and a key class.

Editing the entity beans


Now that our three entity beans have been created, it is time for us to do a little
programming.

For each bean three or four classes were created: the bean class, the home
interface, the local component interface, and (only for the Customer) a key class.

While in the J2EE Hierarchy view, double-click the AccountBean class. Application
Developer will open the Java editor and focus the Outline view (Figure 12-16) on
the class:
򐂰 Life-cycle methods are the callback method used by the EJB container at
predefined events.
򐂰 Business methods manipulate the CMP attributes.

396 WebSphere Studio Application Developer Version 5 Programming Guide


life-cycle methods

business methods

Figure 12-16 Outline view of the AccountBean class

Adding business logic


As you can see, Application Developer has already generated the life-cycle
methods and some business methods for us. The latest, of course, are just the
getters and setters. We still have two more to add: deposit and withdraw. Simply
type them in as shown in Figure 12-17:

public void deposit(java.math.BigDecimal amount) {


setBalance( getBalance().add(amount) );
}

public void withdraw(java.math.BigDecimal amount)


throws InsufficientFundsException {
if ( getBalance().compareTo(amount) == -1 )
throw new InsufficientFundsException();
setBalance( getBalance().subtract(amount) );
}

Figure 12-17 Account bean deposit and withdraw methods

Application Developer should tell you that you code has errors, because it cannot
find the InsufficientFundsException class. You can either type in the import
statement yourself (import itso.ejb.exception.InsufficientFundsException),
or let Application Developer fix the problem for you. For the later option, select
Source -> Organize Imports or click Ctrl-Shift-O.

Chapter 12. Developing EJB applications 397


Promoting business methods to the component interface
Finally, on the Outline view, select the methods that we want to promote to the
component interface: getId, deposit and withdraw (select all three by holding
the Ctrl key). Select Enterprise Bean -> Promote to Local Interface from the
view’s context menu.

Save your changes and close the editor.

Open the AccountLocal interface to check the methods you have just promoted.
Then delete or comment the setBalance method (only deposit and withdraw are
allowed). The local interface is shown in Figure 12-18:

package itso.ejb.model.entity;
import itso.ejb.exception.InsufficientFundsException;

public interface AccountLocal extends javax.ejb.EJBLocalObject {

public java.math.BigDecimal getBalance();


//public void setBalance(java.math.BigDecimal newBalance);
public java.lang.String getType();
public void setType(java.lang.String newType);
public java.lang.String getId();
public void deposit(java.math.BigDecimal amount);
public void withdraw(java.math.BigDecimal amount)
throws InsufficientFundsException;
}

Figure 12-18 AccountLocal interface

Tip: Accessors for the key attribute are not promoted automatically to the
component interface. You have to promote the getter method manually. Do not
promote the setter method, the key cannot be changed.

Even though the AccountBean class has more methods than the ones listed
above, the methods in Figure 12-18 are the only ones a client may call, because
they are declared on the component interface.

For the Customer bean, promote the getId method.

The last one of the three is the TransRecord bean. All transaction records should
be read-only (they cannot be altered once they are created), therefore we have to
remove the setter methods from the interface.

398 WebSphere Studio Application Developer Version 5 Programming Guide


Open the TransRecordLocal interface. There are two ways to remove the setters
from the component interface. You can either manually delete them through the
Java editor, or select them both on the Outline view and select Delete from the
context menu.

Promote the getTimeStamp method from the bean and the interface should look
like Figure 12-19.

package itso.ejb.model.entity;

public interface TransRecordLocal extends javax.ejb.EJBLocalObject


{
public java.util.Date getTimeStamp();
public java.lang.String getTransType();
public java.math.BigDecimal getTransAmt();
}

Figure 12-19 TransRecordLocal interface

Save your changes and close the editor.

Transaction records should only be created if the client supplies both the
transaction type and amount. To enforce this, edit the TransRecordLocalHome
interface and change the signature of the create method (Figure 12-20).

public TransRecordLocal create(String transType,


java.math.BigDecimal transAmt)
throws javax.ejb.CreateException;

Figure 12-20 TransRecord bean create method in the home interface

Make sure that the old create method is deleted. Save your changes and close
the editor.

When you save your changes, Application Developer displays a warning on the
Tasks view, letting you know that an ejbCreate method should exist for the
create method you have just declared. Actually, a pair of ejbCreate and
ejbPostCreate methods with the same set of parameters must exist for every
create declared in the component interfaces. When we changed the create
signature on the TransRecordLocal interface, that ceased to be true.

Open the TransRecordBean class and change the ejbCreate and ejbPostCreate
methods (Figure 12-21). Make sure that the old methods are deleted.

Chapter 12. Developing EJB applications 399


public java.util.Date ejbCreate(String transType,
java.math.BigDecimal transAmt)
throws javax.ejb.CreateException {
setTimeStamp(new java.util.Date());
setTransType(transType);
setTransAmt(transAmt);
return null;
}

public void ejbPostCreate(String transType,


java.math.BigDecimal transAmt)
throws javax.ejb.CreateException {
}

Figure 12-21 TransRecord bean’ejbCreate method

Save your changes and close the editor.

Creating entity relationships


Now that the three business entities have been created, it is time to specify their
relationships: a one-to-many and a many-to-many association (Figure 12-22).

Business Model
Customer

BankEJB m:m

1:m
Facade Account TransRecord

Figure 12-22 Relationships in the model

Application Developer offers a wizard that streamlines the process of both


creating and maintaining CMRs. To open it, you can either use the EJB
deployment descriptor editor, as described below, or select New -> Relationship
from the source enterprise bean’s context menu.

Relationships are defined in the deployment descriptor.

400 WebSphere Studio Application Developer Version 5 Programming Guide


Account TransRecord relationship
In the J2EE Hierarchy view, double-click ItsoProGuideEJB to open the EJB
deployment descriptor. Switch to the Beans page and select the Account bean.

Scroll down to the Relationships section, as shown in Figure 12-23.

Figure 12-23 Defining relationships with the EJB deployment descriptor editor

Click Add to create a new relationship for the Account bean. The Add
Relationship wizard opens (Figure 12-24).

Figure 12-24 Add relationship wizard (page 1)

The wizard opens with the Account bean already selected on the left hand list
box. Select the TransRecord bean on the other list box. The wizard should
automatically fill in the Relationship name field. Click Next to continue to the
second page (Figure 12-25).

Chapter 12. Developing EJB applications 401


Figure 12-25 Add relationship wizard (page 2)

The second wizard page shows a UML view of the relationship and a
specification view.

Note: The multiplicity described in the specification view corresponds to the


rules in the EJB 2.0 specification. It is backwards to the UML view because the
multiplicity for the role is relative to the relationship, and in the UML view it is
relative to the source enterprise bean.

As part of defining a relationship, you assign a role to each bean relative to the
other bean, and you give that role a name. These names are used to derive
method names in the generated code and become part of the enterprise bean's
component interface.
򐂰 For the Account bean (left hand group in Figure 12-25), assign transRecords
as the role of the TransRecord bean. The attribute is in plural because of the
relationship multiplicity (one account may be associated with many
transaction records).
򐂰 For the TransRecord bean (right hand group in Figure 12-25), assign Many for
the Multiplicity field and select the Cascade delete check box.

402 WebSphere Studio Application Developer Version 5 Programming Guide


We want the application server to delete transaction records when the
associated account is deleted.

Click Finish to complete the wizard.

Tip: There are some alternative ways to open the EJB deployment descriptor.
On the J2EE Navigator view, you can double-click the EJB Deployment
Descriptor item right under the ItsoProGuideEJB project, or open the
ejb-jar.xml file under the ItsoProGuideEJB\ejbModule\META-INF folder. Also,
you can have the EJB deployment descriptor editor focus automatically on an
EJB by double-clicking directly on the bean in the J2EE Hierarchy view.

Customer Account relationship


We now have to add the second relationship, between the Customer bean and the
Account bean. In the Bean page of the EJB deployment descriptor, select the
Customer bean and click Add on the Relationships section. Select both Customer
and Account and click Next to continue. The wizard advances to the second page
(Figure 12-26).

Figure 12-26 Customer <-> Account relationship

Chapter 12. Developing EJB applications 403


This time around, the association relationship is many-to-many. Simply turn both
role names to plural and set both Multiplicity fields to Many. Click Finish to
complete the wizard.

Figure 12-27 shows the EJB deployment descriptor with the Account bean
selected.

Figure 12-27 EJB deployment descriptor editor after creating relationships

Save the changes and close the editor.

You may now inspect the changes the wizard made to your EJBs. In the J2EE
Hierarchy view, double-click the AccountLocal interface to open it with the Java
editor. The following methods should have been added:
public java.util.Collection getTransRecords();
public void setTransRecords(java.util.Collection aTransRecords);
public java.util.Collection getCustomers();
public void setCustomers(java.util.Collection aCustomers);

Close the editor.

Updating the TransRecord create method


You might recall that we have updated the TransRecord create method before
(Figure 12-20 on page 399 and Figure 12-21 on page 400). In that opportunity,
we added parameters to the create method to make sure no transaction record
was created unless the transaction type and amount were specified. Now we
want to guarantee that the account associated with the transaction record is also
specified.

404 WebSphere Studio Application Developer Version 5 Programming Guide


Update the TransRecordLocalHome interface so that the create method has this
signature:
public itso.ejb.model.entity.TransRecordLocal create(String transType,
int transAmt, AccountLocal account) throws javax.ejb.CreateException;

Note that the only change was the additional AccountLocal parameter. Save your
changes and close the editor.

Because we changed the create method on the home interface, we also have to
change the ejbCreate and ejbPostCreate methods in the TransRecordBean
class. Open the class and perform the changes described in Figure 12-28.

public java.util.Date ejbCreate(String transType,


java.math.BigDecimal transAmt, AccountLocal account)
throws javax.ejb.CreateException {
setTimeStamp(new java.util.Date());
setTransType(transType);
setTransAmt(transAmt);
return null;
}

public void ejbPostCreate(String transType,


java.math.BigDecimal transAmt, AccountLocal account)
throws javax.ejb.CreateException {
setAccount(account);
}

Figure 12-28 TransRecord bean’s updated ejbCreate and ejbPostCreate methods

Note: The setAccount method was added when we created the association
relationship between the Account and the TransRecord beans. This method
cannot be called from the ejbCreate method. According to the specification,
during ejbCreate the instance cannot acquire a reference to the associated
entity object, and that reference is required by the setAccount method.

In the ejbPostCreate method, on the other hand, the instance may reference
the associated entity object. Thus, a call to setAccount can be made.

Save your changes and close the editor.

Chapter 12. Developing EJB applications 405


Creating custom finders
When you create an entity bean, you always get the findByPrimaryKey finder
method on the home interface. Sometimes, though, you need to find an entity
based on criteria other than just the primary key. For these occasions, the EJB
2.0 specification provides a query language called EJB QL. Custom finder
methods are declared in the home interface and defined in the EJB deployment
descriptor using the EJB QL.

We do not require any custom finders for our RedBank example. But we will add
one nonetheless so that you know how you would do it on your own projects. Our
finder will look for all accounts that have a balance greater than a given value.

Open the EJB deployment descriptor, switch to the Beans page, and select the
Account bean from the list. Scroll down to the Queries section (Figure 12-29).

Figure 12-29 Defining queries with the EJB deployment descriptor editor

Click Add to open the Add Finder Descriptor wizard (Figure 12-30):
򐂰 Here you have the option to define the query descriptor to either a new finder
method or to one previously declared in the bean’s home interface. Select
New, as the only finder we have in our AccountLocalHome interface is the
default findByPrimaryKey. Application Developer will take care of updating the
home interface for you by adding the declaration of the new finder method.
򐂰 The Method Type field lets you select whether you want to create a descriptor
for a finder method or for an ejbSelect method. Select the find method
option. The difference between the two is that finder methods get promoted to
the bean's home interface, whereas ejbSelect methods do not. The latest are
useful as internal helper methods, as they cannot be called by clients.

406 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-30 Adding a new finder method (page 1)

򐂰 The Type field would let you select to which home interface, either local or
remote, you would like the finder method promoted. You do not get an option
in this case because our Account bean only exposes a local view.
򐂰 In the Name field, type findGoldAccounts as the name of the finder method.
򐂰 Click Add to define a BigDecimal parameter.
򐂰 Select java.util.Collection in the Return type field. Finder and ejbSelect
methods may return either a collection of objects, or just one instance of the
object’s component interface types.
򐂰 Click Next to proceed to the final page (Figure 12-31):

The last wizard page lets you type a description to the query and the query
statement. You may optionally select a sample query as a starting point, for
example, FindByPrimaryKey.
򐂰 Complete the query:
select object(o) from Account o where o.balance > ?1
򐂰 Click Finish to end the dialog.

Chapter 12. Developing EJB applications 407


Figure 12-31 Adding a new finder method (page 2)

The EJB deployment descriptor with the query is shown in Figure 12-32.

Figure 12-32 EJB deployment descriptor after adding query

Save your changes and close the editor.

408 WebSphere Studio Application Developer Version 5 Programming Guide


Object-relational mapping
CMP entity beans delegate its persistence to the container. But what does this
mean? Simply, as bean providers, we do not have to code any database access
directly into our entity beans—we let the container do it for us. The only thing we
must provide are the abstract data-to-object mappings that map the fields in our
bean to a database, and the abstract methods that correlate to those fields. The
container knows that data is to be persisted because the mappings are defined in
the deployment descriptor, and during deployment, the JDBC code to perform
the operations is generated by the container. When the beans are actually
deployed, associations to real data sources can be made to dynamically bind the
bean to the data. In this way, the CMPs are abstract classes that associate to
data, but do not provide any implementation for accessing data themselves.

Of course, this is an oversimplification: everything is not completely abstracted


away and hidden from the developer because the developer has to have some
knowledge of the underlying data sources at the time of development, to create
and test the mappings in the first place. It’s just that defining the deployment
descriptor abstract mappings is a separate and distinct process from associating
those mappings to a real data source at deployment time. To facilitate
deployment and testing, Application Developer gives you the tools and means to
both define the mappings and create deployment bindings at the same time.

Hiding the knowledge is not really the primary reason for having an abstraction
such as this, where the definition and development of the bean and its mappings
is separate from the dynamic run-time bindings of the bean. The goal, rather, is
to enable the developer to work with object views of the domain data instead of
data views and writing SQL. But another subtle benefit is also achieved. By
having a separation of these development and persistence concerns, one is free
to focus on the business logic. The CMP can be developed largely independently
of the data source, and allows a clear separation of business and data access
logic. This is one of the fundamental axioms of aspect oriented programming,
where the aspect of persistence can be removed from the development process,
and applied later, in this case, at deployment time.

Application Developer offers three different mapping strategies: top down, meet
in the middle, and bottom up:
򐂰 Top down is when you start from an object oriented model and let the
environment generate the data model automatically for you, including the
object-relational mapping and the DDL that you would use to create the tables
in the database.

Note: This strategy is preferred when the data backend does not exist and
will be created from scratch.

Chapter 12. Developing EJB applications 409


򐂰 Bottom up is when you start from a data model and let Application Developer
generate the object model automatically for you, including the creation of the
entity beans based on tables and columns that you select.

Note: This strategy is not recommended for object oriented applications,


because the data model is less expressive than the object model. It should
be used only for prototyping purposes.

򐂰 Meet in the middle is the compromise strategy, in which you keep both your
existing object oriented and data models, creating a mapping between the
two. The mapping process is usually started by Application Developer, based
on cues like attribute names and types, and completed manually by you.

For now we will use the meet in the middle strategy because we do have an
existing database for application data.

Mapping the model to the EJBBANK database


In the J2EE Hierarchy view, select the EJB module (ItsoProGuideEJB) and select
Generate -> EJB to RDB Mapping from its context menu.

In the EJB to RDB Mapping panel, select Create a new backend folder and click
Next. Application Developer enables us to map an entity bean to multiple
backend stores, for example, different relational database systems
(Figure 12-33).

Figure 12-33 Create a backend folder

410 WebSphere Studio Application Developer Version 5 Programming Guide


In the Create new EJB/RDB Mapping panel, select Meet In the Middle and click
Next.

The Database Connection pane opens, as shown in Figure 12-34.

Figure 12-34 Database connection

Enter the connection name (EJBBankConnection) and the database name


(EJBBank). The rest of the options should be left to their default values, that are:
򐂰 The user ID and password fields can be left empty if your user ID is
authorized to the EJBBANK database and tables. Otherwise use the user ID
that was used to install DB2 and to define the EJBBANK database.
򐂰 For database vendor, make sure that DB2 UDB V7.2 is selected.
򐂰 For JDBC driver, select IBM DB2 APP DRIVER .

Chapter 12. Developing EJB applications 411


򐂰 The class location is prefilled if DB2 is installed on your system. Make sure
that the location points to the db2java.zip file.
򐂰 You can use the Filters button to limit the number of table definitions that are
imported. Although we do not use all the tables for our model, we do not use a
filter.

Click Next to open the Selective Database Import panel. Select the four tables
that are required for our model (Figure 12-35).

Figure 12-35 Selecting the tables for import

Click Next and select Match by Name (Figure 12-36). This option should match
entities and attributes to tables and columns with the same name, thus
minimizing your manual work.

412 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-36 Matching options

Click Finish to complete the database schema import and to open the mapping
editor (Figure 12-37):
򐂰 As you can see, matching by name has already mapped the beans to the
correct tables, and some fields to the correct columns. The mapped items
carry a little triangle as an indicator and they are listed in the bottom pane.
򐂰 Some fields have not been matched automatically. We can perform the
manual mapping by dragging and dropping attributes in the left pane to
relational columns on the right, or vice-versa. A bean must be mapped to a
table before you can map the attributes of the bean to the columns.
Relationships can be mapped as if they were regular fields.

Note: You can alternatively select an item in the left pane and one in the right
pane and select Create Mapping from the context menu. This is the same as
drag and drop.

򐂰 The arrows in Figure 12-37 indicate what manual mapping must be


performed, solid for attributes and dotted for relationships:
– Customer id <--> CUSTOMER CUSTOMERID
– Account id <--> ACCOUNT ACCID
– Account type <--> ACCOUNT ACCTYPE
– TransRecord timeStamp <--> TRANSRECORD TRANSID
– Account customers <--> CUSTACCT CAtoCustomer
– Customer accounts <--> CUSTACCT CAtoAccount
– TransRecord account <--> TRANSRECORD AccountTransrecord
Note: The last mapping also maps Account transRecords (in a 1:m
relationship only one mapping is required)

Chapter 12. Developing EJB applications 413


Figure 12-37 Object-relational mapping editor

The Outline view of the mapping editor summarizes our mapping activities
(Figure 12-38).

414 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-38 Outline view of the mapping editor

Save the mapping (Ctrl-s) and close the editor.

Implementing the session facade


The last EJB that we have to build is the facade: the BankEJB stateless session
bean (Figure 12-39).

Business Model
Customer

BankEJB m:m

1:m
Facade Account TransRecord

Figure 12-39 Business model facade

Chapter 12. Developing EJB applications 415


Creating the session bean
In the J2EE Hierarchy view, select New -> Enterprise Bean from the
ItsoProGuideEJB context menu. Check the project name and click Next to
advance to the wizard’s first page (Figure 12-40).

Figure 12-40 Creating a new session bean (page 1)

Select the Session bean option and type BankEJB in the Bean name field. Type
itso.ejb.model.facade in the Default package field and click Next to continue
(Figure 12-41):
򐂰 Make sure that you have the correct selections Stateless and Container.
򐂰 Note that this time around, Application Developer suggests that you create a
remote client view instead of a local client view. This is because the
environment knows that session beans are normally used to implement the
model’s facade and, as such, need remote interfaces as opposed to local
ones.
򐂰 The next wizard’s page is just like the one shown in Figure 12-14 on page 394
and need not be altered as well.
򐂰 You may as well click Finish to complete the creation of your session bean.

416 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-41 Creating a new session bean (page 2)

If you open the J2EE Hierarchy view, you will be able to see the newly created
session bean (Figure 12-42).

Figure 12-42 J2EE Hierarchy view of session bean

Chapter 12. Developing EJB applications 417


Note that for session beans, just three types are generated by the wizard: the
remote home interface, the remote component interface, and the bean class.
There is no need to have a key class because session beans are not persistent.

Creating an EJB reference


An EJB reference is a logical (alternative) name used to locate the home
interface of an enterprise bean used by an application. Using a logical name
instead of the complete JNDI name allows applications to use hard coded strings
to reference other beans and still be easy to maintain.

The link between the logical name and the real bean is defined in the EJB
deployment descriptor and does not involve changing the code. At deployment,
the EJB reference is bound to the enterprise bean's home in the target
operational environment. The container makes the application's EJB references
available in a JNDI naming context.

In Application Developer, EJB references are edited using the EJB deployment
descriptor editor (Figure 12-43).

logical name

Figure 12-43 EJB references

As you can see, some references have already been defined for you. Application
Developer automatically does that when you create relationships among entity
beans. We now have to add references to the BankEJB facade, so that it can
access the entity beans without having to use the complete JNDI name.

418 WebSphere Studio Application Developer Version 5 Programming Guide


Select the BankEJB bean and click Add. A dialog that lets you select the kind of
reference to add is displayed (Figure 12-44).

Figure 12-44 Reference types

EJBs may reference other EJBs either through a remote or local interface. They
may also reference resources and security roles. Since our entity beans are all
local to the session bean, select EJB local reference and click Next to continue.

The next dialog (Figure 12-46) lets you specify the information of the referenced
local EJB:
򐂰 You do not have to fill in all the fields, because Application Developer knows
all the information if only you let it know which EJB you would like to
reference.
򐂰 Locate the Link field, but instead of typing the information, click Browse to
open the Link Selection dialog.
򐂰 Select the Customer bean from the drop-down combo box and click OK.
򐂰 Click Finish to create the reference.

Chapter 12. Developing EJB applications 419


Figure 12-45 Adding an EJB local reference

Repeat the same process for the Account and the TransRecord bean. When you
are done, the References page of the EJB deployment descriptor should look like
Figure 12-46.

Figure 12-46 BankEJB bean references

Save your changes and close the editor.

420 WebSphere Studio Application Developer Version 5 Programming Guide


Editing the session bean
To be compatible with our existing control and presentation layers, the improved
model layer must expose the very same set of operations that were made public
by the previous JavaBean implementation. These operations are as follows:
򐂰 public BigDecimal deposit(String accountID, BigDecimal amount)
throws AccountDoesNotExistException, CreateException
򐂰 public BigDecimal withdraw(String accountID, BigDecimal amount)
throws InsufficientFundsException, AccountDoesNotExistException,
CreateException
򐂰 public BigDecimal transfer(String accountID1, String accountID2,
BigDecimal amount) throws InsufficientFundsException,
AccountDoesNotExistException, CreateException
򐂰 public Customer getCustomer(String customerID) throws
CustomerDoesNotExistException
򐂰 public Account getAccount(String accountID) throws
AccountDoesNotExistException
򐂰 public Account[] getAccounts(String customerID) throws
CustomerDoesNotExistException
򐂰 public TransRecord[] getTransactions(String accountID) throws
AccountDoesNotExistException

Note: The EJB methods can throw additional exceptions, for example,
CreateException is thrown if the create of a TransRecord fails.

Caching the initial context and the EJB homes


Open the BankEJBBean class with a Java editor. To implement the methods listed
above, we will make use of some private helper methods and properties.

Declare the following properties inside the class definition body:


private Context context;
private AccountLocalHome accountHome;
private CustomerLocalHome customerHome;
private TransRecordLocalHome transRecordHome;

They will hold, respectively, cached references to the initial naming context and
the homes of the entity beans.

Errors may be reported because of missing import statements. Correct them by


selecting Source -> Organize Imports. When asked to inform the complete name
of the Context type, select javax.naming.Context.

Chapter 12. Developing EJB applications 421


Now make Application Developer generate getter methods for the three
properties. Select Source -> Generate Getter and Setter and then select only the
getter methods for all three properties.

Change all three methods from public to private, and then perform changes to
the code as shown in Figure 12-47.

private Context getContext() throws NamingException {


if (context == null) context = new InitialContext();
return context;
}
private AccountLocalHome getAccountHome() {
if (accountHome == null)
accountHome = (AccountLocalHome)lookup("ejb/Account"));
return accountHome;
}
private CustomerLocalHome getCustomerHome() {
if (customerHome == null)
customerHome = (CustomerLocalHome)lookup("ejb/Customer");
return customerHome;
}
private TransRecordLocalHome getTransRecordLocalHome() {
if (transRecordHome == null)
transRecordHome = (TransRecordLocalHome)lookup("ejb/TransRecord");
return transRecordHome;
}

Figure 12-47 BankEJB bean getter methods

All three properties will be lazy-initialized when the getters are called for the first
time. Add the appropriate imports to the javax.naming.InitialContext and
javax.naming.NamingException types.

Note: The get methods to retrieve the local homes of the entity beans invoke
the lookup helper method with the name of the EJB reference that we defined
for the session bean, for example, ejb/Account.

Now enter the remaining three helper methods (Figure 12-48).

422 WebSphere Studio Application Developer Version 5 Programming Guide


private Object lookup(String referenceName) {
try { return getContext().lookup("java:comp/env/" + referenceName);
} catch (NamingException e) { throw new EJBException(e); }
}
private CustomerLocal getCustomerLocal(String customerID)
throws CustomerDoesNotExistException {
try { return getCustomerHome().findByPrimaryKey
(new CustomerKey(Integer.valueOf(customerID).intValue()));
} catch (FinderException e) { throw new CustomerDoesNotExistException();
}
}
private AccountLocal getAccountLocal(String accountID)
throws AccountDoesNotExistException {
try { return getAccountHome().findByPrimaryKey(accountID);
} catch (FinderException e) { throw new AccountDoesNotExistException();
}
}

Figure 12-48 Beanking bean private helper methods

Notes:
򐂰 The lookup method uses the context with the java:comp/env/ejbreference
argument to retrieve a home object.
򐂰 We do not require a getTransRecordLocal method. Transaction records are
only created (using the home) or retrieved from an account through the
relationship.

Adding business methods


To complete the facade, we have to enter its public methods as shown in
Example 12-1.

Example 12-1 Business methods of BankEJB session bean


public BigDecimal deposit(String accountID, BigDecimal amount)
throws AccountDoesNotExistException, CreateException {
AccountLocal account = getAccountLocal(accountID);
account.deposit(amount);
getTransRecordHome().create("C", amount, account);
return account.getBalance();
}
public BigDecimal withdraw(String accountID, BigDecimal amount)
throws InsufficientFundsException, AccountDoesNotExistException,
CreateException {
AccountLocal account = getAccountLocal(accountID);

Chapter 12. Developing EJB applications 423


account.withdraw(amount);
getTransRecordHome().create("D", amount, account);
return account.getBalance();
}
public BigDecimal transfer(String account1, String account2, BigDecimal amount)
throws InsufficientFundsException, AccountDoesNotExistException,
CreateException {
BigDecimal balance = withdraw(account1, amount);
deposit (account2, amount);
return balance;
}
public Customer getCustomer(String customerID)
throws CustomerDoesNotExistException {
CustomerLocal customer = getCustomerLocal(customerID);
Customer customerDTO = new Customer();
customerDTO.setId(customerID);
customerDTO.setFirstName(customer.getFirstName());
customerDTO.setLastName(customer.getLastName());
customerDTO.setTitle(customer.getTitle());
return customerDTO;
}
public Account getAccount(String accountID)
throws AccountDoesNotExistException {
AccountLocal account = getAccountLocal(accountID);
Account accountDTO = new Account();
accountDTO.setId(accountID);
accountDTO.setType(account.getType());
accountDTO.setBalance(account.getBalance());
return accountDTO;
}
public Account[] getAccounts(String customerID)
throws CustomerDoesNotExistException {
CustomerLocal customer = getCustomerLocal(customerID);
Collection accounts = customer.getAccounts();
Iterator i = accounts.iterator();
SortedSet dtoset = new TreeSet();
while ( i.hasNext() ) {
AccountLocal account = (AccountLocal) i.next();
Account accountDTO = new Account();
accountDTO.setId(account.getId());
accountDTO.setType(account.getType());
accountDTO.setBalance(account.getBalance());
dtoset.add(accountDTO);
}
return (Account[])dtoset.toArray( new Account[dtoset.size()] );
}
public TransRecord[] getTransactions(String accountID)
throws AccountDoesNotExistException {
AccountLocal account = getAccountLocal(accountID);

424 WebSphere Studio Application Developer Version 5 Programming Guide


Collection transactions = account.getTransRecords();
Iterator i = transactions.iterator();
SortedSet dtoset = new TreeSet();
while ( i.hasNext() ) {
TransRecordLocal tr = (TransRecordLocal) i.next();
TransRecord trDTO = new TransRecord();
trDTO.setTimeStamp(tr.getTimeStamp());
trDTO.setTransType(tr.getTransType());
trDTO.setTransAmt(tr.getTransAmt());
dtoset.add(trDTO);
}
return (TransRecord[])dtoset.toArray( new TransRecord[dtoset.size()] );
}

Again, you might have to organize the import statements to correct the errors.

Notes:
򐂰 As you can see by the code that you just typed in, the session facade
cannot return references of the entity beans. What it does is build data
transfer objects based on the entity data and return these objects instead.
There are many reasons for this, among which are the facts that these
entity beans do not expose a remote view, and that even if they did, it
would be terrible practice to have the control and view layers make multiple
remote calls to the model to carry on their responsibilities.
򐂰 The building process of the transfer objects is inlined in the session bean
code, making it a little bit cluttered. We did it this way for simplicity. An
alternative would have been to use builder objects.
򐂰 The getAccounts and getTransactions methods use the generated
relationship methods to retrieve a collection of related objects. The
collection is iterated and converted into an array of transfer objects. This is
done using a SortedSet to produce the result array in ascending order of
account IDs or transaction IDs.
To use a SortedSet both Account and TransRecord transfer objects
implement the compareTo method of the Comparable interface.

Promote the business methods to the remote interface


Add all seven methods to the bean’s remote interface by selecting the methods in
the Outline view and Enterprise Bean -> Promote to Remote Interface (context).

Save your changes and close the editor.

Chapter 12. Developing EJB applications 425


Generating the deployed code
If written according to the specification, EJBs can be run on any compliant
server. But for the server to be able to provide the enterprise services the bean
needs to fulfill its responsibilities, it must have generated what is called the
deploy code. This code provides the logic that connects the server-independent
deployable bean to the server-dependent implementation of the standard
services.

The name comes from the fact that this step is normally done at deploy time,
when all the definitions are complete, such as:
򐂰 Life-cycle and finder method(s) defined and promoted to the home interface
򐂰 Business logic methods defined and promoted to the component interface(s)
򐂰 Object-relational mapping completed for CMP entity beans.

Before you can successfully run your enterprise beans on either the test
environment or production server, you need to generate deployed code for the
beans.

If your EJB project contains CMP beans that have not been mapped, a default
top-down mapping is created when you generate the deployment code.

To generate deploy code for our sample EJB project, switch to the J2EE
Hierarchy view and select the EJB module (ItsoProGuideEJB). Now select
Generate > Deploy and RMIC code from the context menu. The Generate Deploy
and RMIC Code wizard appears (Figure 12-49).

Figure 12-49 Generating the deploy code

426 WebSphere Studio Application Developer Version 5 Programming Guide


By default, only those enterprise beans that have changed and require updated
deployment code are selected in the wizard. Make sure all are selected and click
Finish. Code is generated into the folder where your enterprise beans are
located.

If there is a problem with the generation of RMIC code, a window appears where
you can read any error messages that are associated with the problem. You
should not see any error messages during the deployment process if your Tasks
view does not show any errors.

Completing the EJB deployment descriptor


Before we can test the entity beans, we have to update the deployment
descriptor with WebSphere specific binding information. Open the deployment
descriptor of the ItsoProGuideEJB EJB module.

In the Overview page (Figure 12-50) add two values for the CMP Factory
Connection Binding:
򐂰 For the JNDI name enter jdbc/ejbbank. This is the JNDI name we used for
the data source definition during the setup of the WebSphere Test
Environment (see “Defining a data source in the server” on page 256).
򐂰 For the Container authorization type select Per_Connection_Factory. This
results in authorization by enterprise application. The other choice, Container,
results in authorization by the EJB container.

Also, check that the correct current Backend ID is selected (DB2UDBNT_V72_1).

Figure 12-50 WebSphere bindings in deployment descriptor

Save your changes and close the editor.

Chapter 12. Developing EJB applications 427


Changing the data source for EJB access
A data source that is used to access EJBs must be specified in a specific way.
Open the Server perspective and then open the server configuration of the
ItsoServer and go to the Data source page:
򐂰 Select the Default DB2 JDBC Provider.
򐂰 Select the EJBBANK data source and click Edit.
򐂰 Select Use this data source in container managed persistence (see
Figure 8-11 on page 257).
򐂰 Click Finish.
򐂰 Save the configuration.

Testing the EJBs


Start the ItsoServer in the Servers view. Application Developer automatically
publishes your projects to the server.

The Console view opens and you should see that the data source is allocated,
the Web and EJB modules are loaded, and the message Server server1 open
for e-business is displayed. That means that the server is now ready to serve
client requests.

Select the ItsoProGuideEJB EJB module and select Run on Server from the
selection’s context menu. If the Server Selection dialog appears, make sure that
the existing ItsoServer is selected. Select Set this server as project default (do
not prompt) and click Finish. The universal test client launches and we can test
our EJBs.

Universal test client


In this section we describe some of the operations you can perform with the
universal test client (UTC). We will use the test client to find the Customer EJB
home, find and create instances of the Customer bean, and send messages to
those instances.

Home page
Figure 12-51 shows the home page of the test client as it appears in a browser
window after selecting an EJB project and Run on Server :

428 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-51 Universal test client: home page

The test client can also be started from the Servers view by selecting a server
and then Run universal test client from the server’s context menu.

Tip: The default URL of the test client is http://localhost:9080/UTC/, so you


can also access it through an external browser. If you want to access it from
another machine, just substitute localhost with the real hostname or IP
address.

The two main pages to work with are the JNDI Explorer and the Bean page. The
JNDI Explorer is used to locate EJBs and the Bean page is used to work with
EJBs and JavaBeans.

JNDI Explorer
The JNDI Explorer allows you to browse or search for distributed objects (like
EJBs and data sources) deployed in the server. If a distributed object cannot be
found through the JNDI Explorer, it is because it was not deployed to the server
successfully.

Click JNDI Explorer to display the JNDI Explorer page (Figure 12-52).

Chapter 12. Developing EJB applications 429


Figure 12-52 Universal test client: JNDI Explorer

After expanding the [Local EJB beans], ejb and jdbc groups all the way you can
see:
򐂰 AccountLocalHome, CustomerLocalHome, and TransRecordLocalHome—The
local home interfaces to our entity beans.
򐂰 BankEJBHome—The remote home interface to our session bean.
򐂰 jdbc/ejbbank—The data source to the EJBBANK database.

To work with the Customer EJB, we click the CustomerLocalHome link, which
brings us to the Beans page.

Beans page
The Beans page shows EJB references (homes and components), object
references (any objects that are used and kept during the session), class
references (classes that are loaded explicitly), and utilities (which provides
various functions, such as the ability to load a class and cast an instance).

In the JNDI explorer, we selected the CustomerLocalHome and therefore it shows


up under EJB References once we expand that section (Figure 12-53).

430 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 12-53 Universal test client: references on bean page

The create and findByPrimaryKey methods of the home interface are visible
under the CustomerLocal home. In addition, findCustomerByAccountsKey_Local
and remove methods are visible as well. The finder method was automatically
generated to support the customer-account relationship.

Click Method Visibility and you can see from which superclasses and interfaces
methods are inherited, and which ones are selected to be displayed for the
customer home.

To find an EJB instance by its primary key, select the findByPrimaryKey method.
Note that, in this case, the method parameter type is an object type, and a
non-literal one. This means that we first have to create an instance of that type to
be able to call the finder method.

Note: Objects of non-literal types have to be constructed through an explicit


use of the new operator. Objects of literal types, such as java.lang.String,
may be constructed without using the new operator (i.e. “I am a String
object”). In Java, the only literal object types are string and arrays.

Click findByPrimaryKey to display the method in the Parameters pane


(Figure 12-54):

We have to select values for two different list boxes. The first one lets you specify
whether you want to pass an object as a parameter, or just a null reference
instead. Select Objects. The second list then lets you select which constructor to
use. Select CustomerKey(int).

Chapter 12. Developing EJB applications 431


Figure 12-54 Universal Test Client: non-literal object parameter (1)

After you do that, expand the CustomerKey tree and enter a customer ID (for
example, 102) and click Invoke.

A CustomerLocal object is retrieved. Click Work with Object to add the result to
the EJB references (Figure 12-55).

Figure 12-55 Universal Test Client: findByPrimaryKey

432 WebSphere Studio Application Developer Version 5 Programming Guide


Expand the CustomerLocal reference and run some of the methods. For
example, select the getLastName method and click Invoke to display the
customer’s last name (Figure 12-56).

Figure 12-56 Universal Test Client: run customer methods

To remove unwanted objects from the universal test client pane, click the scissor
icon that is displayed next to the object name.

Working with the session bean


Select the BankEJBHome in the JNDI Explorer.

Tip: If you know which EJB you would like to test and want to skip having to
browse for the bean using the JNDI Explorer, you can select the bean in the
EJB module and select Run on Server from its context menu. The UTC will
automatically switch to the Bean page, where a home reference to the
selected bean is instantiated.

A session bean must be created first. Expand the home reference, select the
create method and click Invoke. Click Work with Object to add a session bean
reference.

Select the withdraw method, enter 102-2001 as account number and 375.26 as
amount. Click Invoke (Figure 12-57).

Chapter 12. Developing EJB applications 433


Figure 12-57 Universal Test Client: run BankEJB business method

Select the getAccount method, enter 102-2002 as account number, click Invoke,
then click Work with Object. An object reference of type Account is added.

Remember, getAccount returns a data transfer object. Note that the account data
is displayed because Account has a toString method.

Figure 12-58 Universal test Client: working with a result object

Expand the Account object and run some of the getter methods.

434 WebSphere Studio Application Developer Version 5 Programming Guide


In the BankEJB reference select the getTransactions method. Enter an account
number, 102-2001, and click Invoke. Click Work with Object to add the result
array to the object references (Figure 12-59).

Figure 12-59 Universal test Client: working wit a result array (1)

Expand the TransRecord[2] array and select Inspect Fields. The array is added
to the Parameters pane. Select one of the objects and click the icon on its
right side to add the object as a result. Click Work with Object to add the result
object to the references, from where you can run its methods (Figure 12-60).

Figure 12-60 Universal test Client: working wit a result array (2)

Chapter 12. Developing EJB applications 435


You can play with the UTC to make sure all of your EJBs work. Another method
you can try is the getAccounts method of the BankEJB bean. It returns an array of
Account beans for one customer. Use the same technique as for the array of
transaction records to explore the array of accounts.

When you are done, close the browser and stop the server in the Servers view.

Adapting the Web applications


Our two Web applications, ItsoProGuideBasicWeb and ItsoProGuideStrutsWeb,
use the Banking facade to access the in-memory Bank.

We can now replace the Banking facade with a new facade that interacts with our
EJB implementation. We provide the new facade in:
\sg246957\sampcode\dev-ejb\facade\Banking.java

Import the new facade into both Web projects, ItsoProGuideBasicWeb and
ItsoProGuideStrutsWeb:
򐂰 Select the itso.bank.facade package in the J2EE Navigator view and Import
(context).
򐂰 Select File system and click Next.
򐂰 Click Browse and navigate to the \sg246957\sampcode\dev-ejb\facade
directory.
򐂰 Select Overwrite existing resources with warning and click Finish.

Study the new Banking facade:


򐂰 First a switch is defined that enables the facade to run against the new
BankEJB session EJB or against the old in-memory Bank JavaBean.
//the Switch: EJB=true Memory=false
boolean ejb = true;
򐂰 The BankEJBHome is acquired in lazy mode at the first access using an EJB
reference, and a session bean is created from the home interface:
getBankEJBHome:
Object ior = new InitialContext().lookup("java:comp/env/ejb/BankEJB");
bankEJBHome = (BankEJBHome) PortableRemoteObject.
narrow(ior, BankEJBHome.class);

getBankEJB:
getBankEJBHome().create();

436 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 All the business methods have the same kind of coding:
public BigDecimal deposit(String accountID, BigDecimal amount)
throws AccountDoesNotExistException, BankException {
try {
if (ejb) return getBankEJB().deposit(accountID, amount);
else return getBank().deposit(accountID, amount);
} catch (RemoteException e) { throw new BankException();
} catch (CreateException e) { throw new BankException(); }
}
򐂰 The BankException is used to signal if an EJB access failed.

Web project dependencies


You may have noticed that the import procedure produced errors and warnings.
If not, open the Tasks view by selecting Window -> Show View -> Tasks. Inspect
briefly the errors and warnings. They have to do with the fact that we are still
short of some of the Java types the imported resources reference. These are
associated with the EJBs that we developed during this chapter.

As you know, some resources in the Web project reference other resources in
the EJB project, for the control layer resides in the Web module and the model
layer now resides in the EJB module (Figure 12-4 on page 385).

The model layer does not know about the control layer, but the control layer must
be able to reference the model layer. For that to work, we have to add the EJB
project to the Web project’s classpath.

Select the ItsoProGuideBasicWeb project and Properties from its context menu.
Select the Java JAR Dependencies group and add the ItsoProGuideEJB project
as a dependency (Figure 12-61).

Repeat this step for the ItsoProGuideStrutsWeb project.

Chapter 12. Developing EJB applications 437


Figure 12-61 Properties for the Web projects

EJB references
Web projects access an EJB either through the global JNDI name of the bean, or
through an EJB reference. The second approach is better because it makes the
Web application coding independent of the JNDI name.

However, the reference must be defined in the Web deployment descriptor,


web.xml.

Open the deployment descriptor of the ItsoProGuideBasicWeb project and go to


the References page:
򐂰 Select the EJB tab (the first one).
򐂰 Click Add to add a reference.
򐂰 Overtype the name with ejb/BankEJB, the name used in the Banking class to
acquire the home interface.
򐂰 Click Browse for the Link field and select the BankEJB. It is the only bean that
has a remote interface. (References to local interfaces would be defined on
the EJB Local tab.)
򐂰 All the required information is filled into the dialog (Figure 12-62).

438 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Save the deployment descriptor.

Repeat this step for the ItsoProGuideStrutsWeb project.

Figure 12-62 Defining an EJB reference in a Web project

Testing the Web interface


Nothing has changed with the RedBank’s presentation layer since it was first
developed in Chapter 7, “Developing Web applications” on page 179 for the
ItsoProGuideBasicWeb project and in Chapter 10, “Developing Struts
applications” on page 293 for the ItsoProGuideStrutsWeb project.

As a consequence, the testing of the Web interface should be done exactly as


described in “Testing the application” on page 225:
򐂰 Restart the ItsoServer.
򐂰 Select the ItsoProGuideEJBWeb project and Run on Server. The welcome
page is displayed and you can run some transactions.
򐂰 Repeat the testing for the ItsoProGuideStrutsWeb project.

Persistence: In the first implementation, every time you started the Web
application you got the same data because it was created in memory. Now we
are running with EJBs accessing the underlying EJBBANK database. All our
updates are persistent. The updated balance is stored in the database and the
transaction records accumulate for each account.

Chapter 12. Developing EJB applications 439


Summary
In this chapter we developed three entity beans with two relationships and a
session bean. The entity beans provide the interface to a relational database.
The session bean is the facade for the Web client. Transactions are handled
automatically through the session bean methods.

The use of the MVC architecture we could reuse the Web projects and connect
them to the EJB backend implementation.

As you can see, it paid off to have applied the MVC architectural pattern. We only
has to replace one class, the Banking facade, in the Web projects and they run
with a persistent back end.

Tip: You can reset the data in the EJBBANK database by rerunning the
loadbank.bat file in the _setup directory of the sample code.

For complete coverage of EJBs, refer to the IBM Redbook EJB 2.0 Development
with WebSphere Studio Application Developer, SG24-6819.

440 WebSphere Studio Application Developer Version 5 Programming Guide


13

Chapter 13. Developing Web services


In this chapter we introduce the service-oriented architecture (SOA) for
distributed Web-based systems. We explain the Web Services approach, to give
an introduction to the concept of a Web Service. This will provide the background
needed to understand what is going on when we develop a Web service based
on an existing JavaBean.

The chapter covers the following topics:


򐂰 The concept of a service-oriented architecture (SOA)
򐂰 Web services approach for an SOA architecture
򐂰 Creating a Web service from a JavaBean

For more information about Web services, please refer to IBM Redbook
WebSphere Version 5 Web Services Handbook, SG24-6891.

© Copyright IBM Corp. 2003. All rights reserved. 441


The concept of a service-oriented architecture (SOA)
Each component in a service-oriented architecture can play one (or more) of
three roles: service provider, broker, and requestor, which perform the operations
shown in Figure 13-1.

Legacy
system

2
1
Service Internet Service
Requestor Provider
3

Service
Broker

Figure 13-1 Web services roles and operations

1. The service provider creates a Web service and possibly publishes its
interface and access information to the service registry.
Each provider must decide which services to expose, how to make trade-offs
between security and easy availability, how to price the services (or, if they
are free, how to exploit them for other value). The provider also has to decide
what category the service should be listed in for a given broker service and
what sort of trading partner agreements are required to use the service.
2. The service broker (also known as service registry) is responsible for making
the Web service interface and implementation access information available to
any potential service requestor.
The implementers of a broker have to decide about the scope of the broker:
Public brokers are available all over the Internet, while private brokers are
only accessible to a limited audience, for example, users of a company-wide

442 WebSphere Studio Application Developer Version 5 Programming Guide


intranet. Furthermore, the width and breadth of the information offered has to
be decided. Some brokers will specialize in breadth of listings. Others will
offer high levels of trust in the listed services. Some will cover a broad
landscape of services and others will focus within a given industry. Brokers
will also arise that simply catalog other brokers. Depending on the business
model, a broker may attempt to maximize look-up requests, number of
listings, or accuracy of the listings.
3. The service requestor locates entries in the broker registry using various
find operations and then binds to the service provider in order to invoke one of
its Web services.
One important issue for users of services is the degree to which services are
statically chosen by designers compared to those dynamically chosen at
runtime. Even if most initial usage is largely static, any dynamic choice opens
up the issues of how to choose the best service provider, and how to assess
quality of service. Another issue is how the user of services can assess the
risk of exposure to failures of service suppliers.

Web services approach for an SOA architecture


Web services are a rather new technology that implements the service-oriented
architecture. A major focus during the development of this technology was put on
the goal to make functional building blocks accessible over standard Internet
protocols that are independent from platforms and programming languages.

Web services are self-contained, modular applications that can be described,


published, located, and invoked over a network. Web services perform
encapsulated business functions, ranging from simple request-reply to full
business process interactions.

These services can be new applications or just wrapped around existing legacy
systems to make them network-enabled. Services can rely on other services to
achieve their goals.

The core technologies used for Web services are:


򐂰 XML (eXtensible Markup Language) is the markup language that underlies
most of the specifications used for Web services. XML is a generic language
that can be used to describe any kind of content in a structured way,
separated from its presentation to a specific device.
򐂰 SOAP (formerly referred to as Simple Object Access Protocol, or
Service-Oriented Architecture Protocol—in fact, similarly to JDBC, it is no
longer an acronym) is a network, transport, and programming language

Chapter 13. Developing Web services 443


neutral protocol that allows a client to call a remote service. The message
format is XML.
򐂰 WSDL (Web services description language) is an XML-based interface and
implementation description language. The service provider uses a WSDL
document in order to specify the operations a Web service provides, as well
as the parameters and data types of these operations. A WSDL document
also contains the service access information.
򐂰 UDDI (universal description, discovery, and integration) is both a client side
API and a SOAP-based server implementation which can be used to store
and retrieve information on service providers and Web services.

Figure 13-2 shows a first glance at the relationship between the core elements of
the SOA.

XSD XML WSDL

Metadata/vocabulary Service description

UDDI
(Broker)
HTTP
Runtime
transports

SOAP other

Requestor Provider

SOA Runtime

J2EE other
Implementation

Figure 13-2 Main building blocks in a SOA approach based on Web services

򐂰 All elements use XML, including XML namespaces and XML schemas.
򐂰 Service requestor and provider communicate with each other.
򐂰 WSDL is one alternative to make service interfaces and implementations
available in the UDDI registry.
򐂰 WSDL is the base for SOAP server deployment and SOAP client generation.

444 WebSphere Studio Application Developer Version 5 Programming Guide


Web services tools in Application Developer
Application Developer provides tools to create Web services in bottom-up and
top-down approaches, as well as tools for Web services client development.

Bottom-up development of a Web service


Application Developer provides a wizard for bottom-up Web services
development. The following data structures can be used to build a Web service:
򐂰 JavaBean—The Web service wizard assists you in creating a new Web
service, configuring it for deployment, and deploying the Web service to a
server (which can be the test environment that comes with Application
Developer, or an external application server).
򐂰 EJB—The Web service wizard assists you in creating a new Web service,
configuring it for deployment, and deploying the Web service to a server.
򐂰 DADX—Document access definition extension (DADX) is an XML document
format that specifies how to create a Web service using a set of operations
that are defined by DAD documents and SQL statements. A DADX Web
service enables you to wrap DB2 XML Extender or regular SQL statements
inside a standard Web service. The DADX file defines the operations
available to the DADX run-time environment, and the input and output
parameters for the SQL operation.
򐂰 URL—The Web service wizard assists you in creating a new Web service
that directly accesses a servlet running on a remote server.
򐂰 ISD—An ISD file is a Web service deployment descriptor and provides
information to the SOAP run-time about the service that should be made
available to clients, for example URI, methods, implementation classes
(JavaBean, EJB), serializers, and deserializers. ISD files are concatenated
into the SOAP deployment descriptor, dds.xml.

Top-down development of a Web service


For top-down development, Application Developer provides these functions:
򐂰 JavaBean from WSDL—The Web service wizard assists you in creating a
skeleton JavaBean from an existing WSDL document. The skeleton bean
contains a set of methods that correspond to the operations described in the
WSDL document. When the bean is created, each method has a trivial
implementation that you replace by editing the bean.
򐂰 JavaBean from XSD—The Web services tools support the generation of
JavaBeans from an XML schema. Using these beans, you can create a
JavaBean Web service.

Chapter 13. Developing Web services 445


Client development
To assist in development of Web service clients, Application Developer provides
this function:
򐂰 Java client proxy and sample application from WSDL—The Web service
client wizard assists you in generating a proxy JavaBean and a sample
application. The sample Web application demonstrates how to use the proxy
bean in a client program.
Note that the proxy and sample can also be generated in bottom-up and
top-down approaches for testing of the generated Web service.

Preparation for samples


We will use a new Web project named ItsoProGuideWebServ to work with Web
Services:
򐂰 Create the ItsoProGuideWebServ project as part of the ItsoProGuide
enterprise application, with a dependency to the ItsoProGuideJava utility
project (we are using the exception classes and some model classes).
򐂰 Create a package named itso.webserv.model (under Java Source).
򐂰 Import the three model classes into the itso.webserv.model package using
the code in:
\sg246957\sampcode\dev-webserv\initial
The three classes are Banking (a subset of the Banking class used in the
previous projects), AccountDB (which accesses the ACCOUNT table to retrieve
and update accounts using JDBC), and Account (a subset of the Account
model class without transaction records).
򐂰 You can also import the RunBanking.jsp into the Web Content folder for
testing.

Creating a Web service from a JavaBean


As explained above, Web services can be created using any number of existing
or new applications. Here, we will create a Web service from an existing
JavaBean.

The imported application contains the Banking JavaBean that can be used to get
details about a particular Account, and to deposit, withdraw, and transfer funds. It
acts as a facade, hiding the database access. Behind the facade is another
JavaBean, AccountDB, that accesses the EJBBANK database. Two helper classes

446 WebSphere Studio Application Developer Version 5 Programming Guide


(Account and TransRecord, the same as the data transfer objects used for the
EJBs) and one new exception (AccountDatabaseException) round off the model.

Using a facade allows us to change the way the application accesses the
database, for example using EJBs instead of JavaBeans, without affecting the
remainder of the application.

You should already have created and configured the ItsoServer with an EJBBANK
data source.

We will describe how to use WebSphere Studio wizard to create a Web service
that returns information from the Banking service. The wizard guides us through
generating the WSDL document from the JavaBean, creating a proxy bean, and
testing the Web service in a Web browser using the generated test JSPs.

Creating the Web service using the Web Service wizard


To create the Web service, including the WSDL document, deployment
descriptor, proxy, and test sample, we use the Web Service wizard.

Select File -> New -> Other. Select Web Services to display the various Web
service wizards. Select Web Service and click Next to start the Web Service
wizard.

We go through all the pages of the wizard. Click Next on each page to get to the
next dialog.

From the Web service type drop-down menu select Java bean Web service.
Ensure that Start Web service in Web project is selected (this will start the
server). Select all the following check boxes:
򐂰 Generate a proxy (for testing)
򐂰 Test the generated proxy
򐂰 Overwrite files without warning
򐂰 Create folders when necessary

From the Client proxy type drop down menu, ensure that Java proxy is selected.
Figure 13-3 shows the dialog after making these selections.

Note: A Java proxy provides a remote procedure call interface to the Web
service. It is used by other Java classes to access the Web service.

Chapter 13. Developing Web services 447


Figure 13-3 Web Service wizard

Deployment Settings
The Web Service Deployment Settings page allows you to select from supported
run-time protocols and deployment servers. Select Use Defaults and make sure
that ItsoProGuideWebServ is selected as the Web project.

Java Bean Selection


The Web Service Java Bean Selection page allows you to specify the Java bean
to be turned into a Web service. Click Browse files (or Browse classes) and
locate the itso.webserv.model.Banking JavaBean.

Java Bean Identity


On the Web Service Java Bean Identity page, you specify the Web service
uniform resource identifier (URI), scope, and the names of the generated files.
We now briefly describe the options before we continue:
򐂰 Web service URI—A URI is a name that uniquely identifies a Web service to a
client. The URI for the Web service is automatically generated by the wizard
from the artifact you selected to turn into a Web service:

448 WebSphere Studio Application Developer Version 5 Programming Guide


http://tempuri.org/itso.webserv.model.Banking
You could overwrite the default name, for example, urn:Banking, but we leave
the default name.
򐂰 Web service scope—Three alternatives are available to define the scope of
the Web service:
– Request—A new service bean is constructed by the server for each
SOAP request. The object is available for the duration of the request.
– Session—One service bean is constructed by the server for each new
client session to the Web service, and is maintained by sending cookies to
the client side. The bean is available for the duration of the session in a
similar way to HTTP session data.
– Application—A single instance of the service bean is constructed for the
life of the Web application. This is the best option for good performance,
but requires that the JavaBean is written in reentrant fashion so that
multiple requests can run through the code in parallel. This is the default
for a JavaBean.
Select Request, our bean is not thread safe. This information will be part of
the deployment descriptor for the Web service.
򐂰 Use static methods—If this option is selected, the bean’s static methods
become Web service operations and no object is instantiated. Do not select.
򐂰 Enable SOAP security—The Web service wizard also provides an option to
apply security to the SOAP router servlet when deploying the Web services in
the project to a WebSphere instance and configuration. Do not select.
Because one instance of the SOAP router servlet exists for each Web
application (WAR file), this option can only be edited when creating the first
Web service for the project. When creating further Web services with the Web
service wizard, this option will be disabled, showing the status of the first
selection. This can be changed manually after generation by editing the
deployment descriptor (web.xml).
򐂰 The generated files include the ISD file and four WSDL files.

Java Bean Methods


The Web Service Java Bean Methods page (Figure 13-4) shows a summary of
public methods in your bean. For the example we select all methods. Also, select
Show server (Java to XML) type mappings.

When you select a method, the input and output encoding are displayed. The
encoding style defines how the Java types in the client and server are mapped to
the XML types in the SOAP message:

Chapter 13. Developing Web services 449


򐂰 For all three methods, SOAP encoding is selected by default. SOAP encoding
covers all basic data types as well as JavaBeans containing basic data types.
򐂰 Literal XML encoding would be used for a document object model (DOM)
element (org.w3c.dom.Element). The XML source is then inserted directly into
the SOAP message.

Figure 13-4 Method selection

Java to XML Mappings


On the Web Service Java to XML Mappings page, review the Web service type
mappings. At run time, the mappings govern serialization and deserialization.
Figure 13-5 illustrates the mappings between Java and XML for the Web service
to operate, assuming both a Java client and a Java server.

Input encoding style

Java to XML XML to Java


1 mapping 2 mapping
SOAP
Client Proxy messages
Server
XML to Java Java to XML
4 mapping 3 mapping
Output encoding style
Figure 13-5 mapping and encoding stages for a Web service

450 WebSphere Studio Application Developer Version 5 Programming Guide


There are four steps in the process, indicated by the numbers in Figure 13-5:
1. Client input mapping (Java to XML)—This takes the parameter from the Java
client and maps it using the input encoding style.
2. Server input mapping (XML to Java)—The inbound parameters are
deserialized from the SOAP encoding style in the message to Java types,
which are then used to invoke the method in the JavaBean.
3. Server output mapping (Java to XML)—Once the JavaBean has completed its
method execution, the return value is inserted into the SOAP reply using the
output encoding style.
4. Client output mapping (XML to Java) —The final stage is performed by SOAP
for the client proxy, which maps the returned XML elements into Java types.

The current page of the wizard shows the language mapping from Java types to
XML types (Figure 13-6).

Figure 13-6 Defining Java to XML bindings

Chapter 13. Developing Web services 451


Note: The types that are displayed are method input parameters (String,
BigDecimal), method results (Account, TransRecord), as well as data types
inside the Account bean (String, BigDecimal).

Binding Proxy Generation


In the Web Service Binding Proxy Generation page (Figure 13-7), review the
bindings that are used in the WSDL. The client proxy provides a remote
procedure call interface to your Web service. Using the proxy, the application
calls a remote method on the Web service as if the method were a local one.
Once the application makes the remote call, the proxy handles all of the
communication details between the application and the Web service using SOAP.

Note that the proxy is generated into a separate Web project named
ItsoProGuideWebServClient. You could change the default project name if you
wanted. The name of the proxy defaults to proxy.soap.BankingProxy. Select the
Show mappings check box.

Figure 13-7 Proxy generation

452 WebSphere Studio Application Developer Version 5 Programming Guide


XML to Java Mappings
In the Web Service XML to Java Mappings page (Figure 13-8), review the
mapping for deserialization from XML to Java types. For each XML type the Java
type is displayed in the Class field.

Figure 13-8 Defining XML to Java bindings

SOAP Binding Mapping Configuration


In the Web Service SOAP Binding Mapping Configuration page, review the Web
service SOAP binding mapping configuration. These are set based on our
previous definitions in the wizard and cannot be changed in our example.

Test
In the Web Service Test page (Figure 13-9), you decide which facility to use to
test the Web service. The choices are:
򐂰 Web service sample JSPs—Generates a set of four JSPs into the folder
sample/Banking in the client Web project (select this option).
򐂰 Web tools Java bean JSPs—Generates an HTML page, a result JSP, and a
ViewBean class into the client Web project (does not function with the
BigDecimal class).
򐂰 Universal Test Client—The universal test client is started and the proxy
bean is instantiated. You can always use the universal test client even if you
generate a sample.

Chapter 13. Developing Web services 453


The ItsoServer is used as the server.

Figure 13-9 Testing options for the Web service

Publication
In the Web Service Publication page you can publish the Web service to a UDDI
registry. For now, leave the boxes unchecked and click Finish.

Finish
The Web service is deployed in the Web project and the Web project is deployed
to a WebSphere test server:
򐂰 An existing server is updated (WebSphere v5.0 Test Environment).
򐂰 The enterprise application is added to the configuration.
򐂰 The sample JSP test client is launched to test the Web service.

454 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 The Web Service Explorer is launched in an external Web browser to publish
the Web service (only if you select publishing in the last step of the wizard).

If you have problems creating the Web service, consult the online documentation
and the d:\workspace\.metadata\.log file.

Generated files
Before we test the Web service, let’s look at the generated files (Figure 13-10).

JavaBean
Starting point

Helper

Admin Proxy
application

Test
sample

ISD file
SOAP runtime

XSD files

Client project
WSDL files
deployment
descriptor
Server project
Figure 13-10 J2EE Navigator view after the generation of the Web service

The Web service is installed in the ItsoProGuideWebServ project and the proxy
and sample test client are in the ItsoProGuideWebServClient project.

Chapter 13. Developing Web services 455


Files generated in the server Web project
According to the settings made during the run of the wizard, the following files in
the ItsoProGuideWebServ project have been created:
򐂰 The Web service deployment descriptor Banking.isd in Web
Content/WEB-INF/isd/java/itso/webserv/model provides information about
the services that should be made available to clients. This information is
added to the dds.xml file, the SOAP deployment descriptor, and used by the
SOAP run-time.
򐂰 The Web Content/WEB-INF/lib folder is extended with three library files that
are part of the SOAP run-time code:
– soapcfg.jar
– webservice-runtime.jar
– xsd.bean.runtime.jar
򐂰 The Web Content folder contains the admin folder where SOAP administration
can be performed (select the index.html and Run on Server).
򐂰 In the Web Content folder, a new folder wsdl/itso/webserv/model contains the
WSDL files and an XSD file:
– Banking.wsdl—service interface
– BankingBinding.wsdl—service binding
– BankingJava.wsdl—service binding for Java (for WSIF)
– BankingService.wsdl—service implementation
– Banking.xsd—which defines how the TransRecord array object is mapped
to XML
The wsdl/itso/bank/model folder contains the XSD files of the return types
Account and TransRecord.
򐂰 Finally, the Web Content folder itself contains the files:
– dds.xml, the deployment descriptor for SOAP, a concatenation of all the
ISD files (only one for now)
– soap.xml, the Apache SOAP server configuration file

Tip: The Banking.xsd file will show errors if you are not connected to the
Internet because the import statements cannot be resolved. You can ignore
the errors, the WSDL files are not used at runtime.

Files generated in the client Web project


If the creation of a client-side proxy is selected, Application Developer generates
two classes in the new ItsoProGuideWebServClient project:
򐂰 itso.bank.model package contains the Account and TransRecord objects,
mapped from the XML representation into a Java class.

456 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 proxy.soap.BankingProxy is the proxy class that contains the methods
withdraw, deposit, and getAccount. These methods can now be locally
invoked by a client (see “Implementing a real client application” on page 465).

The test client is generated into the Web Content/sample/Banking folder.

Client Account class


The generated client-side Account class (Figure 13-11) provides the same
accessor methods as the original Account class that we imported into the Web
project.

package itso.webserv.model;

import ....;

public class Account extends AnyType


{
public Account() {
addElement("type", java.lang.String.class);
addElement("balance", java.math.BigDecimal.class);
addElement("id", java.lang.String.class);
}
public String getType() {
return (String)this.basicGet("type", 0);
}
public void setType(String type) {
this.basicSet("type", 0, type);
}
public BigDecimal getBalance() {
return (BigDecimal)this.basicGet("balance", 0);
}
public void setBalance(BigDecimal balance) {
this.basicSet("balance", 0, balance);
}
public String getId() {
return (String)this.basicGet("id", 0);
}
public void setId(String id) {
this.basicSet("id", 0, id);
}
}

Figure 13-11 Generated account class (extract)

Chapter 13. Developing Web services 457


Proxy class
Figure 13-12 shows the getAccount method of the proxy class as an example of
the processing in the proxy.

public class BankingProxy


{
private Call call;
private URL url = null;
private String stringURL =
"http://localhost:9080/ItsoProGuideWebServ/servlet/rpcrouter";
private java.lang.reflect.Method setTcpNoDelayMethod;

......

public synchronized itso.webserv.model.Account getAccount


(java.lang.String accountId) throws Exception {
String targetObjectURI = "http://tempuri.org/itso.webserv.model.Banking";
String SOAPActionURI = "";

if(getURL() == null) {
throw new SOAPException(Constants.FAULT_CODE_CLIENT,
"A URL must be specified via BankingProxy.setEndPoint(URL).");
}

call.setMethodName("getAccount");
call.setEncodingStyleURI(Constants.NS_URI_SOAP_ENC);
call.setTargetObjectURI(targetObjectURI);
Vector params = new Vector();
Parameter accountIdParam = new Parameter("accountId", java.lang.String.class,
accountId, Constants.NS_URI_SOAP_ENC);
params.addElement(accountIdParam);
call.setParams(params);
Response resp = call.invoke(getURL(), SOAPActionURI); <==== Web Service Call

//Check the response.


if (resp.generatedFault()) {
Fault fault = resp.getFault();
call.setFullTargetObjectURI(targetObjectURI);
throw new SOAPException(fault.getFaultCode(), fault.getFaultString());
}
else
{
Parameter refValue = resp.getReturnValue();
return ((itso.webserv.model.Account)refValue.getValue());
}
}
......

Figure 13-12 Generated proxy class (extract)

458 WebSphere Studio Application Developer Version 5 Programming Guide


A Call object is filled with the method name, encoding style, target URI, and
parameters. The Web service is invoked and the result examined. A good result
is converted into the required return type.

Testing the Web service


There are two ways to test the generated proxy code:.
򐂰 Using the generated sample test application, which is composed of a set of
four JSPs
򐂰 Using the universal test client with the proxy class

Using the sample test application


By selecting Test the generated proxy in the Web services wizard (Figure 13-9 on
page 454), the sample test client is started in a browser pane with this URL:
http://local..:9080/ItsoProGuideWebServClient/sample/Banking/TestClient.jsp

Figure 13-13 shows the sample test client in the internal browser. You can also
type the URL into an external browser.

Select a method (for example getAccount, enter the parameter, click Invoke, and
the result is displayed.

Figure 13-13 Sample test client

Chapter 13. Developing Web services 459


Note that the deposit, withdraw and transfer methods have no result, but you
can check if they worked by using the getAccount method and verifying the
balance amount.

The sample test client was created in the new ItsoProGuideWebServClient Web
project called. If the browser does not launch automatically, follow these steps:
򐂰 Select the TestClient.jsp in sample/Banking then select Run on Server from
the context menu.
򐂰 In the Select Server dialog, select Use an existing server and select the
ItsoServer. Also select Set server as project default, then click Finish.

Using the universal test client


To test a Web service with the universal test client, select the proxy class
(proxy.soap.BankingProxy) and Launch Universal Test Client (context).

An instance of the proxy class is instantiated and you can run its methods
(Figure 13-14).

Figure 13-14 Web service testing with universal test client

Click Work with Object to add the result Account object to the object references.
Expand the Account object to run its getter methods.

460 WebSphere Studio Application Developer Version 5 Programming Guide


Creating a Web service client
Application Developer has wizards to create a client that accesses an existing
Web service. We now explain how to quickly create a Java proxy, given a WSDL
file, in order to access a Web service from a Web application.

We use the WSDL file generated by the Web service wizard in “Creating a Web
service from a JavaBean” on page 446.

To simulate the activities of a real client, we copy the WSDL files from the server
Web project to the client Web project:
򐂰 Copy the wsdl folder and all its subfolders:
From: ItsoProGuideWebServ/Web Content
To: ItsoProGuideWebServClient/Web Content
Select the wsdl folder and Copy (context), then select the target Web Content
folder and Paste (context).

For this exercise, imagine that the server Web project is on another server
somewhere in the Internet. All you have available is the description of the Web
service in the form of the WSDL files.

From the WSDL files, we generate a client proxy and a test sample and verify
that the Web service works.

Both the client and the service actually run on the same machine.

Run the Web Service Client wizard


Expand ItsoProGuideWebServClient/Web Content/wsdl, select the
BankingService.wsdl file and New -> Other -> Web Services -> Web Service
Client.

Click Next to start the Web service client wizard. We go through all the pages of
the wizard. Click Next on each page to get to the next dialog.

In the first page of the wizard, select the Test the generated proxy check box, as
shown in Figure 13-15. This causes the wizard to create sample JSP files that we
will use later to verify that the proxy works properly.

Chapter 13. Developing Web services 461


Figure 13-15 Web Service Client wizard

In the Web Services WSDL File Selection page, the BankingService.wsdl file
that you selected earlier is entered in the WSDL file name or URL text box, as
shown in Figure 13-16. Here you could enter the URL to a WSDL file on the
Internet, or click Browse to select a different file that exists in your workspace.

Figure 13-16 Select a WSDL file

The panels that follow are the same as when we created the Web service. We
will only make a few changes to create different classes and JSPs
(Figure 13-17):
򐂰 For the proxy we change the name to proxy.soap.ClientBankingProxy.
򐂰 For the sample test application we use sample/ClientBanking as output
folder.

462 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 13-17 Client proxy and sample application generation

Click Finish to generate the Java proxy and sample JSPs.

After the files are generated, an internal Web browser opens the
TestClient.jsp, as explained in “Testing the Web service” on page 459.

Note that you have now two proxy classes and two folders with a sample test
application. The code of both is identical.

Application Developer provides an easy way to create a client Java application for
a Web service. The Web Service Client wizard generates the Java proxy and,
optionally, a sample Web application that gets you started quickly in using Web
services in your Web applications.

Chapter 13. Developing Web services 463


Creating a Web service from a session bean
Creating a Web service from an EJB session bean is very similar to the process
for a JavaBean. There are only a few differences. Let us go through the process
in abbreviated fashion:
򐂰 In the J2EE Hierarchy view, expand the ItsoProGuideEJB project.
򐂰 Select the BankEJB session bean and New -> Other -> Web Services -> Web
Service.
򐂰 The type of Web service is now preselected as EJB Web service. Select
Generate a proxy and Test the generated proxy.
򐂰 Select the ItsoProGuideWebServ project as the Web project.
򐂰 Leave all the defaults on the EJB configuration.
򐂰 Leave all the defaults on the identity. The URI is:
http://tempuri.org/itso.ejb.model.facade.BankEJB
򐂰 Leave all the methods selected.
򐂰 Leave the proxy class to proxy.soap.BankEJBProxy.
򐂰 Leave the sample test application folder as sample/BankEJB. Make sure the
client project is ItsoProGuideWebServClient.
򐂰 Click Finish.

The code is generated and the test client opens (Figure 13-18).

Figure 13-18 Web service sample for EJB service

464 WebSphere Studio Application Developer Version 5 Programming Guide


Notes:
򐂰 If you encounter runtime errors, restart the server.
򐂰 Methods that return collections are not supported in the test client,
because an instance cannot be created.
򐂰 The methods of our session bean return arrays of objects; these are very
well supported by SOAP encoding.

Implementing a real client application


We provide a very simple client consisting of one JSP to execute the deposit and
withdraw methods of the Banking service:
򐂰 Import the TestBankingWebService.jsp into the ItsoProGuideWebServClient
project (Web Content folder).
򐂰 The main logic is shown in Figure 13-19:
– A proxy bean (proxy.soap.ClientBankingProxy) to invoke the Web
service is allocated using <useBean>.
– The parameters from the form are retrieved and tested.
– Depending on the Submit button, either the deposit or withdraw method of
the Web service is invoked.
– After the banking operation, the getAccount method is invoked so that we
can display the account information.
– The rest is HTML code with JSP tags to display the form with input fields
and push buttons, and to display the resulting account information.
– Note that the proxy and the Account classes are imported.

The client proxy makes coding of a real client very simple.

Chapter 13. Developing Web services 465


<jsp:useBean id="proxy" class="proxy.soap.ClientBankingProxy"
scope="session"></jsp:useBean>

<%! String accid = null;


String amount = null;
String deposit = null;
String withdraw = null;
java.math.BigDecimal amountD = new java.math.BigDecimal(0.00);
Account account = new Account();
%>
<%
accid = request.getParameter("accountid");
amount = request.getParameter("amount");
deposit = request.getParameter("deposit");
withdraw = request.getParameter("withdraw");
if ( accid != null && amount != null && !accid.trim().equals("")
&& !amount.trim().equals("") ) {
amountD = new java.math.BigDecimal(amount);
if ( deposit != null ) proxy.deposit(accid, amountD);
if ( withdraw != null ) proxy.withdraw(accid, amountD);
account = proxy.getAccount(accid);
}
%>
<h1>Banking Web Service Test</h1>
<FORM action="/ItsoProGuideWebServClient/TestBankingWebService.jsp"
method="post">
<TABLE>
<tr><td>Enter an account number:</td>
<td><INPUT type="text" name="accountid" size="20"
value="<%= accid %>"></td></tr>
<tr><td>Enter an amount:</td>
<td><INPUT type="text" name="amount" size="20"></td></tr>
<tr><td>&nbsp; </td>
<td><INPUT type="submit" name="deposit" value="Deposit">
<INPUT type="submit" name="withdraw" value="Withdraw"></td></tr>
</TABLE>
<h2>Account information</h2>
<TABLE border="1">
<tr><td>Account number: </td><td><%= account.getId() %> </td></tr>
<tr><td>Account type: </td><td><%= account.getType() %> </td></tr>
<tr><td>Account balance: </td><td><%= account.getBalance() %></td></tr>
</TABLE>
</FORM>

Figure 13-19 Client JSP to test the Web service (extract)

A sample run of the client is shown in Figure 13-20.

466 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 13-20 Client JSP invoking a Web service

Summary
In this chapter, we introduced Web services. We then showed an example of
using Application Developer to generate a Web service from an existing
JavaBean. Finally, we showed how easy it was to create a Web service client
using the built-in wizard.

More information
The 2003 IBM Redbook WebSphere Version 5 Web Services Handbook,
SG24-6891, goes into thorough detail about the concept of SOA as well as Web
Services for WebSphere Version 5. It also contains examples using Application
Developer Version 5.

Additional information about using and creating Web Services is available from
the online help included in Application Developer.

Chapter 13. Developing Web services 467


468 WebSphere Studio Application Developer Version 5 Programming Guide
14

Chapter 14. Developing GUI applications


Application Developer 5 introduces the Visual Editor for Java (hereafter called
Visual Editor) that lets developers build graphical user interfaces (GUIs) based
on the JavaBeans component model.

In this chapter we introduce you to the Visual Editor and develop a sample GUI,
which lists the content of a table in a DB2 database and has an action that writes
the selected value back to a text field. This GUI is runnable as a JavaBean and
as a Java application.

This chapter provides information on the following topics:


򐂰 Introduction to the Visual Editor for Java
򐂰 Sample GUI
򐂰 Setting up your sample project
򐂰 Launching the Visual Editor
򐂰 Visual Editor look and feel
򐂰 Customizing the appearance of the Visual Editor
򐂰 Changing the default Java Editor
򐂰 Working with the Visual Editor
򐂰 Adding data to the JavaBean
򐂰 Adding additional methods to the sample GUI
򐂰 Writing event handling code
򐂰 Running and testing JavaBeans
򐂰 Running the sample outside of Application Developer

© Copyright IBM Corp. 2003. All rights reserved. 469


Introduction to the Visual Editor for Java
The Visual Editor for Java is a code-centric editor that helps you design
applications containing a graphical user interface (GUI). It is based on the
JavaBeans component model and supports visual construction using either the
Abstract Windows Toolkit (AWT) or Swing. For more information concerning
Swing and AWT, see the either Application Developer’s help manual or Sun’s
Web site:
http://java.sun.com/products/jfc/index.html

The Visual Editor allows you to compose class files visually. Using the Visual
Editor, you can drag beans from different palettes, manipulate them in the Design
view, and edit their properties in the Properties view. The Visual Editor also
includes a Source view where you can both see and modify the generated Java
code. You can make changes in either the Source view or in the Design view.

Note: JavaBeans is basically a portable, platform independent, reusable


component model. When talking about a JavaBean in this chapter, we mean a
reusable software component that can be visually manipulated in builder tools.

The new Visual Editor provides similar function as the earlier VisualAge for Java
Visual Composition Editor. Unlike VisualAge for Java, the Visual Editor is a code
centric editor, so you have to use its embedded Java editor to write event
handling logic.

Sample GUI
The sample GUI we develop in this chapter is shown in Figure 14-1. The sample
GUI displays a list with the last names of customers that are stored in the sample
EJBBANK database. The GUI also provides a push button action that retrieves the
corresponding first name of the customer and writes the first name to a text field
in the GUI.

470 WebSphere Studio Application Developer Version 5 Programming Guide


JLabel bean

JTextField bean

JList bean JButton bean


Figure 14-1 Sample GUI

By creating the sample GUI, you should learn how to work with the new Visual
Editor and how to compose and add visual components, change their properties,
add event handling code, and run the GUI.

Setting up your sample project


To demonstrate the capabilities of the Visual Editor, we set up a new project.
Therefore we create a new Java project and name it ItsoProGuideGui. See
“Creating a Java project” on page 94 for a description of how to create a new
Java project.

Once this is done, we create a Java package named itso.gui. “Creating Java
packages” on page 99 provides information regarding this issue. Our new project
skeleton is shown in Figure 14-2.

Figure 14-2 Project skeleton

You also have to update the Java build path for this project. You do this by
selecting the ItsoProGuideGUI project and Properties from the context menu.
Then you select the Java Build Path entry and the Libraries tab (Figure 14-3).
Click Add Variable, select DB2JAVA and confirm both dialogs with OK.

Chapter 14. Developing GUI applications 471


See “Creating and working with a Java project” on page 94 for more information
about the Java build path.

Figure 14-3 Libraries settings for the sample project

After having created the project, we create a new class and launch the Visual
Editor.

Launching the Visual Editor


The Visual Editor allows you to create and modify application GUIs by
manipulating beans in a WYSIWYG (what you see is what you get) editor. There
are two ways to launch the Visual Editor:
򐂰 Create a visual class, which is automatically assigned and opened with the
Visual Editor.
򐂰 Create a Java class from scratch and open the class with the Visual Editor.

In this example we create a visual class as described in the first step above
(“Creating Java classes” on page 100 provides more information about how to
create a new Java class).

Note: The .java file that you open in the Visual Editor must be stored in a
Java project.

472 WebSphere Studio Application Developer Version 5 Programming Guide


Create a visual class
To create a visual class, select File -> New -> Other -> Java -> Visual Class or,
even easier, select the itso.gui package and New -> Visual Class from the
context menu.

Enter CustomerGUI in the Name field, make sure the package is set to itso.gui,
select Panel from the extension list, select Swing—our sample class will inherit
from the javax.swing.JPanel class—and select to have a main method created
(Figure 14-4).

Figure 14-4 Create a visual Java class

We have a choice of using Swing or AWT as GUI framework.

Table 14-1 shows a brief description of the user interface classes that can be
selected in the New Java Class dialog.

Chapter 14. Developing GUI applications 473


Table 14-1 User interface classes
Name Swing class AWT class Description

Frame javax.swing.JFrame java.awt.Frame A Frame is a top-level window


with a title and a border.

Panel javax.swing.JPanel java.awt.Panel Panel is the simplest container


class. A panel provides space
in which an application can
attach any other component,
including other panels.

Applet javax.swing.JApplet java.awt.Applet An applet is a small program


that is intended not to be run on
its own, but rather is embedded
inside another application, for
example a Web browser.

Other Any superclass, probably inheriting from Choose your own superclass.
one of the Swing or AWT classes

Clicking Finish creates the new CustomerGUI class and opens the Visual Editor.
Figure 14-5 shows the new class CustomerGUI in the Visual Editor.

Figure 14-5 Visual Editor for a new class

474 WebSphere Studio Application Developer Version 5 Programming Guide


Open an existing class with the Visual Editor
Alternatively, you can open any other Java class with the Visual Editor by using
the context menu. Select the class and Open With -> Visual Editor (Figure 14-6).

Note: The big dot in front of the Visual Editor menu item of the context menu
indicates that the last editor used was the Visual Editor.

Figure 14-6 Open With context menu

Visual Editor look and feel


The Visual Editor consists of three panes with views (Figure 14-7):
򐂰 A graphical canvas is located in the top section of the Visual Editor. This is the
Design view, where you compose the GUI.
򐂰 The source file is displayed beneath it, in the Java editor, respectively, the
Source view. The Source view is an embedded version of the standard Java
editor included with Application Developer. Here you can set breakpoints in
the source, use content assist, and benefit from all the other functions
available with the Java editor. The section “Programming assists” on
page 115 provides more information about the Java editor in Application
Developer.
򐂰 A palette of common JavaBeans is available on the left, that allows you to
control the selection of JavaBeans in the design pane and also lets you add
new JavaBeans. Each area is separated by split bars that can be selected
and moved to new positions so that you can make the most out of the
available space.

Chapter 14. Developing GUI applications 475


Design

Bean Palette Source


Figure 14-7 Visual Editor layout

When the Visual Editor is launched, some additional views open automatically:
򐂰 The Java Beans view, in the bottom left corner of the workspace, displays the
structure of the JavaBeans in a tree view.
򐂰 The Properties view lets you view and modify attribute settings. The
Properties view is opened in the same pane where the Outline view is
located, by default, on the right-hand side of the workspace.

Tip: Clicking the Overview button, which is located at the bottom right corner
of the Design view, brings up a new subpane where you can navigate to a
specific section on you GUI. This is practical when you work with larger GUIs.

Figure 14-8 shows the default Workbench of the Visual Editor, including the Java
Beans view and the Properties view.

476 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-8 Workbench of the Visual Editor

Tip: By double-clicking the class name tab, CustomerGUI.java, the Visual


Editor is resized to the size of the Workbench. This allows you to maximize
your work area.

Chapter 14. Developing GUI applications 477


Customizing the appearance of the Visual Editor
You can also customize the appearance of the Visual Editor. By default, the
Visual Editor shows the Design and the Source views on a split pane.

If you click the down arrow located in the center right of the separator between
the Design view and the Source view, the Design view will be maximized to allow
you to work with a large area for the JavaBeans (Figure 14-9).

Maximize
the Design
view or
maximize
the Source
view

Hide the
bean
palette

Figure 14-9 Design and Source view

You can hide the bean palette by clicking the left arrow button on the separator to
the right of the palette.

You can also change the default appearance of the Visual Editor by modifying its
preferences. If you prefer to have more space to work in, you can choose to stack
the Design and Source views rather than tiling them. You can also choose to
show or hide the bean palettes by default.

Click Window -> Preferences, open the Java tree and select Visual Editor. This
will bring up the Visual Editor preferences (Figure 14-10).

478 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-10 Visual Editor Preferences

The section Show the Visual Editor and Source Editor allows you to choose if you
want to stack the Visual Editor and the Source Editor or to split them. If you
choose to stack the Design and Source views, you can switch between them by
clicking the Design and Source tabs that now appear in the editor area
(Figure 14-11).

The check box with palette in editor part indicates if the Palette view with the
JavaBeans will be displayed in the Visual Editor or not.

Figure 14-11 Visual Editor and Source Editor tabs

Chapter 14. Developing GUI applications 479


The Generate a comment for new expressions check box in the Visual Editor
preferences helps you as a user to distinguish which methods have been
generated by the Visual Editor. When this option is enabled, a comment
//Generated will be put at the end of any new statements generated by the Visual
Editor.

The Generate try{}catch{} block check box will generate, if enabled, a try{}
catch{} statement in your source code when modelling JavaBeans.

The Source Synchronization Delay settings can be changed to change the delay
time that is used to make updates from the Java Beans model to the source code
from its initial value of 500 milliseconds. Making updates from the source code to
the Java Beans is initially set to a larger factor. See “Code synchronization” on
page 483 for more information according the synchronization between the
source model and the JavaBeans model.

You have to close and reopen an existing Visual Editor to see the changes.

Changing the default Java Editor


Application Developer provides two editors for editing Java source files:
򐂰 Java editor (text-based)
򐂰 Visual Editor

By default, when you create a new Java class, the Java editor opens. When you
open an existing .java file, the editor that you last used for editing that file opens.

To change the default editor that opens for .java files, click Window ->
Preferences, expand the Workbench category and select File Associations
(Figure 14-12). Select .java from the File types list and select the editor that you
want to set as default, then click Default.

In the next section we show how to work with the Visual Editor and its
JavaBeans.

480 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-12 File associations

Working with the Visual Editor


When you created the class CustomerGUI, Application Developer created a small
gray square in the Design view (Figure 14-5 on page 474) and the following code
skeleton in the Source view (Figure 14-13).

package itso.gui;

import javax.swing.JPanel;

/**
* @author IBM Itso
*
* ......
*/
public class CustomerGUI extends JPanel {

public static void main(String[] args) {


}
}

Figure 14-13 CustomerGUI code skeleton

Chapter 14. Developing GUI applications 481


Resizing a JavaBean component
After creating the new Visual class, we build a GUI with the Visual Editor. The
first step is to resize the JPanel.

The canvas lets you select Java beans. To resize the JPanel, select the panel
(the little square) and use the mouse to move and resize it.

To make the JPanel larger, move the cursor over its bottom right edge so that it
becomes a southeast arrow, then left-click and move the cursor to the desired
size, and finally release it. After performing this action your JPanel should look
like Figure 14-14.

Figure 14-14 Resized JPanel

Once you have resized the panel, Visual Editor synchronized the changes with
the source editor. A constructor and an initialize method have been added to
the sample class including the line of code that sets the new size for the panel.
The initialize method is called from the CustomerGUI constructor.

482 WebSphere Studio Application Developer Version 5 Programming Guide


The new source code should have changed now and displayed in the Source
view, as shown in Figure 14-15.

package itso.gui;

import javax.swing.JPanel;

/** ...... */
public class CustomerGUI extends JPanel {

/**
* This method initializes
*
*/
public CustomerGUI() {
super();
initialize();
}
public static void main(String[] args) {
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(310, 180);

}
} // @jve:visual-info decl-index=0 visual-constraint="0,0"

Figure 14-15 CustomerGUI source code after resizing

Tip: The bold highlighted statement this.setSize(310, 180); indicates the


code which has been added to the class when resizing the panel. The setSize
method resizes a component with the two parameters, width and height.

Code synchronization
When you are working with the Design and the Source views, this forces Visual
Editor to maintain both internal modules:
򐂰 The representation of the JavaBeans, used in the Design view, the Properties
view, and the Java Beans view
򐂰 The source that represents the code

Chapter 14. Developing GUI applications 483


As you make changes to either the Design view or the Source view, Visual Editor
will maintain the other model for you by performing synchronization. The status of
the synchronization of the two models can be seen on the right-hand side of the
status bar at the bottom of the Workbench window (Figure 14-16).

Figure 14-16 Synchronization status - In Sync

There is a performance overhead associated with synchronizing the two models,


so the processes to do this are run in background threads on a delay timer. If
changes are made to a model, by either manipulating the Java beans in a view or
by editing the source, the other model needs to be updated or it will no longer be
synchronized.

To show that the models are not synchronized, the status label changes from
In Sync to Out of Sync (Figure 14-17).

Figure 14-17 Synchronization status - Out of Sync

After a period of inactivity, for example when you have stopped typing code in the
editor, synchronization will occur. While synchronization is taking place the
flashing arrow will show the direction the update is occurring. For example, the
up arrow represents changes from the source to the Java beans model, and the
down arrow vice versa.

You can also disable synchronization by pressing the pause button between the
two arrows. This is a good idea when you wish to make a number of large
changes to the source without incurring the overhead of the synchronizer.

Note: While the synchronizer is paused, you can make changes to the source
without any overhead of parsing source, but you can no longer make changes
to the JavaBeans model. All changes in the Design view, the Java Beans
view, or the Properties view will not be applied.

While the source code is being parsed and analyzed, the synchronizer may
determine that the source contains errors, and rather than trying to update the
JavaBeans model, it will wait for the errors to be corrected. If this occurs the
button will become pressed automatically and the graphic will be changed to this
symbol:

484 WebSphere Studio Application Developer Version 5 Programming Guide


Add JavaBeans to a visual class
The next steps are to add two more JPanels on our existing panel and change
their properties. This allows us to place and align the Swing components in a
very flexible way. To add another JPanel, follow these steps:
򐂰 Left-click the JavaBean on the palette view that you want to add. In this case,
select the JPanel item from the Swing containers list (Figure 14-18). The
background area of the selected bean in the palette view is shaded. Do not
hold down the mouse button.

Figure 14-18 Palette view - Swing containers

򐂰 Move the mouse pointer to the Design view and somewhere over the gray
panel and click the mouse button again to drop the bean (Figure 14-19).

Figure 14-19 Drop a JavaBean on the panel

The Design view should now look like shown in Figure 14-20. The additional
JPanel has been placed on the top of the main panel.

Chapter 14. Developing GUI applications 485


Figure 14-20 Sample GUI: stage 1

Now we want to add a second JPanel to our GUI. This time we use another
technique:
򐂰 Select the JPanel item from the Swing containers selection in the Palette
view.
򐂰 Drop the panel on the this object in the Java Beans view (the top element of
the tree). Figure 14-21 shows where to point the mouse cursor to drop the
panel.

Figure 14-21 Adding a JavaBean by using the Java Beans view

A more detailed description about the Java Beans view and how to work with this
view is provided in the next section “Working with the Java Beans view” on
page 490.

So far we have shown that there are two ways to add a component to the GUI:
򐂰 Select a component and drop it on the Design view
򐂰 Select a component and drop it on the Java Beans view

486 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-22 shows the sample GUI—including both JPanels—in the Design
view.

Figure 14-22 Sample GUI: stage 2

Once in a while you should save your work by pressing Ctrl-S.

Working with the Properties view


By selecting a JavaBean in the Design view, its properties are listed in the
Properties view. The list of properties comes from the inspection of the
JavaBean.

The properties list of the resized JPanel—which is actually root object in the Java
Beans view—are shown in Figure 14-23.

To select the JPanel and display its properties, simply left-click somewhere in the
gray pane of the Design view.

The Properties view allows you to view and edit their values. When you change a
value in the Properties view, the Design and Source views are updated. For
example, you can change the size values and see the panel adjust in the Design
view.

Chapter 14. Developing GUI applications 487


Figure 14-23 JPanel properties

Some properties have a restricted set of enumerated values, which means that
you cannot change the value in the text field of the Properties pane, but instead
pick a value from a list.

Examples of property editors that use enumerated lists are:


򐂰 java.lang.Boolean and boolean
򐂰 java.awt.Cursor
򐂰 java.awt.LayoutManager

In our sample GUI, we want to change the layout property of our JPanel from its
initial value FlowLayout to the value GridLayout. Therefore, click in the cell which
contains the value FlowLayout and click the drop-down button to open the value
list and select GridLayout. Figure 14-24 shows the list of the layout property.

488 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-24 Layout properties of the JPanel Java Bean

Note: Some properties, for example the GridLayout value for the layout
property shown above, are themselves JavaBeans. This means that you can
expand these beans to view and change their properties. This also applies if
the nested properties are JavaBeans as well.

A GridLayout places components in a grid of cells. The GridLayout is the one of


the more powerful (and more complex) layouts. Each component takes all the
available space within its cell, and each cell has exactly the same size. Notice
how the two panels take up half the space in the Design view after the change.

For more information according the GridLayout and layout components in


general, see Sun’s Java Web site:
http://java.sun.com/docs/books/tutorial/uiswing/layout

Tip: The right angle bracket > in front of a property item in the Properties view
indicates that the property has been changed from its default value.

By clicking the drop-down arrow located right to the Properties view title—as
shown in Figure 14-25—a menu opens where you can filter the Properties you
want to be displayed in the Properties view.

Figure 14-25 Properties view filter

Chapter 14. Developing GUI applications 489


򐂰 Selecting Show null values on the menu lets you distinguish between a
property with a null value and one with an empty value. Null values are
indicated by displaying <null>.
򐂰 Show set values toggles the right angle bracket > in front of the modified
properties off
򐂰 Show read only properties displays additional properties that you cannot
change.

Next we take a closer look at the Java Beans view.

Working with the Java Beans view


We have seen that the Java Beans view can be used to add beans to your GUI.
The Java Beans view also provides you with a tree view of all the components
that are used in the class that you are composing.

The Java Beans view supports you in accomplishing these tasks:


򐂰 Selecting a JavaBean
򐂰 Renaming a JavaBean
򐂰 Moving a JavaBean
򐂰 Deleting a JavaBean

Tip: The Java Beans view provides an easy way to select and move an object
in the Visual Editor. As you start laying components in the Visual Editor, it may
be hard to drop a component in the target container in the Design view. Using
the Java Beans view helps you also to see what visual components contain
other visual components.

The selection between the entries in the Java Beans view and those in the
Design view is synchronized both ways, so if you select an item or multiple items
in the Design view, then they are also selected in the Java Beans view.

Also, in the Java Beans view, the icon shown for the entry is the same icon that is
used in the palette to represent the bean type.

Now we want to rename both JPanels we have created in the previous step. To
do this, we open the context menu of the jPanel component as shown in
Figure 14-26 and select Rename Field.

490 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-26 Context menu of a bean in the Java Beans view

Note: The context menu item Delete allows you to delete the selected
JavaBean. By deleting a bean, the Design view and the Source view will be
updated and synchronized appropriately.

If we have not saved our file yet, the dialog shown in Figure 14-27 comes up.
Click OK to save the file CustomerGUI.java and close the dialog.

Figure 14-27 Save all modified resource dialog

The Refactoring dialog comes up next. The section “Refactoring” on page 122
provides a detailed description of the refactoring process in Application
Developer.

Enter jPanelLeft in the new name field (Figure 14-28), leave the other default
values in the refactoring dialog as they are, and click Finish.

Chapter 14. Developing GUI applications 491


Figure 14-28 Refactoring: rename field dialog

The Design view and Source view will be synchronized by Application Developer
and the code will be changed appropriately.

Repeat the refactoring step for the bean jPanel1 and rename it to jPanelRight.
The Java Beans view should now look as shown in Figure 14-29.

Figure 14-29 Java Beans view with renamed panels

Tip: Moving a JavaBean by using the Java Beans view is very simple. Select
a bean, move it to the appropriate spot in the tree, and drop it there. When
moving a bean, a horizontal line is displayed. This line helps you locate the
exact position where you want to drop the bean.

Extending the sample GUI


In this section we want to improve our sample GUI and add the remaining beans
to it. First we want to change the layout property of our two new panels. We
change the layout of both panels in the Properties view from FlowLayout to the
GridBagLayout as shown in Figure 14-30.

492 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-30 GridBagLayout property

Tip: The GridBagLayout is a flexible layout manager that aligns components


vertically and horizontally, without requiring that the components be of the
same size.

Designing the left panel


Now we add a JLabel bean on our jPanelLeft panel. This bean is a display area
for a short text string or an image, or both.

To add the label, select the JLabel bean from the Swing components of the
Palette view and drop it onto the jPanelLeft (Figure 14-31). Alternatively, you
can drop the label into the left panel in the Design view.

Figure 14-31 Adding a JLabel to the panel

Rename the jLabel to jLabelCustomerList and change the Text property from
JLabel to Customer List (Figure 14-32). Modifying the text property changes the
text of the label which is displayed on the GUI.

Figure 14-32 Text property

Chapter 14. Developing GUI applications 493


Now select a JList of the Swing components from the palette and drop the list on
the jPanelLeft. This component allows the user to select one or more objects
from a list.

Change the name of the list from jList to jListCustomers and change its gridy
property (you have to expand constraint) from -1 to 1 (Figure 14-33).

Figure 14-33 JList constraints

Changing the gridy property aligns the JList below the JLabel within the
jPanelLeft bean.

Tip: The gridy property is used to set the vertical position of objects, where
the topmost cell has gridy=0.

You also have to change the property selectionMode from its initial value
MULTIPLE_INTERVAL to SINGLE. This prevents us from selecting multiple
elements from the list bean.

By now the GUI should look as shown in Figure 14-34.

494 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 14-34 Sample GUI: stage 3

In case our list contains many entries, it is a good idea to have a scroll bar added
to the list bean.

To do this, you need to select the JScrollPane bean from the Swing containers
and add it to the jPanelLeft bean. Rename the new scroll pane to
jScrollPaneForCustomersList and change its gridy property from -1 to 1.

To associate the scrollpane with the jListCustomers bean, you can add a line of
code to the getJScrollPaneForCustomersList method:
jScrollPaneForCustomersList.setViewportView(getJListCustomers());

Even simpler: Select the jListCustomers bean in the Java Beans view and drop
it onto the scroll pane. This makes the list a component of the scroll pane and
adds the required line of code to the getJScrollPaneForCustomersList method:

The complete code of the scroll pane is shown in Figure 14-35. If you click the
jScrollPaneForCustomersList bean in the Java Beans view, the Visual Editor
automatically navigates to this code in the Source view.

private javax.swing.JScrollPane getJScrollPaneForCustomersList() {


if(jScrollPaneForCustomersList == null) {
jScrollPaneForCustomersList = new javax.swing.JScrollPane();
jScrollPaneForCustomersList.setViewportView(getJListCustomers());
}
return jScrollPaneForCustomersList;
}

Figure 14-35 Source code for the scroll pane

Chapter 14. Developing GUI applications 495


Designing the right panel
Next, we want to add a JLabel bean to the jPanelRight and rename it to
jLabelCustomerSelection. We also change the text property from JLabel to
Customer Selection.

Once the JLabel has been added, we add a JTextField to the jPanelRight
bean. Also rename the JTextField from its initial value jTextField to
jTextFieldCustomerSelection and change the gridy property from -1 to 1, to
align the bean appropriate within this GridBagLayout panel.

You also have to change the enabled property of the


jTextFieldCustomerSelection from the initial value true to false. By changing
this property to false, we are not allowed to enter a value in the text field
anymore.

We also want to change the background color and the disabled text color
properties of the text field. By doing this, we demonstrate that we can also
overwrite the default properties of a JavaBean by using the source editor.

Add the following code statements to the initialize method:


getJTextFieldCustomerSelection().setBackground(getJPanelRight().getBackground());
getJTextFieldCustomerSelection().setDisabledTextColor(Color.black);

This statement will change the background color of the text field to the same as
the jPanelRight panel uses as its background color. To resolve the Color class,
select Color and Source -> Organize Imports (context). Application Developer
also adds automatically the following import statement to the class:
import java.awt.Color;

The last JavaBean we want to add to our sample GUI is the JButton. Add the
JButton bean to the jPanelRight, rename from jButton to jButtonGetFirstName
and also set the text property to Get First Name. The gridy property should also
be changed from -1 to 2.

Improving the layout


As we have seen, all JavaBeans which have been placed on the GridBagLayout
panels have constraint properties, except for the jLabelCustomerList bean that
is inside the scroll pane.

To improve the layout of our sample GUI, we now change the insets property for
all beans mentioned above. Figure 14-36 shows the insets property of a
GridBagLayout component.

496 WebSphere Studio Application Developer Version 5 Programming Guide


Change this property from its initial value 0,0,0,0 to 10,10,10,10 for all
JavaBeans in the two panels. Changing this property specifies the external
padding of the component and increases the space between the beans.

Figure 14-36 Insets property of a GridBagLayout component

Now we have finished designing the sample GUI. Figure 14-37 shows the Java
Bean view of our sample GUI.

Figure 14-37 Java Beans view of the sample GUI

Figure 14-38 shows the Design view of our sample GUI.

This GUI is already runnable as a JavaBean. However, it does not yet do


anything but display. The section “Running and testing JavaBeans” on page 504
provides a description of how to run and test a JavaBean.

Chapter 14. Developing GUI applications 497


Figure 14-38 Sample GUI in Design view

Adding data to the JavaBean


As shown in the section “Sample GUI” on page 470, we want to list the last
names of the customers in the JList bean. Chapter 5, “Developing Java
applications” on page 93 uses a simple Java class (CustomerListing) that reads
a DB2 database table to retrieve information about Customers. This sample code
is provided in Figure 5-10 on page 102.

We want to reuse most of the code of this class in our ItsoProGuideGui project,
modify some statements, and fill the jListCustomer bean with the last names of
all records provided in the CUSTOMER table of the sample DB2 database.

Note: This sample provides a simple guide showing how to create a small GUI
with some logic behind it. For simplicity, this code does not follow any
architectural practices or rules.

There are two ways to add the CustomerListing class to this project:
򐂰 Create the class from scratch, place it in the itso.gui package, and add the
code.
򐂰 Copy—if it exists—the class CustomerListing from the itso.java package of
the ItsoProGuideJava project to the iso.gui package of this project and
adapt the code.

Figure 14-39 shows the sample class, where bold statements differ from the
original Java class. The code is provided in:
\sg246957\sampcode\dev-visual\initial\CustomerListing.txt

498 WebSphere Studio Application Developer Version 5 Programming Guide


package itso.gui;
import java.sql.*;
import java.util.Vector;

public class CustomerListing {


static String dbtab = "CUSTOMER";

public Vector getAllByLastName() {


Vector result = new Vector();
Connection con = null;
con = connect();
Statement stmt = null;
ResultSet rs = null;
String select = "SELECT * FROM ITSO." + dbtab;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(select);
while (rs.next()) {
//String lastName = rs.getString("lastName"); ......
result.addElement(rs.getString("lastName"));
}
//System.out.println("End of Listing");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}
return result;
}

protected static Connection connect() {


Connection con = null;
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
con = DriverManager.getConnection("jdbc:db2:EJBBANK");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
return con;
}
}

Figure 14-39 Sample class CustomerListing - adapted for sample GUI

Chapter 14. Developing GUI applications 499


To add data to the JList bean of the sample GUI, we have to add some code to
the initialize method. The bold formatted code in Figure 14-40 shows the code
which has to be added to the initialize method of the CustomerGUI class.

First we have to create an instance of the CustomerListing class which will be


used to call the method getAllByLastName — which returns the last names of all
customers of the CUSTOMER table — and stores the result in a Vector object, which
is named allCustomers.

The setListData method of the JList object adds the allCustomers vector to the
list.

private void initialize() {


java.awt.GridLayout layGridLayout1 = new java.awt.GridLayout();
layGridLayout1.setRows(1);
this.setLayout(layGridLayout1);
this.add(getJPanelLeft(), null);
this.add(getJPanelRight(), null);
this.setSize(330, 180);
getJTextFieldCustomerSelection().setBackground(getJPanelRight()
.getBackground());
getJTextFieldCustomerSelection().setDisabledTextColor(Color.black);

// initialize the list with data from the database


CustomerListing customerList = new CustomerListing();
getJListCustomers().setListData(customerList.getAllByLastName());
}

Figure 14-40 Initialize method of the CustomerGUI class

If you would run the GUI now, then the last names of the customers would be
displayed.

Adding additional methods to the sample GUI


The sample GUI is not yet complete, as we have to implement some code which
will enable the button and return the first name of the selected entry in the list.

To do this, we first add a new method to the CustomerListing class. This method
is called by a new method of the CustomerGUI class that has not been
implemented yet.

Figure 14-41 shows the code of the new method. By a given key—in this
example the last name—this method returns the corresponding first name.

500 WebSphere Studio Application Developer Version 5 Programming Guide


This method is similar to the getAllByLastName method (Figure 14-39 on
page 499). You can copy and paste the getAllByLastName method and change
the bold statements.

public String getFirstNameByKey(String key) {


String result = new String();

Connection con = null;


con = connect();

Statement stmt = null;


ResultSet rs = null;
String select =
"SELECT * FROM ITSO." + dbtab + " WHERE lastName = '" + key + "'";
try {
stmt = con.createStatement();
rs = stmt.executeQuery(select);
while (rs.next()) {
result = rs.getString("firstName");
}
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}
return result;
}

Figure 14-41 getFirstNameByKey method of the CustomerListing class

Next we add a new method to the CustomerGUI class. This method is called by
the jButtonGetFirstName bean and returns the first name of the customer
selected in the jListCustomers.

Add the code as shown in Figure 14-42 to the class CustomerGUI.

The method checks if an entry in the jListCustomers bean has been selected.
If so, the method calls the getFirstNameByKey method, which returns the
corresponding first name of the selected entry. If nothing has been selected in
the list, the method returns a string which says: No customer selected .

Chapter 14. Developing GUI applications 501


private String getFirstName() {
String result = new String();

if (getJListCustomers().getSelectedIndex() == -1) {
// Nothing has been selected in the list
result = "No customer selected.";
} else {
// An item has been selected in the list
String selectedItem =
getJListCustomers().getSelectedValue().toString();
CustomerListing customerList = new CustomerListing();
result = new String(customerList.getFirstNameByKey(selectedItem));
}
return result;
}

Figure 14-42 Method to retrieve the first name

Writing event handling code


Once we have added these methods to the CustomerListing and the
CustomerGUI class, we add an action listener to the jButtonGetFirstName bean.
This is the last step to finish the sample GUI.

Note: An action listener is an event handler which has to be implemented to


respond to the user’s actions, such as clicking a push button.

We have to implement the action listener to trigger an action when the button in
our GUI has been clicked.

The Visual Composition Editor of Visual Age for Java allowed you to generate
program logic by making connections between JavaBeans. Visual Age for Java
generated the appropriate code to attach the listener to the source JavaBean,
and then executed the desired action on the target.

The new Visual Editor in Application Developer does not implement the concept
of creating connections graphically between JavaBeans. Such program logic is
specified by writing code directly in the Java editor. To help developers write the
event handling code, Visual Editor provides several content assist templates.

Usually, each template has the same name as the method it is designed to work
with. The template for adding an action listener to a JavaBean is named
addActionListener.

502 WebSphere Studio Application Developer Version 5 Programming Guide


To use the addActionListener template, navigate to the method that initialized
the jButtonGetFirstName bean by selecting this bean in the Java Beans view.
The Visual Editor will select the appropriate method in the Source view.

After you write the beginning of the line of code, for example,
jButtongetFirstName.addA, you can invoke code assist by pressing Ctrl-Space
on your keyboard. The template will appear at the bottom of the content assist
list, as shown in Figure 14-43.

Figure 14-43 addActionListener template

Note: If the template for the event you wish to add is not present in the
available code assist list, then you might be able to import it into Application
Developer. The import file is named allTemplates.xml and is located in the
Application Developer’s folder:
wstools\eclipse\plugins\com.ibm.etools.jbcf.codegen_5.0.1\Examples\
Templates\java\awt\event

See “Code assist” on page 118 for more information regarding templates.

The code skeleton as shown in Figure 14-44 is created automatically, after the
addActionListener template has been added.

jButtonGetFirstName.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {

}
});

Figure 14-44 Action listener code skeleton

Chapter 14. Developing GUI applications 503


Once the template is used, the cursor will be positioned inside the
actionPerformed method. Add the following statement to this method:
getJTextFieldCustomerSelection().setText(getFirstName());

This statement calls the getFirstName method and writes the return value to the
jTextFieldCustomerSelection bean.

The getJButtonGetFirstName method is completed now. The bold code is the


new action listener code that has been added (Figure 14-45).

private javax.swing.JButton getJButtonGetFirstName() {


if (jButtonGetFirstName == null) {
jButtonGetFirstName = new javax.swing.JButton();
jButtonGetFirstName.setText("Get First Name");

jButtonGetFirstName
.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
getJTextFieldCustomerSelection().setText(getFirstName());
}
});
}
return jButtonGetFirstName;
}

Figure 14-45 getJButtonGetFirstName method

By now, we have finished designing our sample GUI, including an event handler,
and are able to run and test it.

Running and testing JavaBeans


Once you have written a class using the Visual Editor for Java, you may wish to
run and test it. If the class has a main method, you can use the menu option Run
-> Java Application.

In this section we show how to run the sample as a JavaBean and as a Java
application. Additional information about running a Java class is provided in the
section “Running your programs” on page 103.

However, when you write a JavaBean using the Visual Editor, it will not typically
have a main method. Rather than having to add a main method, to allow you to
test JavaBeans classes, there is an additional option available from the Run
menu called JavaBean that invokes a JavaBean launcher.

504 WebSphere Studio Application Developer Version 5 Programming Guide


By comparison, in VisualAge for Java, you could not test a JavaBean, and you
could only execute JavaBeans through the main method. Visual Age for Java was
able to generate a default implementation of the main method to help test the
JavaBean.

Running the sample GUI as a JavaBean


To run the sample GUI, simply click the drop-down arrow of the Run icon in the
toolbar and select Run. The Launch Configurations dialog opens and you select
Java Bean / Applet from the Launch Configurations list (Figure 14-46).

Figure 14-46 Create a launch configuration for the JavaBean

Click New to create a new launch configuration for the class CustomerGUI.

If the class you are testing extends java.awt.Applet or javax.swing.JApplet,


you can go to the Applet Parameters tab of the launch configuration to specify its
parameters. It will be launched inside an applet viewer.

Other tab views let you specify the JRE, program, and VM arguments, classpath
information, and additional settings. Besides using the JavaBean launcher to run
your JavaBeans, you can also select Debug -> Debug As -> Java Bean to run
JavaBeans using the debugger.

Figure 14-47 shows the new launch configuration with the JavaBean tab. Leave
the default values and click Run.

Chapter 14. Developing GUI applications 505


Figure 14-47 Run the JavaBean by using its launch configuration

The GUI should be launched now, and Figure 14-48 shows what the launched
sample GUI looks like.

Figure 14-48 Launched sample GUI with the default look-and-feel

Also, in the launch configuration dialog, you can change the Swing look-and-feel,
which controls the appearance of visual components in the GUI. As the default

506 WebSphere Studio Application Developer Version 5 Programming Guide


look-and-feel, Swing initializes the cross-plattform Java look-and-feel, formaly
knows as Metal.

If you change the launch configuration and launch the sample GUI with the
Windows look-and-feel, our GUI looks as shown in Figure 14-49 on page 507.

Figure 14-49 Launched sample GUI with the Windows look-and-feel

Running the sample GUI as a Java application


You can also run the sample GUI as a Java application. To do this you have to
add code to the main method.

Figure 14-50 shows the main method including the additional code. As we use a
JPanel, we have to put this panel first in a frame, to make it runnable as a Java
application.

Finally, we have to set the frame object visible, and our sample GUI is now also
runnable as a Java application.

public static void main(String[] args) {


JFrame frame = new JFrame("Sample GUI");
CustomerGUI customerGUI = new CustomerGUI();

frame.setSize(330, 150);
frame.getContentPane().add(customerGUI);

// close the frame properly instead of just hiding it


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);
}

Figure 14-50 Main method of the sample GUI

Chapter 14. Developing GUI applications 507


To run the GUI as an application, select the CustomerGUI class and Run ->
Run As -> Java Application. This adds a second launch configuration under Java
Application.

Note that we set the vertical size of the frame to 150, not big enough to hold all
the last names. In this case the scroll bar appears so that we can scroll through
the names (Figure 14-51).

JScrollPane
bean

Figure 14-51 Reduce sample GUI window size

Testing the sample GUI


When we launch our sample GUI, we can play around by selecting elements
from the list and clicking the button to return the first name.

You can also resize the GUI and see the GUI ‘s behavior. If you for example
reduce the size of the GUI as shown in Figure 14-51, the implemented scroll
pane of the list becomes visible. Also,the beans align automatically.

Another difference with respect to the Visual Composition Editor from Visual Age
for Java is that the new Visual Editor directly reads and writes source code and
has no additional metadata files associated with a visual class.

Running the sample outside of Application Developer


To run the sample outside of Application Developer, select the CustomerGUI class
and Export -> File system. Export the project to the hard drive, for example C:\.

To run the sample, go to the ItsoProGuideGui directory that is created by


exporting and issue either of these commands:
java -cp ".;c:\sqllib\java\db2java.zip" itso.gui.CustomerGUI
java itso.gui.CustomerGUI

508 WebSphere Studio Application Developer Version 5 Programming Guide


Summary
In this chapter we introduced you to the new Visual Editor. We created a new GUI
and demonstrated how to add JavaBeans to the GUI based on Swing
components.

We also implemented event handling code to the GUI and showed how to run
and test such a visual bean.

Chapter 14. Developing GUI applications 509


510 WebSphere Studio Application Developer Version 5 Programming Guide
Part 3

Part 3 Testing and


debugging
applications
Part 3 describes how to test and debug your applications. This part of the book
also introduces Application Developer’s server tools feature and demonstrates
how to test components by using JUnit.

© Copyright IBM Corp. 2003. All rights reserved. 511


512 WebSphere Studio Application Developer Version 5 Programming Guide
15

Chapter 15. Servers and server


configurations
Application Developer provides support for testing, debugging, profiling, and
deploying your Enterprise applications to built-in, local, and remote test
environments.

To run an enterprise application or Web application in Application Developer, it


must be published (deployed) to the server. This is achieved by installing the
EAR project for the application into an application server. The server can then be
started and the application can be tested in a Web browser or by using the
universal test client for EJBs and Web services.

This chapter describes how to use the Server perspective to set up and use
servers and server configurations to test applications.

© Copyright IBM Corp. 2003. All rights reserved. 513


Server tools feature
Application Developer provides the server tools feature to support you in testing
your applications. It provides test environments where you can test Web modules
with servlets, JSPs, and HTML files. It also provides a tool called the universal
test client (UTC) with which you can test your EJB modules and Web services
(see “Universal test client” on page 428).

The server tools feature uses servers and server configurations to test and
deploy your projects. Servers identify server instances where you can run your
projects and server configurations contain setup information for the servers. You
can have multiple server configurations with different settings and then select
which configuration a particular server should use. This allows you to easily
switch between different setups of memory configurations, data sources, trace
settings, class loading policies, and so forth. Servers and server configurations
are kept in server projects.

If you do not have any servers or server configurations set up, you can have the
server tools create them for you automatically. However, doing it manually using
the server tools wizards gives you more control over what is being set up.

The server tools feature allows you to create servers and server configurations
that can run resources from the following types of projects:
򐂰 Web projects—containing servlets, JSPs, HTML files, and Java beans.
Web projects can also contain Web services to be tested.
򐂰 EJB projects—containing EJB beans.
򐂰 Enterprise application projects—containing Java Archive (JAR) files, Web
and EJB projects.

Using the Server perspective, you can manage the servers and server
configurations and start, stop, or restart them.

When running the Application Developer built-in test environments, the server is
running against the resources in your workspace. This allows you to add,
change, or remove resources from your enterprise application, and the server is
able to pick up these changes without having to be restarted.

Supported run-time environments


The server tools feature allows you to test your applications in different run-time
environments that can be installed as part of Application Developer (built-in), and
run locally on the same machine or remotely on another machine. Table 15-1
describes the different options available with Application Developer 5.0.

514 WebSphere Studio Application Developer Version 5 Programming Guide


Table 15-1 Supported test server environments
Environment Built-in Local Remote

WebSphere Application Server 5.0 Yes Yes Yes

WebSphere Application Server 5.0 Express Yes Yes Yes

WebSphere Application Server 4.0


Yes Yes Yes
Advanced Edition Single Server

WebSphere Application Server 4.0


No Yes Yes
Advanced Edition

Apache Tomcat 3.2, 4.0, and 4.1 Yes Yes No

WebSphere Application Server 5.0, WebSphere Application Server 5.0 Express,


and WebSphere Application Server 4.0 Advanced Edition Single Server ship with
Application Developer 5.0 and can be selected during installation. The local and
remote WebSphere Application Server environments, as well as the Apache
Tomcat servers, must be installed separately.

When using either a local or remote WebSphere Application Server environment,


a tool called the IBM Agent Controller is used to control the server (start, stop,
restart, and profiling). It must therefore be installed on the same machine as the
WebSphere Application Server environment to use.

The IBM Agent Controller is not required when using the Application Developer
built-in test environments or when using Apache Tomcat, unless you want to
perform profiling (see Chapter 20, “Profiling applications” on page 655).

Each environment provides different capabilities as shown in Table 15-2.

Table 15-2 What projects can run in which environment


Environment Enterprise EJB Web
Application projects projects
Projects

WebSphere Application Server 5.0 Yes Yes Yes

WebSphere Application Server 5.0 Express No No Yes

WebSphere Application Server 4.0


Yes Yes Yes
Advanced Edition Single Server

WebSphere Application Server 4.0


Yes Yes Yes
Advanced Edition

Apache Tomcat 3.2, 4.0 and 4.1 No No Yes

Chapter 15. Servers and server configurations 515


Notes: WebSphere Application Server 4.0 supports J2EE 1.2 projects only.
To run a J2EE 1.3 project, you must use a WebSphere Application Server 5.0
server.

A run-time environment called the TCP/IP Monitoring Server is also packaged


with the server tools feature. This is a simple server that monitors all the requests
and responses between the Web browser and an application server. It also
monitors TCP/IP activity. This run-time environment can only be run locally. You
cannot publish projects to the TCP/IP Monitoring Server.

There is also a new server type called the J2EE Publishing Server. This feature
allows you to deploy J2EE applications developed in Application Developer to
remote J2EE compliant servers that require minimal configuration (for example,
Tomcat/JBoss), and then test the client applications from the Application
Developer Workbench. We do not cover this server type in this book, but if you
are interested in learning more about it, you can take a look at the following
WebSphere Developer Technical Journal tutorial:
http://www7b.software.ibm.com/wsdd/techjournal/0302_koo/koo.html

Creating server and server configuration automatically


If there are no servers or server configurations defined, you can have Application
Developer create them for you automatically. All you need to do is to select Run
on Server from the context menu of the project you want to run (Figure 15-1) and
then select the type of server to create (Figure 15-2).

The server options available to you in Figure 15-2 depend on what servers you
installed with Application Developer.

If you also select the Set server as default (do not prompt) you will not be
prompted for which server to run this project on when using the Run on Server
option in the future. This setting is available in the project’s properties if you want
to change it later.

Note: Before you run the application for the first time, make sure that no
servers or server configurations exist, otherwise you will not see the same
dialogs as shown here.

516 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 15-1 Select Run on Server from the context menu

Figure 15-2 Selecting a server type

The server tools feature automatically does the following for you:
򐂰 Opens the Server perspective
򐂰 Creates a server project called Servers
򐂰 Creates the server you selected and gives it a default name (for example,
WebSphere v5.0 Test Environment)

Chapter 15. Servers and server configurations 517


򐂰 Creates a corresponding server configuration and gives it a default name (for
example, WebSphere v5.0 Server Configuration)
򐂰 Sets the server to use the server configuration
򐂰 Adds your project to the server configuration, and, if selected, sets the server
as the default for your project
򐂰 Publishes your project to the server
򐂰 Starts the server
򐂰 Opens the Debug view and the Source pane, if there are breakpoints set in
the file
򐂰 Displays the file in the Web browser as shown in Figure 15-3.

Figure 15-3 Application running in built-in test environment

Note: If you select Run on Server from the context menu of an Enterprise
Application project, Application Developer will not open a Web browser for
you. If you select a Web project, however, it will open the Web browser and go
to the URL of the Web project’s context root. If you select an EJB project, the
universal test client is started.

518 WebSphere Studio Application Developer Version 5 Programming Guide


Creating server and server configuration manually
When creating servers and server configurations manually, you can reuse an
existing server project or create a new project. This section walks you through
the process of creating a new server project and adding a remote WebSphere
Application Server 5.0 server and server configuration. It then runs the
ItsoProGuide project in this remote environment.

Using a built-in server: See “Creating a server for testing” on page 224 for
instructions to define a built-in server and server configuration (ItsoServer).

Before proceeding, you should make sure that the following products are
installed on the remote machine:
򐂰 WebSphere Application Server 5.0
򐂰 IBM Agent Controller

Also make sure that only the IBM Agent Controller is started (this will control the
starting and stopping of the remote WebSphere Application Server).

Creating a Server project


Skip this step if you created the Server project in “Creating a server for testing”
on page 224.

From the File menu, select New -> Project and then Server -> Server Project.
The Create a New Server Project wizard opens (see Figure 15-4). Enter
ItsoProGuideServer as the project name and then click Finish.

Figure 15-4 Create server project wizard

Chapter 15. Servers and server configurations 519


Creating a remote server and file transfer mechanism
Once a server project is available, you can create a server to identify the run-time
environment you want to use for testing your project. If you create a server that is
not built into Application Developer (that is, local or remote) you also have to
define how the application and server configuration should be transferred to the
server when published. There are two methods available, copy and FTP. Copy
performs a simple file copying, and FTP uses the FTP protocol. For a local
server, the copy mechanism is the best choice.

If you are creating a server on a remote machine and want to use the copy
mechanism you must have the drive where the server (only WebSphere
Application Server is supported for remote testing) is installed on the remote
machine mapped to a local drive letter on the Application Developer machine.

To use the FTP mechanism, you must have an FTP server active on the remote
machine. We will not explain how to set this up, as that depends on the FTP
server chosen. We will, however, explain how to set up Application Developer to
use both copy and FTP file transfers.

Creating the server


In this example we will create a server pointing to a remote WebSphere
Application Server 5.0 environment installed on a machine called vertex. If you
would like to create a server pointing to a local server environment (on your own
machine) you should still select Remote server but then use IP address
127.0.0.1 or hostname localhost.
򐂰 In the Server perspective, Navigator view select the ItsoProGuideServer
project and select New -> Server from its context menu. The Create New
Server wizard opens as shown in Figure 15-5.
This wizard creates a new server with the information required to publish and
run projects on built-in, local, or remote run-time environments.
򐂰 In the Server name field, enter a name for the server. As the method of file
transfer is associated with the server, it is a good idea to give the server a
name identifying the method used. We will configure this remote server to use
the copy method, so we call the server WebSphere v5.0 on vertex (Copy).
򐂰 Make sure that the project ItsoProGuideServer is selected, and select
WebSphere Version 5.0 Remote Server as the server type. Then click Next.

520 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 15-5 Create new server wizard

򐂰 On the WebSphere Remote Server Settings page (see Figure 15-6) enter the
IP address or hostname of the remote machine running the WebSphere
Application Server 5.0 product. Then click Next.

Figure 15-6 Specifying remote server address

Chapter 15. Servers and server configurations 521


Note: At this point, Application Developer attempts to contact the IBM Agent
Controller running on the remote machine to retrieve configuration information
about the remote environment. If this procedure fails, the following tips may be
helpful in resolving the problem (the actions should be performed on the
remote machine where the IBM Agent Controller is running):
򐂰 Verify that the IBM Agent Controller process is running either by opening a
command prompt and typing net start or selecting the My Computer icon
and then selecting Manage -> Services and Applications -> Services from
its context menu. You should see a process called IBM Agent Controller
running.
򐂰 Verify that you can ping the remote machine and that there is no firewall
blocking the communication (the IBM Agent Controller listens on port
10002).
򐂰 Verify that the configuration file for the IBM Agent Controller contains
correct values for the WAS_HOME (in case of WebSphere Application Server
4.0) and WAS_HOME_V5 (in case of WebSphere Application Server 5.0)
variables. The configuration file is called:
C:\Program Files\IBM\IBM Agent Controller\config\serviceconfig.xml
Open the file, find the AgentControllerEnvironment section, and look for
the following line (example for WebSphere Application Server 5.0):
<Variable name="WAS_HOME_V5" value="C:\WebSphere\AppServer"
position="replace"/>
Make sure the value specifies the full path of your WebSphere Application
Server 5.0 installation directory (it must not just say %WAS_HOME_V5%). Then
save the file and restart the IBM Agent Controller.
򐂰 Examine the log file to see if it has any error messages explaining the error
condition:
C:\Program Files\IBM\IBM Agent Controller\config\servicelog.log

Once Application Developer has connected to the remote IBM Agent Controller,
the window shown in Figure 15-7 is displayed.

522 WebSphere Studio Application Developer Version 5 Programming Guide


c:\SQLLIB\java\db2java.zip

Figure 15-7 Specifying remote server settings

The WebSphere installation directory is prefilled with the information the IBM
Agent Controller collected on the remote machine.

If you select the Use default WebSphere deployment directory it means that
Application Developer will publish the enterprise application and server
configuration to the directory where the remote WebSphere Application Server
installation keeps its information, overwriting the information there. Deselecting
this check box allows you to enter another directory (that should exist on the
remote machine) where the information should be published instead.

When publishing to the remote server, the Enterprise Application and server
configuration will be published to the installedApps, config, and properties
directories under the remote deployment directory.

If you want to run DB2-based applications, you must define the DB2 driver
location. If you forget to specify the driver location, you can open the
configuration editor later and specify the location on the Server page (see
Figure 15-30 on page 544).

Chapter 15. Servers and server configurations 523


Notes:
򐂰 If you select Use default WebSphere deployment directory, the
WebSphere Application Server configuration on the remote machine is
replaced by the published version. Before publishing, Application
Developer creates a backup copy of the configuration. In the target
WebSphere Deployment Directory, it creates a config/wasTools_bkup
directory and a properties/wasTools_bkup directory. In these directories,
it creates backup directories and files. Only one backup directory per day is
created, however.
򐂰 The paths on this page refers to the remote machine. Therefore C: means
C: on the remote machine, not the machine where Application Developer is
running.
򐂰 If you are using DB2: In the DB2 driver location field, type the DB2 location
where the DB2 classes reside on the remote machine. If a default value
has been set in the Window -> Preferences -> WebSphere dialog, this field
is pre-filled with the DB2 location.

򐂰 Click Next.
򐂰 On the page shown in Figure 15-8, you can define a new remote file transfer
instance or reuse an existing one, if one exists. A remote file transfer instance
contains information on how to transfer the Enterprise application and server
configuration to the remote server when publishing. Select Copy file transfer
mechanism and then click Next.

Figure 15-8 Selecting a file transfer mechanism

524 WebSphere Studio Application Developer Version 5 Programming Guide


Copy file transfer
On the page shown in Figure 15-9, you specify the settings for the new file
transfer mechanism to be created. This page shows the settings for a copy file
transfer mechanism.

Figure 15-9 Creating a new copy file transfer mechanism

򐂰 In the Project folder field, enter the name of the project folder in your
workspace where the remote file transfer instance should be created. In our
example we place it in the ItsoProGuideServer project folder.
򐂰 In the Remote file transfer name field, enter a name for the remote file
transfer instance. We choose the name vertex-copy.
򐂰 In the Remote target directory field, type the name of the directory on the
remote machine where you want your Enterprise application and server
configuration to be published. The remote target directory is the one as seen
by the local machine (where Application Developer is running). In our case we
have mapped our W: drive to C:\ of the remote machine, so we enter
W:/WebSphere/AppServer. If setting up a local server, the remote target
directory would have been the same as the WebSphere deployment directory
in Figure 15-7.

Note: Make sure you have both read and write permissions on the remote
resource.

򐂰 Click Finish.

Chapter 15. Servers and server configurations 525


FTP file transfer
If you select FTP file transfer mechanism in Figure 15-8 on page 524, instead of
Copy file transfer mechanism, you would see the dialog in Figure 15-10 instead.

Figure 15-10 Creating an FTP file transfer mechanism

򐂰 In the Project folder field, enter the name of the project folder in your
workspace where the remote file transfer instance should be created. In our
example we place it in the ItsoProGuideServer project folder.
򐂰 In the Remote file transfer name field, enter a name for the remote file
transfer instance. We choose the name vertex-ftp.
򐂰 In the Remote target directory field, type the name of the directory on the
remote machine where you want your Enterprise application and server
configuration to be published. The remote target directory points to the
WebSphere deployment directory that is seen from the Application Developer
machine, being the FTP client. In our case the WebSphere deployment
directory on the remote machine is c:\WebSphere\AppServer and when
logging on to the FTP server we are placed in the /c:/ directory, so our remote
target is /c:/WebSphere/AppServer.

526 WebSphere Studio Application Developer Version 5 Programming Guide


Notes:
򐂰 To determine whether a beginning slash is required, log on to the FTP
server using an FTP client program, and then type the pwd command. If
the result containing the default log on directory begins with a slash,
then a slash is required prior to typing the remote target directory,
otherwise it is not.
򐂰 Make sure you have both read and write permissions on the remote
resource.

򐂰 In the Host name field, enter the IP address or hostname of the remote
machine.
򐂰 In the User login and User password fields, enter the FTP user ID and
password that will be used to access the machine.
򐂰 If you need to use passive FTP mode or need to go through a firewall, select
the appropriate check boxes. If you click the Firewall Settings button, you can
specify the type of firewall used and the information required to connect
through it.
򐂰 Click Finish.

Server created without a configuration


This creates a new server with the selected file transfer mechanism and it
appears in the Server Configuration view, as shown in Figure 15-11. It does not
yet have a server configuration assigned to it. We will do that next.

Figure 15-11 New server created

Creating a server configuration manually


A server configuration contains the information required to set up and publish a
server. We will first create a new server configuration and then assign this to the
server we just created.

Chapter 15. Servers and server configurations 527


򐂰 From the Server perspective, Navigator view, select the ItsoProGuideServer
project and select New -> Server configuration from its context menu. The
New Server Configuration wizard is shown in Figure 15-12.

Figure 15-12 Creating a server configuration

򐂰 Enter WebSphere v5.0 ITSO Configuration as the name of the configuration.


򐂰 Select Server Configuration as the configuration type.
򐂰 Click Next.

Note: Depending on what configuration type you select, the Next button,
allowing you to specify the details of the server configuration, may or may not
be enabled. In the case of a WebSphere version 5.0 configuration, it is
enabled.

򐂰 The window in Figure 15-13 allows you to set the port number for the
WebSphere Application Server 5.0 built-in HTTP server. You can use the
same port number for multiple server configurations as long as they are not
run simultaneously. Keep the default value of 9080 and click Finish.

528 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 15-13 Setting the HTTP server port

Note: To test using the IBM HTTP Server (Apache server) in the remote
machine, you must customize the server configuration so that the IBM HTTP
Server plug-in configuration is updated in the remote machine. See
“Customizing server configurations” on page 544 for information on how to do
this. The HTTP port number in Figure 15-13 should still be 9080.

The new server configuration is added to the Unused Server Configurations in


the Server Configuration view (Figure 15-14).

Figure 15-14 Server Configuration view

Note: Clicking the (Menu) down-arrow in the Server Configuration view allows
you to switch it to advanced display mode. In advanced mode, the servers and
server configurations are displayed in separate trees, giving you a better
overview.

Chapter 15. Servers and server configurations 529


Assigning a server configuration to a server
To use a server configuration it must be assigned to a server.
򐂰 Select the WebSphere v5.0 on vertex (Copy) server and select Switch
Configuration -> WebSphere v5.0 ITSO Configuration from its context menu
as shown in Figure 15-15.

Figure 15-15 Assigning a server configuration to a server

Creating a server and server configuration together


You can create both a server and a server configuration at once by performing
these steps:
򐂰 In the Server perspective, Server Configuration view, select the server project
ItsoProGuideServers and New -> Server and Server Configuration from its
context menu.
򐂰 The dialog shown in Figure 15-16 is displayed. Enter a name for the server
and in which folder to create it. Also select the type of server and then click
Next.

530 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 15-16 Creating server

In the next dialog (see Figure 15-13 on page 529) enter a port number for the
server. Keep the default of 9080 and click Finish.

This creates a new server and a default server configuration for you and assigns
the server configuration to the server.

Assigning a project to a server configuration


Once you have assigned a server configuration to a server, you also need to add
your project(s) to the server configuration. A project can be assigned to multiple
server configurations and a server configuration can be assigned to multiple
servers.

This means that your application can actually be associated with multiple servers
at the same time. If you launch your application by using the Run on Server

Chapter 15. Servers and server configurations 531


option from its context menu, you must therefore decide on which of your servers
you want to run your application. Application Developer can prompt you for a
server to run on every time or you can specify a default server to run on without
being prompted.

From our first example (see “Creating server and server configuration
automatically” on page 516) where we automatically created a server project, a
server and a server configuration, we already have the ItsoProGuide Enterprise
Application project assigned to the WebSphere v5.0 Test Environment server
(which is a built-in test environment).

We will now also add this project to the new server configuration we have
created. From the Server perspective, Server Configuration view select the
WebSphere v5.0 on vertex (Copy) server and select Add -> ItsoProGuide from
its context menu as shown in Figure 15-17.

Figure 15-17 Adding a project to a server

The project is now associated also with the WebSphere v5.0 on vertex (Copy)
server.

Note: You can only assign enterprise applications to a server. This action
assigns all contained modules (for example, Web and EJB) to the server.

532 WebSphere Studio Application Developer Version 5 Programming Guide


To be prompted for a server to run on select the ItsoProGuide Enterprise
Application Project and then select Properties -> Server preferences from its
context menu. This displays the window shown in Figure 15-18.

Figure 15-18 Setting the server preference

Select Prompt for server before running and click OK.

Configuring the data source


If your enterprise application accesses a database using JDBC or through EJBs,
you have to configure the data sources.

Open the configuration editor for the WebSphere v5.0 on vertex (Copy) server in
the Server Configuration view.

For our sample applications, we require a data source named jdbc/ejbbank.


Follow the instructions in “Defining a data source in the server” on page 256 to
define the data source for the new WebSphere v5.0 on vertex (Copy) server.

Be sure to select Use this data source in container managed persistence for the
EJB-based applications to work (see Figure 8-11 on page 257).

When running on another server, we have to configure authorization for DB2. On


the Security page, for JAAS Authentication Entries, click Add. Enter DB2user as
the alias, and define a user ID and password that are authorized for DB2 on the
remote server machine (Figure 15-19).

Chapter 15. Servers and server configurations 533


Figure 15-19 Defining an authentication entry

On the Data source page, open the EJBBANK data source and set the
authentication alias (Figure 15-20). Save the configuration.

Figure 15-20 Using the authentication for a data source

534 WebSphere Studio Application Developer Version 5 Programming Guide


Important: If you want to run the database applications using the remote
WebSphere server, then you must implement the EJBBANK database on the
remote server machine. See “Installing the EJBBANK database” on page 811
for instructions to set up the database.

Starting and stopping servers


To run your application, you can either select Run on Server from the context
menu of its project (as shown in Figure 15-1) or you can manually start the server
associated with your application. If you select Run on Server, the server will be
started for you automatically.

To start a server manually, select the WebSphere v5.0 on vertex (Copy) server in
the Server Configuration view or in the Servers view (Figure 15-21):
򐂰 In the Server Configuration view, select Control -> Start (context)
򐂰 In the Servers view, select Start (context).

Figure 15-21 Starting a server

This automatically performs the following steps for you:


򐂰 Publishes the enterprise application, if necessary
򐂰 Publishes the server configuration, if necessary
򐂰 Starts the server and the enterprise application

Chapter 15. Servers and server configurations 535


A progress window displays the publishing of the applications to the WebSphere
server (Figure 15-22).

Figure 15-22 Application publishing progress window

You will see the output from the remote server stdout log file in the Console
window (lower right part of Figure 15-23).

When the Console window shows the application is started, you can start a Web
browser by clicking the icon in the toolbar. This brings up the Web browser
and you can enter the URL for the applications.

You can run most of the applications we developed without any changes, for
example:
http://vertex:9080/ItsoProGuideBasicWeb/
http://vertex:9080/ItsoProGuideStrutsWeb/
http://vertex:9080/ItsoProGuideWebServClient/sample/Banking/TestClient.jsp
http://vertex:9080/ItsoProGuideWebServClient/TestBankingWebService.jsp

When running the Struts Web application, your Application Developer window
should look like Figure 15-23.

Tip: If you select a project or an HTML/JSP file and Run on Server, the
enterprise application is published again to the server. This can be time
consuming for larger applications. It is faster to start a browser and enter the
URL. You can also use an external browser instead of the internal browser of
Application Developer.

536 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 15-23 Running the application

Notes:
򐂰 If you start the remote WebSphere Application Server instance before you
start the IBM Agent Controller, you will receive an error message. Make
sure the IBM Agent Controller is started first so it can keep track of the
state of the WebSphere Application Server instance.
򐂰 Do not stop the IBM Agent Controller when it is in control of a server. Doing
so may cause it to lose track of the state of the server, and you may have
to manually terminate the server process in the remote machine using the
Windows Task Manager.

Using the Control option in the server’s context menu in the Server Configuration
view or the context menu of the server in the Servers view are the best ways for
controlling servers.

Chapter 15. Servers and server configurations 537


Although rare, it can happen that a server goes into an inconsistent state and you
cannot start or stop it using its context menu. In that case you can add the Debug
view by selecting Window -> Show view -> Debug and, by using the context
menu of the server in the Debug view, you can terminate the server process and
also remove terminated server processes, as shown in Figure 15-24.

Figure 15-24 Terminating a server process

Changing the applications to run on a remote server


Some of our applications require changes to make them work on a remote
server:

ItsoProGuideDatabaseWeb
The TestDBBeans.jsp requires a user ID and password for the remote server:
<% Connect.setDriverName("COM.ibm.db2.jdbc.app.DB2Driver");
Connect.setUrl("jdbc:db2:EJBBANK");
Connect.setUsername("db2admin"); // authoized user ID
Connect.setPassword("xxxxxxxx"); // authorized password
SelectStatement.setConnectionSpec(Connect);
SelectStatement.setCommand("SELECT * FROM ITSO.CUSTOMER");
SelectStatement.execute();
out.println("Row count is: " + SelectStatement.getRowCount());
%>

538 WebSphere Studio Application Developer Version 5 Programming Guide


The database Web pages application also requires user ID and password in the
initialization parameters of the JSPs. Open the Web application deployment
descriptor (web.xml) on the Servlets page (Figure 15-25):

xxxxxxxx

Figure 15-25

򐂰 Select the ListCreditsMasterview and add values for username and


password.
򐂰 Do the same for the ListCreditsDetailsView.

ItsoProGuideStoredProcWeb
To run the stored procedures you have to redefine the stored procedures in the
remote server DB2 system. You can use the DB2 net JDBC driver to connect to
the database on the remote server and import the table definitions. Then you
would have to recreate and build the stored procedures for the remote DB2
server.

Note: Building DB2 stored procedures using the net driver is very unstable.
One solution is to define the remote database locally and use the app driver.
Another solution is to build the procedures on the remote system.

Apache Tomcat
Application Developer 5.0 ships with support for Apache Tomcat 3.2, 4.0 and 4.1.
However, it does not ship with the Apache Tomcat product itself. To use Apache
Tomcat, you must therefore first download and install it on the machine running
Application Developer.

Tomcat can be downloaded from:


http://jakarta.apache.org/tomcat/

Chapter 15. Servers and server configurations 539


When Tomcat has downloaded and installed, go to Window -> Preferences ->
Server -> Apache Tomcat and fill in the information about where it is installed
(Figure 15-26).

Figure 15-26 Apache Tomcat preferences

Once this is done, you can create a server and a server configuration as
described in “Creating a server and server configuration together” on page 530,
and select the appropriate version of Tomcat as the server type.

Note: Apache Tomcat can only be run as a built-in and local server, not as a
remote server.

TCP/IP Monitor
The TCP/IP Monitor is a simple server that monitors all the requests and the
responses between a Web browser and an application server. By default, when
the TCP/IP Monitor is started, it listens for requests on port 9081 and then it
forwards these requests to the application server on port 9080. For responses
from the application server, the TCP/IP Monitor forwards them back.

540 WebSphere Studio Application Developer Version 5 Programming Guide


Configuring the TCP/IP Monitor
To set up the TCP/IP Monitor, perform these steps:
򐂰 Switch to the Server perspective and select File -> New -> Server and Server
Configuration.
򐂰 Enter a name for the server (ItsoMonitor), select a folder to place it in
(ItsoProGuideServer), select TCP/IP Monitoring Server as the server type,
make sure that None is selected in the template drop-down list, and click Next
(Figure 15-27).

Figure 15-27 Creating a TCP/IP Monitoring Server

This creates a monitoring server that listens to port 9080, which is the default
for a WebSphere v5.0 test environment. If you would like to monitor a
WebSphere v4.0 test environment, select Monitor on port 8080 as the
template instead.

Chapter 15. Servers and server configurations 541


򐂰 On the next page you can configure on which host the server to be monitored
is running. In our example we monitor a built-in test environment, so we use
localhost as the hostname. Keep the port as the default 9080. Click Next.
This creates the TCP/IP Monitoring Server and it is added to the list of servers
in the Server Configuration view.

Using the TCP/IP Monitor


򐂰 To use the TCP/IP Monitoring Server it is best to start the monitor first. The
Console view displays a message about the port the TCP/IP Monitoring
Server is listening on:
Monitoring server started
localhost:9081 -> localhost:9080
򐂰 Now start the ItsoServer server; we use the built-in server for this test. The
console output of the monitor is replaced with the server console.
򐂰 Bring up a Web browser and open the address:
http://localhost:9081/ItsoProGuideStrutsWeb
򐂰 The TCP/IP Monitor view is opened (Figure 15-28). Exercise the application
by navigating through the pages to create some traffic.

Figure 15-28 TCP/IP Monitor view

542 WebSphere Studio Application Developer Version 5 Programming Guide


The TCP/IP Monitor view lists all the HTTP requests that are generated and,
if one is selected, the time, response time, and the type of request.
򐂰 The TCP/IP Monitor can also show more detailed information about the traffic.
Maximize the TCP/IP Monitor view by double-clicking its title or pressing
Ctrl-M. This brings up the window shown in Figure 15-29.

Figure 15-29 TCP/IP Monitor view - maximized

By selecting an HTTP request in the top pane, you can see both the request
from the browser and the response returned by the HTTP server.

Tip: You can use the TCP/IP Monitor to watch HTTP traffic as well as Web
services traffic. By default the generated proxy classes route the SOAP
requests to port 9080, but you can easily change that port to 9081 and watch
the SOAP messages in the TCP/IP Monitor.

You can either change the Java code of the proxy or dynamically change the
target address using the getEndpoint and setEndpoint methods.

Chapter 15. Servers and server configurations 543


Customizing server configurations
Each server configuration can be customized by double-clicking either the server
configuration itself or a server using it. If you double-click a server, you will see an
extra tab, Server, with configuration information for that server instance.

Figure 15-30 shows the window for our WebSphere 5.0 on vertex (Copy) server
using a WebSphere Application Server 5.0 configuration. We double-clicked the
server, thus the extra Server tab is shown.

We will not explain all the options available in this server configuration, only
highlight some of the less obvious ones. If you make any changes, be sure to
press Ctrl-S to save them before starting a server using the configuration.

Figure 15-30 WebSphere remote server settings

Server page
On the Server page (Figure 15-30) you can select if you want to generate the
HTTP server plug-in configuration. Doing so re-generates and publishes the
plugin-cfg.xml file allowing you to test using the IBM HTTP Server on the
remote machine (and not only the application server’s built-in HTTP server). The
plugin-cfg.xml file will be published to the config directory under the
WebSphere remote deployment directory (Figure 15-7 on page 523).

544 WebSphere Studio Application Developer Version 5 Programming Guide


Configuration page
On the Configuration page (Figure 15-31) you can enable and disable the
administration console and the universal test client (UTC). If you have limited
memory in your machine and do not need these features, you can turn them off
to save some valuable memory and also reduce the bring-up time for the server.

Figure 15-31 Server configuration settings

You can also change the Application class loader policy for the server, which
controls the isolation between the applications (EARs) deployed to the server.
The application class loader is the class loader that loads the EJB JARs, utility
JARs and RARs (resource archives) contained in an EAR:
򐂰 SINGLE policy means that there is only one such class loader in the server.
This means that there is no isolation between the EARs in the server and that
classes in an EAR can see classes in the other EARs.
򐂰 MULTIPLE policy, on the other hand, gives each EAR its own application
class loader which then isolates the EARs from each other. This is the
recommended setting and follows the J2EE 1.3 class loading specification.

Applications page
On the Applications page (Figure 15-32) you can also change the application
class loader mode. This determines how the application class loader should
delegate the loading of classes.

Chapter 15. Servers and server configurations 545


Figure 15-32 Server applications settings

򐂰 When PARENT_FIRST (which is the default and the recommended setting) is


used, the application class loader delegates the loading of classes to its
parent class loader (which is the WebSphere extension class loader) and only
if the parent class loader fails to load the class does the application class
loader attempt to load it.
򐂰 When using PARENT_LAST, the application class loader first attempts to
load the class and only if it fails will it delegate the loading of the class to its
parent. This can be used to give JARs packaged in the root of an EAR file
precedence over JARs on the WebSphere extension classpath. Examples of
such JARs could be JDBC drivers or other common, stable classes.
The WebSphere Extension class loader uses the ws.ext.dirs classpath to
locate classes. On the Paths tab you can add folders and JARs to this
classpath and they will then be visible to the whole server.

The Applications tab also allows you to change the WAR class loader policy,
which affects the isolation between the Web modules in an EAR:
򐂰 When using MODULE policy, each Web module gets its own class loader and
the Web modules are isolated from each other. This is the default and
recommended setting.
򐂰 When using APPLICATION policy, the classes in all Web modules in the EAR
are loaded by the application class loader and there is no isolation between
the Web modules.

546 WebSphere Studio Application Developer Version 5 Programming Guide


Environment page
On the Environment page (Figure 15-33) you can supply environment properties
to the JVM.

Figure 15-33 Server environment settings

򐂰 By default the IBM Java Virtual Machine used by Application Developer sets
its maximum heap size to half the amount of RAM installed in the machine.
For a machine with 512MB of RAM, this means that the JVM of Application
Developer has a maximum heap size of 256MB.
򐂰 When a built-in server environment is started, Application Developer starts a
new JVM for the server. By default, this JVM also has a maximum heap size
setting of half the amount of RAM installed in the machine, so on a 512MB
machine this JVM also uses a maximum heap size of 256MB.
򐂰 When the heaps in these two JVMs reach their maximum size, they have in
total consumed 512MB of RAM, equal to the total amount of RAM installed in
the machine.
򐂰 As the JVM processes themselves require more RAM than just their heap and
the operating system and other processes on the machine also require RAM,
this can lead to excessive swapping, slowing the whole machine down.
򐂰 By adding the -Xms and -Xmx options (Figure 15-33) to set the initial and
maximum heap sizes of the built-in test server JVM you can limit the amount
of ram this process will consume. Lowering this setting, however, leads to
more frequent garbage collection, but it can improve performance anyway
since swapping to disk is really slow.
򐂰 These settings can be tuned together with the -Xms and -Xmx settings for the
JVM of Application Developer (see “Memory consideration” on page 25) to
achieve a system that performs well even in a memory constrained
environment.

Chapter 15. Servers and server configurations 547


Setting the values too low, however, may cause an out-of-memory condition
and freeze Application Developer or the built-in server. If you encounter such
conditions, revert to the default value for Application Developer, which is
-xms=64M (and no -Xmx value).
򐂰 Also, debugging and profiling an application requires more RAM than simply
running it. Therefore, it can be good to have multiple server configurations
tuned for their purposes and then simply switch between them.

On a 512 MB machine, we have been able to find a sweet spot for our
environment by using the following values:
򐂰 Application Developer JVM: -Xms128M -Xmx128M
򐂰 Built-in test server JVM: -Xms96M -Xmx96M

Using these values, we have been able to keep our Windows 2000 installation
with Application Developer 5.0 and some applications running within the 512MB
limit without too much swapping.

Administrative console
If you enable the administration console (Figure 15-30 on page 544) and start a
server using the configuration you can launch the administration console for the
server by selecting the server in the Servers view and then select Run
administrative console from its context menu (Figure 15-34).

Figure 15-34 Launching administrative console

This brings up the administrative console for the server (Figure 15-35), allowing
you to perform administrative tasks and change settings not available in the
server configuration.

548 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 15-35 WebSphere Application Server 5.0 administrative console

Applying Fix Packs to the WebSphere test environment


You can apply WebSphere Application Server Fix Packs (previously called
eFixes) to Application Developer’s built-in test environments to keep them
up-to-date and synchronized with your production environment.

The trick to applying the Application Server Fix Packs to Application Developer is
first to get the right Fix Pack, and then to know where to install it.

Fix Packs for Application Server can be downloaded from:


http://www.ibm.com/software/webservers/appserv/support/index.html

Application Developer 5.0 comes with support for the following Application
Server built-in test environments:
򐂰 WebSphere Application Server 5.0
򐂰 WebSphere Application Server 5.0 Express
򐂰 WebSphere Application Server 4.0 Advanced Edition Single Server

The Fix Pack to download must therefore be for one of these products.

Chapter 15. Servers and server configurations 549


Note: If applying a Fix Pack to a WebSphere v4.0 test environment, make
sure to download the Fix Pack for the WebSphere Application Server 4.0
Advanced Edition Single Server product.

Once the Fix Pack is downloaded, you must to know where to install it.
WebSphere Application Server’s default installation directory is C:\Program
Files\WebSphere\AppServer. However, in Application Developer the run-times
are located in the following directories:
򐂰 WebSphere Application Server 5.0:
<wsad_home>\runtimes\base_v5
򐂰 WebSphere Application Server 5.0 Express:
<wsad_home>\runtimes\express_v5
򐂰 WebSphere Application Server 4.0 Advanced Edition Single Server:
<wsad_home>\runtimes\aes_v4

When prompted for the Application Server Home directory during fixpack
installation, you should enter the corresponding directory above.

At the time of writing, there are no Fix Packs available for Application Server 5.0,
so in this example we update the Version 4.0 test environment to Fix Pack 5
(4.0.5).

Perform the following steps:


򐂰 Download the correct Fix Pack and unzip it to a temporary directory. The file
we downloaded was called was40_aes_ptf_5.zip and we unzipped it to
C:\temp\was40ptf5.
򐂰 Run install.bat from the directory.
򐂰 At the prompts, reply with the following answers:
– Update the Application Server (yes/no)? yes
– Enter the Application Server Home:[Example: C:\WebSphere\AppServer]
C:\WSAD5\runtimes\aes_v4
– Use the Application Server JDK (yes/no)? yes
– Perform update of the JDK (yes/no)? yes
– Update iPlanet Web server configuration for support by WebSphere
(yes/no)? no
– Perform update of the IBM HTTP Server (yes/no)? no
– Perform update of the Apache Web server (yes/no)? no

550 WebSphere Studio Application Developer Version 5 Programming Guide


– Use the Application Server Logs directory (yes/no)? yes
– Place backups under the WebSphere Application Server Home (yes/no)?
yes

When the Fix Pack is applied, you can start the server in Application Developer
and verify that it was successfully updated. When starting our server the
following message was displayed, indicating a successful update:
*** Starting the server ***
IBM WebSphere Application Server, Release 4.0.5
Advanced Single Server Edition for Multiplatforms
Copyright IBM Corp., 1997-2001

Summary
In this chapter we have shown you how to use the server tools feature of
Application Developer to test Web and EJB applications. We set up both a
built-in test environment and a remote WebSphere Application Server, and we
published and tested an application.

We examined the server configurations and gave you some tips on how to
improve performance.

The TCP/IP Monitor server was also covered. Finally, we showed you how to
update the internal test environment by applying WebSphere Fix Packs.

Chapter 15. Servers and server configurations 551


552 WebSphere Studio Application Developer Version 5 Programming Guide
16

Chapter 16. Testing and debugging


In this chapter, we explain how to use the debugger included within Application
Developer to test Web applications. We also detail how to debug on a remote
server.

This chapter describes the following topics:


򐂰 Debugging a Web application
򐂰 Debugging on a remote WebSphere Application Server

© Copyright IBM Corp. 2003. All rights reserved. 553


Debugging a Web application
In this section, we show how to debug a servlet running as part of a Web
application. We will be using the ListAccounts.java servlet in the
ItsoProGuideBasicWeb project for our example. This is the servlet that was
developed in “Creating dynamic Web resources” on page 203.

Setting breakpoints in a servlet


Breakpoints are indicators to the debugger that it should stop execution at
specific places in the code, and let you step through it. Breakpoints can be set to
trigger always or when a certain condition has been met.

To add a breakpoint in the code, do the following:


򐂰 Open the ListAccounts.java in the Java editor.
򐂰 Place your cursor in the gray bar (along the left edge of the editor area) on the
line Banking banking = new Banking().
򐂰 Double-click to set a breakpoint (Figure 16-1). A marker will be shown at the
line.

Figure 16-1 Add a breakpoint

554 WebSphere Studio Application Developer Version 5 Programming Guide


Note: Enabled breakpoints are indicated with a blue circle. If the enabled
breakpoint is successfully installed in a class in the VM at runtime, it is
indicated with a check mark overlay.

Right-click the breakpoint in the breakpoint view, and select Breakpoint


Properties from the context menu. A window opens where more detailed options
about the breakpoint are displayed (Figure 16-2).

Figure 16-2 Breakpoint properties

The Enable Hit Count property, when set, causes the breakpoint to be triggered
only when the lines has been executed as many times as the hit count specified.
Once triggered, the breakpoint is disabled.

The other property of interest here is Enable Condition. If set, then the breakpoint
is reached only when the condition specified in the entry field evaluates to true.
This condition is a Java expression. In our case, select Enable Condition and
enter customerNumber.equals("104"); as the condition. The breakpoint will only
be reached when you enter 104 as the customer ID.

The Restrict to Selected Thread(s) list is only filled if a server is running in debug
mode already, otherwise the list in empty.

Chapter 16. Testing and debugging 555


Click OK to close the breakpoint properties. In the breakpoints view, the
breakpoint is now marked with a question mark , which indicates that it is a
conditional breakpoint.

Setting breakpoints in a JSP


You can also set breakpoints in the JSP source code. However, you can only set
breakpoints in Java code and <jsp> tags.

Open the listAccounts.jsp that will be called from the ListAccounts servlet. Set
a breakpoint as shown in Figure 16-3.

Figure 16-3 Setting a breakpoint in a JSP

You could also set a breakpoint in the lines with <jsp.getProperty> tags.
Sometimes reformatting the source code to have only one statement per line is
better for debugging.

556 WebSphere Studio Application Developer Version 5 Programming Guide


Testing the application with breakpoints enabled
Once you have set the breakpoint, the Web application can be started for
debugging.

Note: The server used for testing, for example ItsoServer, must be either
stopped or started in debug mode. Otherwise, an error message will be
displayed.

From the Web perspective, bring up the context menu on ItsoProGuideBasicWeb


and select Debug on Server (Figure 16-4).

Figure 16-4 Debug Web project on server

Tip: To debug a non-Web Java application, select Run -> Debug As -> Java
Application to start the debugger. This is the only difference between
debugging a Web application and debugging a Java application.

Application Developer switches to debug perspective automatically, if the


preference to do so is set.

In the Debug perspective, you should now see index.html displayed in the Web
Browser view, as shown in Figure 16-5. Enter 104 as the customer ID.

Chapter 16. Testing and debugging 557


Figure 16-5 Web browser in the Debug perspective

Click Submit to display the list of accounts.

You are prompted to step into the itso.basicweb.control.ListAccounts.doPost


method. This is a feature in the debugger to allow you to debug code without
setting breakpoints. It can be disabled by clicking Enable/Disable step-by-step
debugging .

Select the Skip radio button, then check the Disable step-by-step mode check
box, and click OK (Figure 16-6).

558 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 16-6 Disable step-by-step debugging

After step-by-step has been disabled, the servlet is executed. As soon as the
breakpoint in ListAccounts.java is reached, execution stops and the
ListAccounts.java source file is displayed with the line containing the break
point highlighted. The thread is suspended in debug, but other threads might still
be running (Figure 16-7).

Figure 16-7 Debug perspective when stopped at a breakpoint

Chapter 16. Testing and debugging 559


Next we discuss the different views of the Debug perspective.

Debug view with stack frames


When a breakpoint is reached, the debugger displays a list of stack frames
before the breakpoint occurred. Each frame corresponds to a called method. The
entire list is in reverse chronological order. Figure 16-8 shows the stack frame
listing for the breakpoint in the ListAccounts class, doPost method.

Figure 16-8 Stack frame listing in Debug view

When a thread suspends, the top stack frame is automatically selected. If you
select another stack frame, all visible variables in that frame are shown in the
Variables view.

Debug functions
From the Debug view, which should now be displayed in the top left pane, you
can use the functions available from its icon bar to control the execution of the
application. The following icons are available:
򐂰 Resume: Runs the application to the next breakpoint
򐂰 Suspend: Suspends a running thread
򐂰 Terminate: Terminates a process
򐂰 Disconnect: Disconnects from the target when debugging remotely
򐂰 Remove All Terminated Launches: Removes terminated executions

560 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Step Into: Steps into the highlighted statement
򐂰 Step Over: Steps over the highlighted statement
򐂰 Step Return: Steps out of the current method
򐂰 Step Debug: Only for compiled languages (steps to next statement)
򐂰 Show Qualified Names: Toggle option to show the full package name.

In the upper right pane you can see the various debugging views that are
available.

Breakpoints view
The Breakpoints view displays all the breakpoints set in the Workbench.
(Figure 16-9).

Figure 16-9 Debugging views

You can use the breakpoints view to display and manipulate the breakpoints that
are currently set. You can open the properties (for example to set the hit count),
remove the breakpoint, or open its source file.

Watching variables
The Variables view displays the current values of the variables in the selected
stack frame. Follow these steps to see how you can track the state of a variable.

Click the Step Over icon to execute the current statement. Note that a new
variable banking has been added to the Variables view.

Click Step Over again and the customer variable is added. The plus sign (+) next
to a variable indicates that it is an object. Expand the customer to reveal the
values of its attributes (Figure 16-10).

Chapter 16. Testing and debugging 561


Figure 16-10 Displaying variables

If you want to test the code with some other value for any of these instance
variables, you can change one of them by selecting Change Variable Value from
its context menu. An entry field opens where you can change the value; for
example, you can change the last name to upper case (Figure 16-11).

Figure 16-11 Changing a variable value

Inspecting variables
To view more details about a variable, select a variable and Inspect from the
context menu. The result opens in expressions view (Figure 16-12).

Both the Variables and Expressions view can be split into two panes by selecting
Show Detail Pane from the context menu.

562 WebSphere Studio Application Developer Version 5 Programming Guide


Details pane

Figure 16-12 Inspecting a variable in Expressions view

Evaluating an expression
To evaluate an expression in the context of the currently suspended thread, use
the Display view. Enter the expression customer.getFirstName(), then highlight
the expression and select Display from the context menu.

Do the same for the expression banking.getTransactions("104-4001"). Each


expression is executed and the result is displayed (Figure 16-13).

Figure 16-13 Expression and evaluated result in display view

The results of the Java expression can also be inspected by selecting Inspect
from the context menu.

You can also highlight any expression in the source code and select Display or
Inspect (context). The result is shown either in the Display or Expressions view.

For example, highlight the expression banking.getCustomer(customerNumber) in


the source code and select Inspect (context). The result is displayed in the
Expressions view (Figure 16-14).

This is a useful way to evaluate Java expressions during debugging, without


having to make changes in your code and recompile.

Chapter 16. Testing and debugging 563


Figure 16-14 Inspection of Java expression

Select Remove from the context menu to remove expressions or variables from
the Expressions views. In the Display view just select the text and delete it.

Now step over the next statement:


Account[] accounts = banking.getAccounts(customerNumber);

Watch the array of accounts in the Variables view. You can expand accounts and
see their attributes (Figure 16-15).

Figure 16-15 Watching an array in the Variables view

Debugging a JSP
Step through the servlet code or click the Resume icon to progress to the
breakpoint in the JSP.

Figure 16-16 shows the Debug view with the JSP opened.

Note: If you have two JSPs in different Web applications, the wrong JSP
source may be displayed. Open the correct JSP to see its source code.

564 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 16-16 Debugging a JSP

Watch the JSP variables in the Variables view. The same functions as for servlets
are available for JSP debugging. A JSP is compiled into a servlet. The difference
is that the debugger shows the JSP source code and not the generated Java
code.

When you step through JSP code, the debugger only stops at Java code; HTML
statements are skipped.

Resume execution to see the next Web page, then close the Debug perspective
and stop the server.

Chapter 16. Testing and debugging 565


Debugging on a remote WebSphere Application Server
It is possible to connect to and debug a Java program that has been launched in
debug mode on a remote application server, and the application server has been
configured to accept remote connections. Debugging a remote program is similar
to debugging a local Java program, except that the program has already been
launched and could be running on a remote host.

Important: This section assumes that you have already deployed the
ItsoProGuide enterprise application containing the ItsoProGuideBasicWeb
project to a remote Application Server. For details on deploying to a remote
server, see Chapter 18, “Deploying enterprise applications” on page 607

Configuring the remote server


The following steps explain how to configure WebSphere Application Server
version 5.0 to start in debug mode:
򐂰 Start the application server.
򐂰 Launch and log in to the Administrative Console.
򐂰 In the left-hand frame, expand the Servers node and then select Manage
Application Servers. (Without Network Deployment installed, the link is simply
called Application Servers.) This opens the Application Servers page.
򐂰 In the Application Servers page, all application servers are listed by Name
and Node. In the Name column, each server name appears as a link which,
when selected, takes you to configuration pages for the server. Follow the link
for the server that you wish to set up for debug mode.
򐂰 On the Configuration tab, select Debugging Service in the Additional
Properties section to open the Debugging Service configuration page.
򐂰 In the General Properties section of the Configuration tab, select the Startup
check box. This enables the debugging service when the server starts.
򐂰 Note the values of the JVM debug port (default 7777) and BSF debug port
(default 4444) fields, which are needed when connecting to the application
server with the debugger.
򐂰 Click OK to make the changes to your local configuration, and then click Save
to apply the configuration changes.
򐂰 Proceed with other actions in the Administrative Console or log out, as
desired.
򐂰 You must restart the application server before the changes that you have
made take effect.

566 WebSphere Studio Application Developer Version 5 Programming Guide


Attaching to remote server in Application Developer
In the server perspective, in the server configuration view, select Servers and
select New -> Server and server configuration from the context menu
(Figure 16-17).

Enter WebSphere version 5.0 remote server attach as the server name, and
select WebSphere version 5.0 -> Remote Server Attach as the server type. Click
Next to proceed to the next page of the wizard.

Figure 16-17 Create new remote server attach

On the next page, enter the host name of the remote host where WebSphere
Application Server Version 5 is installed (Figure 16-18). This can be your own
machine (localhost) or another machine (such as vertex used for remote
testing).

Chapter 16. Testing and debugging 567


or hostname

Figure 16-18 Specify the host for the remote server attach

Click Next to go to the next page of the wizard. There, you enter the port
numbers for JVM debug and for HTTP (Figure 16-19). The JVM debug port is the
port that Application Developer will use to communicate with the remote
application server during debugging. The HTTP port is the port used to send
HTTP commands through the Web browser.

Figure 16-19 Set ports for attaching to remote server

By default, the JVM debug port is set to 7777 in both the wizard and in the
Application Server. In this example, we are connecting to a remote application
server that uses port 9080 for HTTP (the internal HTTP server). If the external
HTTP Server is started as well, we can use port 80.

Click Finish to create the remote server attach. In the servers view, this new
server is now listed (Figure 16-20).

568 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 16-20 New remote server in servers view

Connecting to the remote server


To connect to the remote server, select WebSphere version 5.0 remote server
attach server and select Debug from the context menu. Alternatively, you may
click Debug .

You are taken to the debug perspective, and the remote server is connected
(Figure 16-21). You may now debug applications on the remote server.

Figure 16-21 Attached to remote server

Debugging on the remote server


The next step needed to debug on a remote server is to add the project to the
server. In server perspective, select the new WebSphere version 5.0 remote
server attach server and select Add -> ItsoProGuide.

The Server Configuration view reflects this change (Figure 16-22).

Chapter 16. Testing and debugging 569


Figure 16-22 ItsoProGuide project added to remote server attach

Note: The project should already be published on the remote server. Here we
are just configuring this in Application Developer to allow us to debug.

Next, we debug the application on the remotely attached server. Select the
ItsoProGuideBasicWeb in the Navigator view and Debug on Server. If you are
prompted to select the server to debug the application on, select WebSphere
version 5.0 remote server attach.

Tip: Make sure that the server preference of the project properties is set to
prompt; otherwise the preferred server is started!

The index.html page of the Web application opens. You may now debug the
application in the same way you did in “Debugging a Web application” on
page 554. The only difference is that the application is running on a remote
server.

Where is the source code?


If you use the enterprise application as deployed in Chapter 18, “Deploying
enterprise applications” on page 607, that is, without source code, then you
cannot see the source that you are debugging. You can see the variables while
you step into code.

When entering a class, such as itso.basicweb.control.ListAccounts, you can


locate the source code as shown in Figure 16-23:
1. Select the line in the Debug view and Change Source File (context).
2. In the Debugger Source Selection window click Browse.
3. Deselect Use default source lookup path and click Add Projects. Select the
ItsoProGuideBasicWeb project and add it to the list.
4. Click OK to add the ListAccounts class to the list.

570 WebSphere Studio Application Developer Version 5 Programming Guide


5. Select the ListAccounts line and click OK.

3
1

4
2

Figure 16-23 Attaching source code to the remote debugger

With the source code attached, you can debug the classes by stepping through
the code. Debugging on a remote server is basically the same as debugging on
the internal server.

Note: You may find response time quite slow. The more applications you have
deployed on the remote server, the slower is execution.

Chapter 16. Testing and debugging 571


Disconnecting from the remote server
To disconnect from a remote server, select the server in the Servers view and
click the disconnect button . Alternatively, select the server and select
Disconnect from the context menu.

Communication with the remote server is terminated, and all threads in the
remote VM are resumed. Although the remote VM continues to execute, the
debug session is now terminated.

Summary
In this chapter we described the process of debugging Web applications on the
built-in server and on a remote WebSphere Application Server.

Let us conclude with a generic tip for debugging.

Tip: You can make your programs easier to debug by avoiding having multiple
statements on one line, and by attaching the source code to JAR files.

572 WebSphere Studio Application Developer Version 5 Programming Guide


17

Chapter 17. JUnit and component


testing
JUnit is an open source testing framework for Java that is included in Application
Developer. It provides a simple way of expressing how you intend your code to
work. In this chapter, we explain what JUnit is, then go over the benefits of unit
testing and using a unit testing framework. Next we describe how to set up JUnit
for use in the Workbench and how to write tests with JUnit.

Following that, we introduce component testing within Application developer, and


show examples of creating, running, and reporting the results of Java and HTTP
component tests.

In this chapter, we cover the following topics:


򐂰 What is JUnit?
򐂰 Preparing for JUnit
򐂰 Creating the test case
򐂰 Running the test case
򐂰 Component testing

© Copyright IBM Corp. 2003. All rights reserved. 573


What is JUnit?
JUnit is an open source testing framework that is used to develop and execute
unit tests in Java. It was written by Erich Gamma, one of four notable authors,
who wrote the classic book Design Patterns; and Kent Beck, who has also
written extensively about object development and first described the eXtreme
Programming (XP) software development process.

A good starting point for finding information about JUnit on the Web is the JUnit
Web site:
http://www.junit.org/

This site contains documentation and links, as well as a free download that
includes both the JUnit source and compiled code.

Unit testing
Unit tests are informal tests that are generally executed by the developers of the
application code. They are often quite low-level in nature, and test the behavior of
individual software components such as individual Java classes, servlets, or
EJBs.

Because unit tests are usually written and performed by the application
developer, they tend to be white-box in nature, that is to say they are written
using knowledge about the implementation details and test specific code paths.
This is not to say all unit tests have to be written this way; one common practice
is to write the unit tests for a component based on the component specification
before developing the component itself. Both approaches are valid and you may
want to make use of both when defining your own unit testing policy.

Why unit testing?


On the surface, this is a question with a straightforward answer. We test to find
defects in our code, and to verify that changes we have made to existing code do
not break that code.

Perhaps it is more useful to look at the question from the opposite perspective,
that is to say, why do developers not perform unit tests? In general the simple
answer is because it is too hard, and because nobody forces them to. Writing an
effective set of unit tests for a component is not a trivial undertaking. Given the
pressure to deliver that many developers find themselves subjected to, the
temptation to postpone the creation and execution of unit tests in favor of
delivering code fixes or new functionality is often overwhelming.

574 WebSphere Studio Application Developer Version 5 Programming Guide


In practice, this usually turns out to be a false economy—developers very rarely
deliver bug-free code, and the discovery of code defects and the costs
associated with fixing them are simply pushed further out into the development
cycle. This is inefficient—the best time to fix a code defect is immediately after
the code has been written, while it is still fresh in the developer’s mind.
Furthermore, a defect discovered during a formal testing cycle must be written
up, prioritized, and tracked—all of these activities incur cost, and may mean that
a fix is deferred indefinitely, or at least until it becomes critical.

Based on our experience, we believe that encouraging and supporting the


development and regular execution of unit test cases ultimately leads to
significant improvements in productivity and overall code quality. The creation of
unit test cases does not have to be a burden—developers often find the
intellectual challenge quite stimulating and ultimately satisfying. The thought
process involved in creating a test can also highlight shortcomings in a design,
which may not otherwise have been identified when the main focus is on
implementation.

We recommend that you take the time to define a unit testing strategy for your
own development projects. A simple set of guidelines, and a framework that
makes it easy to develop and execute tests, pays for itself surprisingly quickly.

Benefits of a unit testing framework


Once you have decided to implement a unit testing strategy in your project, the
first hurdles to overcome are the factors that dissuade developers from creating
and running unit tests in the first place. A testing framework can help by making it
easier to:
򐂰 Write tests
򐂰 Run tests
򐂰 Rerun a test after a change

Tests are easier to write, because a lot of the infrastructure code that you require
to support every test is already available. A testing framework also provides a
facility that makes it easier to run and re-run tests, perhaps via a GUI. The more
often a developer runs tests, the quicker problems can be located and fixed,
because the difference between the code that last passed a unit test, and the
code that fails the test, is smaller.

Testing frameworks also provide other benefits:


򐂰 Consistency—Because every developer is using the same framework, all of
your unit tests work in the same way, can be managed in the same way, and
report results in the same format.

Chapter 17. JUnit and component testing 575


򐂰 Maintenance—Because a framework has already been developed and is
already in use in a number of projects, you spend less time maintaining your
testing code.
򐂰 Ramp-up time—If you select a popular testing framework, you may find that
new developers coming into your team are already familiar with the tools and
concepts involved.
򐂰 Automation—A framework may offer the ability to run tests unattended,
perhaps as part of a daily or nightly build.

Automatic builds: A common practice in many development environments is


the use of daily builds. These automatic builds are usually initiated in the early
hours of the morning by a scheduling tool.

Testing with JUnit


A unit test is a collection of tests designed to verify the behavior of a single unit
within a class. JUnit tests your class by scenario, and you have to create a testing
scenario that uses the following elements:
򐂰 Instantiate an object
򐂰 Invoke methods
򐂰 Verify assertions

Note: An assertion is a statement that allows you to test the validity of any
assumptions made in your code.

This simple test case tests the result count of database query:
//Test method
public void testGetAccount(){
//instantiate
Banking banking = new Banking();
//invoke a method
Account account = banking.getAccount("104-4001");
//verify an assertion
assertEquals(account.getAccountId(),"104-4001");
}

In JUnit, each test is implemented as a method that should be declared as public


void and take no parameters. This method is then invoked from a test runner
defined in a different package. If the test method name begins with test..., the test
runner finds it automatically and runs it. This way, if you have a large number of
test cases, there is no need to explicitly define all the test methods to the test
runner.

576 WebSphere Studio Application Developer Version 5 Programming Guide


TestCase class
The core class in the JUnit test framework is junit.framework.TestCase. All of
our test cases inherit from this class:
import junit.framework.TestCase;

public class BankingTest extends TestCase {

/**
* Constructor for BankingTest.
* @param arg0
*/
public BankingTest(String arg0) {
super(arg0);
}

All test cases must have a constructor with a string parameter. This is used as a
test case name to display in the log.

Tests are executed using a test runner. To run this test, use TestRunner as
follows.
public static void main (String[] args) {
junit.textui.TestRunner.run (BankingTest);
}

TestSuite class
Test cases can be organized into test suites, managed by the
junit.framework.TestSuite class. JUnit provides tools that allow every test in a
suite to be run in turn and to report on the results.

TestSuite can extract the tests to be run automatically. To do so, you pass the
class of your TestCase class to the TestSuite constructor.
TestSuite suite = new TestSuite(BankingTest.class);

This constructor creates a suite containing all methods starting with test and that
take no arguments.

Alternatively, you can add new test cases using the addTest method of
TestSuite:
TestSuite suite = new TestSuite();
suite.addTest(new BankingTest("testBankingConnection"));
suite.addTest(new BankingTest("testBanking"));

Chapter 17. JUnit and component testing 577


Creating the test case
Application Developer contains wizards to help you build JUnit test cases and
test suites. We will use this wizard to create the BankingTestTest test class to
test the BankingTest JavaBean, which is a facade of a banking application that
allows you to get information about your account, withdraw, and deposit funds.
We use a copy of the banking model of the ItsoProGuideJava project.

In our example, we use a Java project called ItsoProGuideJUnit. Create the Java
project (New -> Project -> Java -> Java Project). Enter its name and click Next.

Importing the model


We will use the banking model of the ItsoProGuideJava project. You can either
copy the Java packages from that project or import the JAR file:

Select the ItsoProGuideJUnit project and Import (context). Select ZIP file, click
Next, locate the \sg246957\sampcode\dev-java\BankingModel.jar file, and click
Finish.

Preparing for JUnit


To use JUnit in the Application Developer Workbench, you have to add the JUnit
packages to the classpath of the Java project. The jar file is:
c:\WSAD5\eclipse\plugins\org.junit_3.7.0\junit.jar

Open the ItsoProGuideJUnit project properties. On the Libraries page add a


JUNIT variable that points to the junit.jar file. Also add the DB2JAVA variable to
the build path (Figure 17-1).

Figure 17-1 Updating Java build path

578 WebSphere Studio Application Developer Version 5 Programming Guide


Creating a test case
Here we create a test case for the deposit method of the BankingTest facade.

To begin, use the Java perspective of Application Developer, and expand


ItsoProGuideJUnit -> itso.bank.model.facade, select the BankingTest.java
class and New -> Other (context). Expand Java, select JUnit -> TestCase and
click Next.

Figure 17-2 Create a JUnit Test Case

Figure 17-3 shows the next page of the wizard, where you enter details about the
new test case:
򐂰 Set the source folder to ItsoProGuideJUnit (where we want to store the test
case).
򐂰 Enter itso.junit as package name.
򐂰 Select public static void main(String[] args) and Add TestRunner statement for
and select text ui in the combo box. The creates a main method in the test
case, and adds a line of code that executes the TestRunner to run the test
methods and output the results.
򐂰 Select setUp() to create a stub for this method in the generated file.

Chapter 17. JUnit and component testing 579


Figure 17-3 Specify test case and test class

We leave the default values for all other fields on this page. The other options on
this page are:
򐂰 Test case—The name of the new test case class is generated as the name of
the source class we want to test, with Test as a suffix.
򐂰 Test class—The Java class that this new test case is testing.
򐂰 Superclass—By default the JUnit TestCase class, but can be changed if you
extend the JUnit package yourself.
򐂰 Method stubs—Which method stubs do you want to generate:
– main is the method that is executed to start the JUnit test case as a Java
application. This is not required, as within Application Developer, we can
run Java classes as JUnit test cases.
– The check box, Add TestRunner statement for:, has three options: text ui,
swing ui, awt ui. These options add a single line of code to the main
method to run the test case and output the results in three different user
interfaces. Text is plain text, while swing and awt are graphical outputs.
– setUp is a method that is executed before the tests.
– tearDown is a method that is executed after the tests.

580 WebSphere Studio Application Developer Version 5 Programming Guide


Note: A stub is a skeleton method, generated so that you can add the body of
the method yourself.

Click Next to proceed to the next page of the wizard. Figure 17-4 shows the
available methods for which stubs should be created. We select the deposit
method.

Figure 17-4 Test methods

Think of the stub methods as just a suggestion for a few scenarios to test in your
test case. You can add as many methods to the generated file as you would like,
and the naming conventions are up to you. This page of the wizard gets you
started.

Click Finish to complete the wizard. BankingTestTest.java is generated and can


now be used to test the BankingTest class. All that remains to do is to write your
testing code.

Chapter 17. JUnit and component testing 581


The setUp and tearDown methods
Typically, you run several tests in one test case. To make sure there are no side
effects between test runs, the JUnit framework provides the setUp and tearDown
methods. Every time the test case is run, setUp is called at the start and tearDown
at the end of the run.

In our new BankingTestTest test case, we must add the following private object
that will be instantiated before starting the test:
//Banking facade
private itso.bank.facade.BankingTest banking;

In the setUp method, add the following code to create an instance of the Banking
facade:
public void setUp(){
super.setUp();
banking = new itso.bank.facade.BankingTest();
}

In our example, there is no tearDown method. This method could be used to


clean up the application by performing tasks such as disconnecting from a
database. In our case, no cleanup is required.

Test methods
Next we update the stub testDeposit method by adding the code shown in
Figure 17-5.

This method retrieves an account balance, then deposit funds into that account.
Then it retrieves the account balance again and verifies that the balance before
plus the deposit amount is equal to the balance after the deposit was made.

After entering the code, select Source -> Organize Imports from the context
menu to fix any unresolved errors. Make sure that you import
java.math.BigDecimal when prompted.

Note: We first tested the balance by retrieving the Account object before and
after the deposit. This logic fails because, with the in-memory model of the
ItsoProGuideJava project, the same Account object is retrieved. This does
work if new objects are created by the model.

582 WebSphere Studio Application Developer Version 5 Programming Guide


/**
* Method to deposit funds to an account, and verify that the
* balance afterwards is equal to the balance before plus the
* deposited amount
*/
public void testDeposit() {
try {
// invoke three methods to get account info, deposit
// funds, then get account info after deposit
BigDecimal balanceBefore =banking.getAccount("104-4001").getBalance();
banking.deposit("104-4001", new BigDecimal(100));
BigDecimal balanceAfter = banking.getAccount("104-4001").getBalance();
//verify an assertion
assertEquals(
balanceBefore.add( new BigDecimal(100) ),
balanceAfter );
} catch (Exception ex) {
fail(ex.getMessage());
}
}

Figure 17-5 Method to test and verify depositing funds to an account

Now we add another test method called testDepositInvalidAccount. This


method verifies that if you enter an invalid account ID, you receive the proper
AccountDoesNotExistException exception (Figure 17-6).

/**
* Method to test making a deposit to an invalid account number
*/
public void testDepositInvalidAccount() {
try {
// test getting an invalid account
banking.deposit("AAAA", new BigDecimal(1));
fail("Got account even though used invalid account id");
} catch (AccountDoesNotExistException accex) {
assertTrue(true);
} catch (Exception ex) {
fail(ex.getMessage());
}
}

Figure 17-6 Method to test depositing to an invalid account

Save and close BankingTestTest.java.

Chapter 17. JUnit and component testing 583


JUnit supplied methods
The assertEquals, assertTrue, and fail methods are provided by the JUnit
framework.

JUnit provides a number of methods that can be used to assert conditions and
fail a test if the condition is not met. These methods are inherited from the class
junit.framework.Assert (see Table 17-1).
Table 17-1 JUnit assert methods
Method name Description

assertEquals Assert that two objects or primitives are equal. Compares objects
using equals, and compares primitives using ==.

assertNotNull Assert that an object is not null

assertNull Assert that an object is null

assertSame Assert that two objects refer to the same object. Compares using ==.

assertTrue Assert that a boolean condition is true

fail Fails the test

All of these methods include an optional String parameter that allows the writer of
a test to provide a brief explanation of why the test failed—this message is
reported along with the failure when the test is executed, for example:
assertEquals(String message, object expected, object actual);).

Creating a TestSuite
A TestSuite is used to run one or more test cases at once.

Application Developer contains a simple wizard to create a test suite. Select the
itso.junit package and New -> Other -> JUnit -> TestSuite. Alternatively select
the project folder and package after you start the wizard.

The test classes window shows all test cases in the specified package, selected
by default. In our case, BankingTestTest is shown and selected. The first page of
the wizard is shown in Figure 17-7.

584 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 17-7 Create JUnit TestSuite

By default, the test suite is called AllTests. If you had multiple test classes, you
could include them in one suite. In our case, we have only one test class. The
check boxes to create a method stub for the main method does just that, and we
select that here as well as the check box to add a TestRunner statement.

The generated AllTests Java source opens, and requires a small modification.
You must change the TestRunner statement to the following:
public static void main(String[] args) {
junit.textui.TestRunner.run( suite() );
}

This code uses the text-based test runner tool in the JUnit framework, which runs
the tests and reports the results.

In our case, using a TestSuite is not required. However, as you add more and
more test cases, a TestSuite is more practical.

Chapter 17. JUnit and component testing 585


Running the test case
There are a couple of ways to run our new test case.

Select the BankingTestTest class and Run -> Run As -> JUnit Test from the
menu bar. Application Developer opens a JUnit View with the results of the run
(Figure 17-8).

Figure 17-8 JUnit view

A test is considered to be successful if the test method returns normally. A test


fails if one of the methods from the Assert class signals a failure. An error
indicates that an unexpected exception was raised by the test method, or the
setUp or tearDown method was invoked before or after it.

Tip: To run just one test case, select the test case class and Run -> Run As ->
JUnit Test. To run all the test cases, run the test suite class.

The JUnit view is more interesting when an error or failure occurs. Update
BankingTestTest so that the testDepositInvalidAccount method causes an
error by changing the account ID to a valid one:
banking.deposit("104-4001", new BigDecimal(1));

Figure 17-9 shows the JUnit view when the test case is run as a JUnit test again.
This time, an error occurs and its details are output in the Failures list.

586 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 17-9 Junit view with failure

Selecting the testDepositInvalidAccount method in the Failures list updates the


Failure Trace window to show the stack trace of the failure. This makes it easy for
you to track where the failure occurred. Double-clicking the entry in the Failure
Trace list takes you to the specified line in the specified Java source file.

Alternatively, the BankingTestTest class can be run as a Java application by


selecting Run -> Run As -> Java Application, which executes the main method
and uses the TestRunner from the JUnit framework to run and output the test
results.

Figure 17-10 shows the output from the Banking test case, containing the same
update noted above, run as a Java application. We can see that there was one
success and one failure. The failure occurred when running
testDepositInvalidAccount.

Figure 17-10 Output from running BankingTest as Java Application, with failure

Chapter 17. JUnit and component testing 587


Each dot (.) in the first line of the output represents the start of a test. We have
two tests in our test case, so there are two dots. An “F” indicates a failure, so one
test failed. Once all the tests have completed, the test runner shows how long
they took to run and a summary of the results.

Once we have corrected the error, the output in Figure 17-11 is shown.

Figure 17-11 Output from running the test case as Java Application, no failures

Testing the Web applications


You can also create test cases that run against one of the Web projects,
ItsoProGuideBasicWeb or ItsoProGuideStrutsWeb.

However, you cannot easily run the test cases when the Web application uses
the EJB back-end. Test cases are run as Java applications, and you cannot
access EJBs from a Java project.

Possible alternatives:
򐂰 You can test the Banking class in the Web projects if you change the flag to
use the in-memory objects:
boolean ejb = true;
򐂰 You create a J2EE client project as part of the enterprise application for the
test cases. J2EE clients can access EJBs when run in a client container.
򐂰 You create test case classes as servlets in the Web project.

Component testing
The Component Test perspective provides a framework for defining and
executing test cases. The basic framework supports three sorts of test case,
based on their different scheduler: manual, Java, and HTTP. You can also create
report generators to work with the data returned by an executed test case.

In order to use component tests, you must have a host with the Agent Controller
installed and running. The Agent Controller is not installed by default when

588 WebSphere Studio Application Developer Version 5 Programming Guide


installing Application Developer. For more information on the Agent Controller,
see “Agent Controller” on page 657.

Here we will define Java test cases, which implement the JUnit framework
described earlier in the chapter. We will use the project ItsoProGuideJUnit
explained in “Preparing for JUnit” on page 578.

Change to the Component Test perspective by clicking Window -> Open


Perspective -> Other, then selecting Component Test, and click OK.

Creating a Java test case


In the definition view, right-click Testcases and select New -> Testcase.

Select the ItsoProGuideJUnit project, then enter BankingTestCase in the New


Testcase wizard, as shown in Figure 17-12.

Figure 17-12 New Test case wizard

Chapter 17. JUnit and component testing 589


In the next page of the wizard, select Java, then click Finish to complete the
wizard. This is illustrated in Figure 17-13.

Figure 17-13 Specify attributes of a test case

You have now created the BankingTestCase test case. You now see
BankingTestCase listed in the Testcases folder of the Definition view.

Next, we create a task within the test case that translates into a method in a JUnit
test class. In the Outline view, select Main Block. Select New -> Task -> Java
from the context menu.

In the editor view for BankingTestCase, change the name of the task from T1 to
testGetAccount (Figure 17-14).

You can also add a description for this task in the Description field, if desired.

590 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 17-14 BankingTestCase in the editor view

Save the changes. We have now outlined the tasks to be performed in this Java
test case. Now we prepare the test case, thus generating a JUnit test class.

Preparing a Java test case


Before running a Java test case, we must prepare it. This generates all JUnit
code. We can then add code to the previously declared tasks, which map to
methods in a JUnit test case.

In the Definition view, select the BankingTestCase and Prepare (context). The
prepare test case wizard opens (Figure 17-15).

Chapter 17. JUnit and component testing 591


Figure 17-15 Prepare test case

Click Next, then click New Host and the new host dialog opens (Figure 17-16).

Figure 17-16 New host dialog

592 WebSphere Studio Application Developer Version 5 Programming Guide


Select ItsoProGuideJUnit, enter the host name localhost, and click Finish. Click
Finish again to complete the Prepare wizard. Java source files have been
generated for this test case.

Note: The ItsoProGuideJUnit project has been modified extensively with new
library files. However, the reference to the ItsoProGuideJava project was
removed. Open the project properties and select the ItsoProGuideJava project
in the Java Build Path Projects page.

Next we add code to the generated test method.

Updating code of Java test case


Open the Java perspective, then expand ItsoProGuideJUnit ->
comptest.java.bankingtestcase1. Double-click MainBlock.java to open the test
case, then add the following code to testGetAccount:
try {
BankingTest banking = new BankingTest();
Account account = banking.getAccount("104-4001");
} catch (Exception ex) {
fail(ex.getMessage());
}

This code gets details about an account with account ID 104-4001. If an


exception occurs, then the test fails. Otherwise, it passes.

You have to add import statements for Banking and Account in your test class.
This can be done by right-clicking in the text editor and selecting Source ->
Organize Imports. Save the file.

Note: If you have the automatic build preference turned off, you must build
your project before executing it. To build the project, press CTRL-B.

Finally, return to the Component Test perspective, where we will run the
component test.

Note: For testing of any applications that use database access, make sure
that a user name and password to connect to the database is specified within
the application’s code. If not, during component testing, the user SYSTEM is
used by default. If this user name is not defined or does not have the proper
security properties, your tests may fail inexplicably.

Chapter 17. JUnit and component testing 593


Running a Java test case
In the Component Test perspective, in the Execution view, right-click Banking
Test Case 1 and then select Run from the context menu. This is shown in
Figure 17-17.

Figure 17-17 Run BankingTestCase 1 in the execution view

The run test case wizard opens, as shown in Figure 17-18. Here you give a name
to this execution.

Figure 17-18 Define the name of the execution

Click Next, then you select the host to run the tests on, as shown in Figure 17-19.
In our case, we will use the localhost. You could, however, execute tests on any
server that has the IBM Agent Controller installed. New hosts can be defined by
clicking New Host.

594 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 17-19 Define the host where the test case will be executed

Click Next, and you are taken to the final page of the wizard, which allows you to
describe the execution. After you have done that, click Finish to begin executing
the test case.

When the execution is running, you will see next to the execution in the
execution view. After it has completed, the running man disappears.

Report test case results


Upon completion of execution, you can generate reports to analyze the test
results. To do so, select a completed execution and select Report from the
context menu (Figure 17-20).

Figure 17-20 Report results of an execution

Chapter 17. JUnit and component testing 595


The new report wizard opens (Figure 17-21). Here you can select the type of
report to generate. Each report provides different details. In our case, we select
HTML Report - All (html).

Figure 17-21 Select report to generate

Select the Open browser check box and make sure the Open editor check box is
not selected. If you select both, the new report will open twice.

Click Next to proceed to the next page of the wizard, where you select the output
location of the report (Figure 17-22). In a larger application, you could organize
reports into folders of a project. In our case, we will simply generate the report in
the root folder of the ItsoProGuideJUnit project.

Figure 17-22 Define name and location of the report

596 WebSphere Studio Application Developer Version 5 Programming Guide


We enter BankingTestCaseReport as the report name, and will have the report
output to the ItsoProGuideJUnit location. Click Finish to complete the wizard
and open the new report.

Figure 17-23 shows the report in the Web browser. The top of the report shows
the execution statistics. The remainder of the report shows the details of each
step of the test execution in the info field, including:
򐂰 Starting the test case
򐂰 Connecting to the local host
򐂰 Verifying that an agent is available to connect to
򐂰 Connecting to the agent
򐂰 Starting the JUnit test cases
򐂰 Completing the JUnit test cases
򐂰 Reporting the results
򐂰 Completing the test.

The complete report is available as


BankingTestCaseReport.html, in
\sg24657\sampcode\test-junit

Figure 17-23 Banking test case report

Chapter 17. JUnit and component testing 597


Creating an HTTP test case
HTTP test cases use the HTTP scheduler to perform specific queries and HTTP
operations against a server. HTTP test cases can consist of the following:
򐂰 HTTP tasks (a request of some sort, with various options)
򐂰 Delays, which instruct the test case to wait a certain amount of time before
continuing
򐂰 Blocks, which organize the tasks and verification points into groups that can
be repeated
򐂰 Other HTTP test cases (pulled in by reference)

You can create HTTP tasks directly in the Component Test perspective, or you
can import a record of HTTP interactions in XML format.

We will now create a simple HTTP test case and create our own HTTP task to
call a servlet.

Note: This section assumes that you have an existing WebSphere Application
Server started and running on port 9080. Note that this is the default port for
test servers within Application Developer.

In the Component Test perspective, select Testcases in the Definition view and
select New -> Testcase from the context menu. In the new test case window,
select ItsoProGuideJUnit as the location and enter HTTPTestCase as the name of
the new test case (Figure 17-24).

Figure 17-24 Create new HTTP test case

598 WebSphere Studio Application Developer Version 5 Programming Guide


Select HTTP in the define attributes of the test case page, and click Finish to
complete the wizard (Figure 17-25).

Figure 17-25 Define attributes for new HTTP test case

The new test case has now been created and is open in the editor, as shown in
Figure 17-26.

Figure 17-26 HTTP test case

In outline view, right-click Main Block and select New -> Task -> HTTP from the
context menu. A new task has now been created for the test case.

Change the name to be FirstHTTPTest and the description to be whatever you


want for this task (Figure 17-27).

Chapter 17. JUnit and component testing 599


Figure 17-27 HTTP test case with new HTTP task

Select Design in the left column, then in the right part of the editor, specify the
following options:
򐂰 Request Method: GET
򐂰 Host Name: localhost
򐂰 Port: 9080
򐂰 Absolute Path: /

The result is shown in Figure 17-28.

Figure 17-28 Design of HTTP test case

600 WebSphere Studio Application Developer Version 5 Programming Guide


Click Execute request to test the request against the given host, port, and path. A
server must exist and be running on the specified port, otherwise an error
message is shown.

You will see a small message below the Execute request button:
Response: 404 - Content Type:html/text - Bytes:142

Change the path to /ItsoProGuideBasicWeb and click Execute request again.


This time the message is:
Response: 200 - Content Type:html/text - Bytes:1249

The first response (404) is the typical file not found message, the second
message indicates success.

Change the path back to / and save the test case. We want to see a failure.

Select the HTTPTestCase and Prepare from the context menu in the Definition
view. This generates the Java code for the test case. This wizard is explained in
detail in “Preparing a Java test case” on page 591.

Running an HTTP test case is done in the same way as running a Java test case,
except that the generated Java test case code does not need to be updated. For
more details about running the test case, see “Running a Java test case” on
page 594. The difference here is in the name of the test case.

Finally, reporting results from an HTTP test case is the same as a Java test case.
For more details, see “Report test case results” on page 595. The actual report is
slightly different, as shown in Figure 17-29.

To have a successful run, open the comptest.http.httptestcase1.MainBlock


class and change one line to:
firstHTTPTest.setAbsolutePath("/ItsoProGuideBasicWeb");

Rerun the test case as execution2 and generate the report again.

Chapter 17. JUnit and component testing 601


The complete report is available as
HTTPTestCaseReport.html, in
\sg24657\sampcode\test-junit

Figure 17-29 HTTP test case report

As you can see, there was a softFail due to a 404 error reported from the HTTP
server because no file existed at the root of the server. HTTP test cases read the
header of the HTTP response to determine whether tests pass or fail. In our
case, there was no file at the root of the localhost. If there had been, then the test
would have passed.

This concludes our introduction of HTTP test cases. This is a new and useful
feature of Application Developer that can be used to automate testing and
reporting of HTTP requests.

602 WebSphere Studio Application Developer Version 5 Programming Guide


Summary
Testing is a valuable part of software development. Application Developer
includes JUnit and component testing tools that speed up development of test
cases, therefore making them more easily accessible.

In this chapter, we covered the following topics:


򐂰 What is JUnit?
򐂰 Preparing for JUnit
򐂰 Creating the test case
򐂰 Running the test case
򐂰 Component testing

Chapter 17. JUnit and component testing 603


604 WebSphere Studio Application Developer Version 5 Programming Guide
Part 4

Part 4 Deploying and


profiling
applications
Part 4 discusses the deployment of enterprise applications, how to build
applications with Ant, and how to initiate a performance analysis by using the
profiling feature of Application Developer.

© Copyright IBM Corp. 2003. All rights reserved. 605


606 WebSphere Studio Application Developer Version 5 Programming Guide
18

Chapter 18. Deploying enterprise


applications
This chapter explains how to deploy an enterprise application to a WebSphere
Application Server Version 5.0.

In this chapter, we tell you how to:


򐂰 Export an enterprise application to an EAR file
򐂰 Set up a J2C authentication alias
򐂰 Create a data source using the authentication alias
򐂰 Deploy the application to the default server and start it
򐂰 Test the deployed Web applications

For detailed information about WebSphere Application Server, see the IBM
Redbook, IBM WebSphere Application Server Version 5.0 Handbook,
SG24-6195.

For detailed information about EJB development and deployment, see the IBM
Redbook, EJB 2.0 Development with WebSphere Studio Application Developer,
SG24-6819.

© Copyright IBM Corp. 2003. All rights reserved. 607


Enterprise application deployment
Deployment is an important topic that should be considered by every
development project. Unfortunately, this is not always the case. Developers often
develop applications without thinking too much about the environment in which
they will be deployed. Once handed over to the IT Department, the applications
may not perform optimally or may, due to poor packaging, become a
maintenance nightmare with interdependencies between modules, version
incompatibility, and classpath problems.

Although Application Developer 5.0 has excellent support for testing applications
in its built-in test environment, it is always good practice to export your
application and deploy and test it on the target environment as early as possible
in the development cycle. More than one project has had unpleasant surprises
when developing large applications by only using the built-in test environment for
testing, and then attempted to deploy it to the target environment—only to find
out, too late, that it failed there.

Importing the enterprise application


In this example we use the ItsoProGuide enterprise application that we
developed so far in the previous chapters.

This enterprise application has an EJB module, several Web modules, and a
utility JAR (a Java project).

You can use your own ItsoProGuide project, or import the EAR file from the
sample code associated with this redbook (see Appendix C, “Additional material”
on page 809).

To import the enterprise application follow the instructions in “Installing the


ItsoProGuide.ear file” on page 812. Make sure that the classpath is fixed for the
projects that show errors.

Working with deployment descriptors


Application Developer provides editors to customize the deployment descriptors
for both EJB modules and Web modules. This more or less makes the
WebSphere Application Assembly Tool (AAT) that ships with WebSphere
Application Server redundant. However, if you were to package applications for
deployment to WebSphere Application Server and you did not use Application
Developer, you would need the AAT to customize the deployment descriptors.

608 WebSphere Studio Application Developer Version 5 Programming Guide


Note: At the time of writing, IBM has released a preview of a tool called the
Assembly Toolkit for WebSphere Application Server. This tool is based on the
Eclipse platform and provides the functionality of the Application Assembly
Tool (application packaging and deployment descriptor editing) but also adds
functionality like database meet-in-the-middle mapping. We do not describe
this tool here because we can do the same with Application Developer.

EJB deployment descriptor


EJB modules are contained in EJB JAR files. The important deployment
information for a WebSphere Application Server that you have to configure is
contained in the WebSphere Bindings sections of the deployment descriptor
editor. The other information should have been provided by the application
developers.

Before exporting the EAR file, we verify that the database mapping deployment
information for the EJBs in our project is correct:
򐂰 Open the deployment descriptor editor for the ItsoProGuideEJB project by
expanding the EJB Modules in the J2EE Perspective, J2EE Hierarchy view
and double-clicking the ItsoProGuideEJB module. This brings up the window
shown in Figure 18-1.

Figure 18-1 EJB Deployment Descriptor editor

Chapter 18. Deploying enterprise applications 609


The editor has the following tabs (only the most important tabs that have to do
with deployment information are listed):
򐂰 Overview—Backend ID and JNDI - CMP Factory Connection Binding
򐂰 Beans—JNDI name for each bean and possible WebSphere extensions such
as caching
򐂰 Assembly Descriptor—Definition of security roles, method permissions, and
container transactions
򐂰 References—JNDI name for each of the references
򐂰 Access—WebSphere extensions for security, access intent, and isolation
level

Select the Overview tab and scroll to the bottom of the page as shown in
Figure 18-2.

Figure 18-2 Specifying database mapping information

򐂰 Verify that DB2UDBNT_V72_1 is selected as the Backend ID.


򐂰 Verify that the JNDI name for the data source is jdbc/ejbbank and that
Per_Connection_Factory is used as Container authorization type.
Per_Connection_Factory uses authentication per module. The other choice,
Container, uses authentication by the EJB container.
򐂰 Save the deployment description information by pressing Ctrl-S.

Note: There is a graphical bug in Application Developer 5.0 that sometimes


truncates the first character(s) of the drop-down fields in this editor.

We will not use any of the EJB security functions in our examples.

610 WebSphere Studio Application Developer Version 5 Programming Guide


Web deployment descriptor
Web modules are contained in WAR files and are described by Web deployment
descriptors. Just as for the case with the EJB deployment descriptors, the
application developers should have provided most of the information necessary.

Before exporting the EAR file, we verify that the deployment information is
suitable for a production system.
򐂰 Open the Web deployment descriptor editor by expanding the Web Modules
in the J2EE Hierarchy view and double-clicking the ItsoProGuideBasicWeb
module (Figure 18-3).

Figure 18-3 Web Deployment Descriptor editor

Chapter 18. Deploying enterprise applications 611


The editor has the following tabs (only the most important tabs are listed):
򐂰 Overview—This page is a summary of the information on the other pages.
You can see the servlets and JSPs, filters, listeners, pages, and references.
The only WebSphere deployment information is the virtual host name
(default_host) at the bottom of the dialog (not visible in Figure 18-3).
򐂰 Servlets—These are servlet mappings and load-on-startup settings.
򐂰 References—These are the JNDI names for each of the references (our
application references the BankEJB session bean).
򐂰 Pages—These are welcome pages when the Web application is invoked
without specifying a specific Web page.
򐂰 Extensions—These are WebSphere extensions such as reloading, JSP
precompile, file serving, and caching (Figure 18-4).

Figure 18-4 Specifying WebSphere extensions

򐂰 Deselect the Reloading enabled option. If selected, this causes WebSphere


Application Server to scan the classpath for the application at regular intervals
to check for modified classes and reload them. This may be fine for a
development test system, but should be avoided in production, as it
consumes unnecessary CPU cycles and may be a potential security risk if
someone manages to introduce incorrect classes in the file system.
Deployment of new versions must be done in a controlled manner.

612 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Verify that the File serving enabled option is selected. This tells WebSphere
Application Server that it should not only serve dynamic content, such as
servlets and JSPs, but also static content like HTML pages and images. In
our simple environment we want to use this feature as it makes deployment a
little easier. However, in a production environment you may want a separate
HTTP server (perhaps on a remote machine) to serve the static content and
this option should then be deselected.
򐂰 Deselect the Serve servlets by classname option. If selected it means that a
user can invoke servlets using their class name (for example
itso.basocweb.control.ListAccounts).
This can be a potential security risk if users manage to find out the class
names and access servlets that were not meant to be accessed directly. If this
option is deselected only servlets that are explicitly named on the Servlets tab
and mapped to a URL are accessible.
򐂰 Select the Precompile JSPs option to have all JSPs compiled during
application startup.
򐂰 Save the deployment description information by pressing Ctrl-S.

Application client module deployment descriptor


An application client module is contained in a client JAR file. The WebSphere
specific options in the deployment descriptor are:
򐂰 References—JNDI name for each of the references (Figure 18-5)

Figure 18-5 Application client deployment descriptor

We provide an application client module called ItsoProGuideJavaClient.

Chapter 18. Deploying enterprise applications 613


Building an application client module
Our application client module (ItsoProGuideJavaClient) contains one program,
CustomerListingDS. This program is basically a copy of the CustomerListing
program developed in Chapter 5, “Developing Java applications” (see source
listing in Figure 5-10 on page 102).

The difference in the application client module is that we use a data source to
connect to the database:
protected static Connection connect() {
Connection con = null;
try {
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
javax.sql.DataSource ds =
(javax.sql.DataSource)ctx.lookup("java:comp/env/jdbc/mybank");
con = ds.getConnection();
} catch (javax.naming.NamingException e) {
System.err.println("Naming-Exception: " + e.getMessage());
} catch (java.sql.SQLException e) {
System.err.println("SQL-Exception: " + e.getMessage());
}
return con;
}

Here are some short instructions on how we built the application client module:
򐂰 Create a new project of type J2EE -> Application Client Project. Enter a name
of ItsoProGuideJavaClient and use the existing ItsoProGuide enterprise
application.
򐂰 Create the class itso.javadb.CustomerListingDS and use the source in:
\sg246957\sampcode\deploy-app\client\CustomerListingDS
򐂰 Open the deployment descriptor and on the References page define a
resource environment reference named java:comp/env/jdbc/mybank,
pointing to our jdbc/ejbbank data source (as shown in Figure 18-5).

Note: You have to use a resource environment reference. Defining a


resource reference in Application Developer does not work when running
the program. Resource references can currently only be defined using the
Application Client Resource Configuration Tool (clientConfig.bat) of
WebSphere Application Server outside of Application Developer to update
the client deployment descriptor.

򐂰 Define the CustomerListingDS program as the main application of the module


(Figure 18-6). Click Edit to locate the main class.

614 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 18-6 Defining the main program

򐂰 To test the application you have to run the program in a WebSphere


application client container.
Start the ItsoServer (it defines the data source), then create a launch
configuration as explained in “Running your programs” on page 103.
However, this time create a WebSphere v5 Application Client launch
configuration (Figure 18-7). On the Classpath tab, click Advanced, then Add
Variables, and select the DB2JAVA variable.

DB2JAVA

Figure 18-7 Launch configuration for a J2EE application client

򐂰 When you run the program, you can see the start of the client container and
the binding of the JDBC reference in the Console view. The database records
are displayed as the result of the program execution.

Chapter 18. Deploying enterprise applications 615


Exporting an enterprise application

Note: You may want to make the changes to the applications as noted in
“Changing the applications to run on a remote server” on page 538 before
exporting.

After the deployment descriptors have been customized for our environment, the
enterprise application can be exported to an EAR file:
򐂰 In the J2EE Perspective, J2EE Hierarchy view expand Enterprise Applications
and select the ItsoProGuide project. Then select Export EAR File from its
context menu. The EAR Export dialog shown in Figure 18-8 is displayed.

Figure 18-8 Exporting an EAR file

򐂰 Enter the EAR filename to export the resources to. A possible location is the
installableApps directory of the WebSphere Application Server, but you can
export to anywhere in the file system.
򐂰 Make sure that the three options are unchecked. Because the EAR file will be
used in a production system we do not want to include the source files or the
Application Developer meta-data.
򐂰 Click Finish to export the EAR file.

The next step is to prepare our WebSphere Application Server environment.

616 WebSphere Studio Application Developer Version 5 Programming Guide


Configuring WebSphere Application Server
In this section we configure WebSphere Application Server 5.0 to install and run
the sample application.

This consists of the following tasks:


򐂰 Configure the JDBC driver
򐂰 Set up a data source
򐂰 Configure a J2C authentication alias to access the database
򐂰 Install the EAR file
򐂰 Start the application

The administrative actions are performed using the WebSphere Application


Server 5.0 administrative console.

Start the server and the administrative console


To configure the server we use the administrative console:
򐂰 Start the WebSphere Application Server 5.0 server (from the program group,
from First Steps, or as a service).
򐂰 Start the administrative console (from the program group or from First Steps).
򐂰 Login with your normal user ID (Figure 18-9).

Figure 18-9 Administrative Console Login

Chapter 18. Deploying enterprise applications 617


򐂰 Select Servers and Applications to expand the tree (Figure 18-10). Select
Application Servers and you can see the default server (server1). Select
Enterprise Applications and you can see the sample applications.

Figure 18-10 Administrative Console

Configuring a server (optional)


With WebSphere Application Server Network Deployment we suggest to
configure a separate server and not use the default server. With the base
WebSphere Application Server we use the default server (server1) for our
sample application.

Configuring a JDBC driver and data source


In this section we configure a JDBC driver for DB2 and the data source for the
EJBBANK database.

JDBC driver path


򐂰 Select Environment (left side) and Managed WebSphere Variables.
򐂰 Select DB2 JDBC DRIVER PATH.
򐂰 Verify or enter the directory of the db2java.zip file (c:\SQLLIB\java).
򐂰 Click OK.

618 WebSphere Studio Application Developer Version 5 Programming Guide


JDBC driver
򐂰 Select Resources (left side) and select JDBC Providers.
򐂰 Select Node (should be preselected)
򐂰 Click New (under JDBC Providers):
– Select DB2 JDBC Provider from the pull-down and click Apply.
– All the defaults should be fine. Check that the implementation class is
COM.ibm.db2.jdbc.DB2ConnectionPoolDataSource. Note that the classpath
entry points to ${DB2_JDBC_DRIVER_PATH}/db2java.zip (Figure 18-11).
– Click Apply.

Figure 18-11 Defining a JDBC provider

Data source
򐂰 Under Additional Properties select Data Sources.
– Click New (Figure 18-12).
– Enter EJBBANK as name and jdbc/ejbbank as JNDI name (to match what
we defined in the EJB deployment descriptor).

Chapter 18. Deploying enterprise applications 619


– Select Use this Data Source in container-managed persistence (CMP).
– The data source helper class should be filled in as
com.ibm.websphere.rsadapter.DB2DataStoreHelper.
– Click Apply.

Figure 18-12 Defining the data source for the EJBBANK database

򐂰 Under Additional Properties select Custom Properties, then select


databaseName, enter EJBBANK as value and click OK.
򐂰 Go back to the data source (select EJBBANK at the top of the page). Under
related Items select J2C Authentication Data Entries, then click New
(Figure 18-13):
– Enter DB2user as alias.
– Enter a valid user ID and password, for example what was used to install
DB2.
– Click OK.
– The new alias appears in the list, prefixed with the node name.

620 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 18-13 Defining an authentication alias

򐂰 Go back to the data source (select EJBBANK at the top of the page):
– For component- and container-managed authentication alias, select the
{node}/DB2user from the pull-down and click OK (Figure 18-14).

Figure 18-14 Defining container authentication for the data source

Note: Due to Web browser caching, the alias may not appear in the pull-down
list. If this happens, refresh your Web browser by pressing F5 and then
navigate to this entry again.

򐂰 If you select Security (left side) and JAAS Configuration you can find the new
alias by selecting J2C Authentication Data.

Save the configuration


Save the configuration. There should be no problems.

Chapter 18. Deploying enterprise applications 621


Installing an enterprise application
To install an enterprise application from an EAR file:
򐂰 Select Applications and Install New Application.
򐂰 For the local path, click Browse and locate the EAR file that you exported
from Application Developer (Figure 18-15):
c:\ItsoProGuide.ear
d:\WebSphere\AppServer\installableApps\ItsoProGuide.ear
Click Next.

c:\ItsoProGuide.ear

Figure 18-15 Enterprise application installation

򐂰 On the panel, Preparing for the application installation, all the defaults should
be fine:
– You do not want to overwrite existing bindings, everything was configured
in Application Developer
– You can choose the virtual host (instead of default_host)
Click Next.

Installation process steps


Installation of our enterprise application is a multi-step process, in our case,
9 steps (the actual number of steps vary depending on the content and
requirements of your application).

Unless otherwise noted, review the options and then click Next for each step.
Because we configured all the deployment information in Application Developer
there is almost no need to change the options.

622 WebSphere Studio Application Developer Version 5 Programming Guide


1. Provide options to perform the installation (Figure 18-16):

Figure 18-16 Enterprise application installation: step 1

– You may want to select Pre-compile JSP (although we set this in our Web
applications it is not picked up as a default).
– Do not select Deploy EJBs; deployment code was generated in
Application Developer.
2. Provide JNDI Names for Beans (Figure 18-17).
All the JDNI names for our entity and sessions beans have been set.

Figure 18-17 Enterprise application installation: step 2

3. Provide default data source mapping for modules containing EJB 2.0 entity
beans (Figure 18-18).
We configured the jdbc/ejbbank data source previously.

Chapter 18. Deploying enterprise applications 623


Figure 18-18 Enterprise application installation: step 3

4. Map data sources for all EJB 2.0 CMP beans (Figure 18-19).

Figure 18-19 Enterprise application installation: step 4

5. Map EJB references to beans (Figure 18-20).

Figure 18-20 Enterprise application installation: step 5 (abbreviated)

624 WebSphere Studio Application Developer Version 5 Programming Guide


6. Map virtual hosts for Web modules (Figure 18-21).

Figure 18-21 Enterprise application installation: step 6

7. Map modules to application servers (Figure 18-22).

Figure 18-22 Enterprise application installation: step 7

8. Ensure that all unprotected EJB 2.0 methods have the correct level of
protection (Figure 18-23).

Chapter 18. Deploying enterprise applications 625


Figure 18-23 Enterprise application installation: step 8

9. A Summary report is produced (Figure 18-24).

Figure 18-24 Enterprise application installation: step 9

Click Finish and be patient. Messages are displayed in the console:


Check the SystemOut.log on the Deployment Manager or Server where the
application is deployed for specific information about the EJB Deploy
process as it occurs.

ADMA5009I: Application archive extracted at


C:\DOCUME~1\FUNDY\LOCALS~1\Temp\app_f4fa315b45\ear

ADMA5003I: Jsps in wars ItsoProGuideStoredProcWeb.war,


ItsoProGuideWebServ.war, ItsoProGuideWebServClient.war,
ItsoProGuideStrutsWeb.war, ItsoProGuideBasicWeb.war,

626 WebSphere Studio Application Developer Version 5 Programming Guide


ItsoProGuideXmlWeb.war, ItsoProGuideDataBaseWeb.war
compiled successfully

ADMA5005I: Application ItsoProGuide configured in WebSphere repository

ADMA5001I: Application binaries saved in


D:\WebSphere\AppServer\wstemp\UELI\workspace\cells\FUNDY\applications\
ItsoProGuide.ear\ItsoProGuide.ear

ADMA5011I: Cleanup of temp dir for app ItsoProGuide done.

ADMA5013I: Application ItsoProGuide installed successfully.

If you want to start the application, you must first save changes to the
master configuration.

When installed, click Save to master configuration to save the installed


application. You can find the installed application in:
c:\WebSphere\AppServer\installedApps (under the node)

Regenerating HTTP Server plug-in configuration


When the application is installed we have to update the IBM HTTP Server’s
plug-in configuration to make it aware of the new URLs that the application uses:
򐂰 Select Environment (left side) and Update Web Server Plugin.
򐂰 Click OK to regenerate the plugin.
򐂰 Either wait until the IBM HTTP Server has picked up the new configuration
(default is every 60 seconds) or restart the IBM HTTP Server.

Starting the enterprise application


You can start the ItsoProGuide enterprise application by expanding Applications
and selecting Enterprise Applications and then select the application and click
Start.

This may work, dependent on the modifications you made to the configuration.
Sometimes it is necessary to stop and start the server:
򐂰 Use the startServer.bat and stopServer.bat scripts in
c:\WebSphere\AppServer\bin
򐂰 Use the icons in the program folder or in First Steps

Chapter 18. Deploying enterprise applications 627


Testing the applications
You can test the application using the built-in HTTP server or the stand-alone
HTTP server.

Running the Web applications


Open a browser and enter these URLs:
http://hostname:9080/ItsoProGuideBasicWeb <=== from another machine

http://localhost:9080/ItsoProGuideBasicWeb <=== from the same machine

http://localhost:9080/ItsoProGuideStrutsWeb

http://localhost:9080/ItsoProGuideDataBaseWeb/ListCreditsInputForm.html
enter type: C or D, and a partial last name: %i%
http://localhost:9080/ItsoProGuideDataBaseWeb/TestDBBeans.jsp

http://localhost:9080/ItsoProGuideStoredProcWeb/RunStoredProcedure.jsp
http://localhost:9080/ItsoProGuideStoredProcWeb/RunGetCustomerBean.jsp
http://localhost:9080/ItsoProGuideStoredProcWeb/RunTransfer.jsp
Note: the stored procedures must be installed on the server machine

http://localhost:9080/ItsoProGuideWebServ/RunBanking.jsp

http://localhost:9080/ItsoProGuideWebServClient/TestBankingWebService.jsp

If you have regenerated the Web server plugin, start the HTTP server and you
can test the applications using URLs without the 9080 port:
http://hostname/ItsoProGuideBasicWeb

Running the application client module


To run the application client module, use these commands:
cd \WebSphere\AppServer\bin where WebSphere is installed

launchClient.bat d:\WebSphere\AppServer\installableapps\ItsoProGuide.ear
-CCclasspath=d:\SQLLIB\java\db2java.zip

To run the application on another machine you must have the WebSphere client
installed. The command would be:
launchClient.bat d:\WebSphere\AppServer\installableapps\ItsoProGuide.ear
-CCclasspath=d:\SQLLIB\java\db2java.zip
-CCBootstrapHost=hostname

Note that you must provide the DB2 JDBC classes in the classpath.

628 WebSphere Studio Application Developer Version 5 Programming Guide


Remote debugging
With the enterprise application installed on a real WebSphere Application Server
you can now perform remote debugging as described in “Debugging on a remote
WebSphere Application Server” on page 566.

Command line tools


Command line tools can greatly speedup deployment of applications and other
WebSphere configuration tasks.

We only cover a small subset of the tools; those which seem useful to an
application developer and tester. For a complete discussion of the tools, refer to
the WebSphere documentation.

Command line tools come in two sets:


򐂰 Batch commands (.bat files in WebSphere\AppServer\bin)
򐂰 Scripting tool (started with the wsadmin.bat file)

Batch commands
Here is a list of some of the commands:
򐂰 assembly—runs the Application Assembly Tool (AAT)
򐂰 clientConfig— runs the Application Client Configuration Tool
򐂰 backupConfig—creates a ZIP file of all the configuration information
򐂰 restoreConfig—restores a configuration from a backup file
򐂰 dumpNameSpace—lists all the JNDI names from the name server
򐂰 ejbDeploy—generates deployed code for an EJB JAR file
򐂰 firstSteps—launches the First Steps menu
򐂰 GenPluginCfg—generates the HTTP plugin
򐂰 launchClient—run an application client module
򐂰 JspBatchCompiler—compiles the JSPs for an application server
򐂰 startServer—starts a server
򐂰 stopServer—stops a server
򐂰 serverStatus—report if a server is running
򐂰 setupCmdLine—sets the classpath for most of the other tools
򐂰 wsadmin—starts the administration scripting tool

Chapter 18. Deploying enterprise applications 629


Scripting tool: wsadmin
WebSphere Application Server 5.0 provides a scripting tool, wsadmin, with which
many of the configuration functions can be run in batch. For a description of all
the functions, refer to the WebSphere documentation.

Wsadmin can be run with a single command, or you can interact with the tool:
򐂰 Single command example:
wsadmin -c "$AdminApp list"
A single command is passed to wsadmin using the -c option. The $AdminApp
list command lists all the installed applications.
򐂰 To start wsadmin in interactive mode, enter wsadmin:
D:\WebSphere\AppServer\bin>wsadmin
WASX7209I: Connected to process "server1" on node a23wph18 using SOAP
connector; The type of process is: UnManagedProcess
WASX7029I: For help, enter: "$Help help"
wsadmin>

Example commands
Once the interactive mode has started, you can enter commands, such as:
$AdminApp list
$AdminApp install c:/ItsoProGuide.ear
$AdminConfig save

Some commands work with objects that you have to retrieve first. For example, to
regenerate the HTTP server plugin:
set pluginGen [$AdminControl completeObjectName type=PluginCfgGenerator,*]

===> output:
WebSphere:platform=common,cell=a23wph18,version=5.0,name=PluginCfgGenera
tor,mbeanIdentifier=PluginCfgGenerator,type=PluginCfgGenerator,
node=a23wph18,process=server1

$AdminControl invoke $pluginGen generate "c:/WebSphere/AppServer


c:/WebSphere/AppServer/config a23wph18 null null plugin-cfg.xml"

===> no output

Stopping and starting an enterprise application:


set appManager [$AdminControl queryNames cell=a23wph18,node=a23wph18,
type=ApplicationManager,process=server1,*]
$AdminControl invoke $appManager stopApplication ItsoProGuide
$AdminControl invoke $appManager startApplication ItsoProGuide

630 WebSphere Studio Application Developer Version 5 Programming Guide


Example script
You can also write script files with multiple commands and run the file using:
wsadmin -f RunningApplications.script

The sample script in Figure 18-25 can be found in the Information Center. It lists
all the applications running on all the servers on all the nodes.

# retrieve all cells


set cells [$AdminConfig list Cell]
foreach cell $cells {
# retrieve nodes for each cell
set nodes [$AdminConfig list Node $cell]
foreach node $nodes {
set cname [$AdminConfig showAttribute $cell name]
set nname [$AdminConfig showAttribute $node name]
# retrieve servers for each node
set servs [$AdminControl queryNames type=Server,cell=$cname,node=$nname,*]
puts "Number of running servers on node $nname: [llength $servs]"
foreach server $servs {
set sname [$AdminControl getAttribute $server name]
set ptype [$AdminControl getAttribute $server processType]
set pid [$AdminControl getAttribute $server pid]
set state [$AdminControl getAttribute $server state]
set jvm [$AdminControl queryNames
type=JVM,cell=$cname,node=$nname,process=$sname,*]
set osname [$AdminControl invoke $jvm getProperty os.name]
puts " $sname ($ptype) has pid $pid; state: $state; on $osname"
# retrieve applications
set apps [$AdminControl queryNames
type=Application,cell=$cname,node=$nname,process=$sname,*]
puts " Number of applications running on $sname: [llength $apps]"
foreach app $apps {
set aname [$AdminControl getAttribute $app name]
puts " $aname"
}
puts "----------------------------------------------------"
puts ""
}
}
}

Figure 18-25 Sample wsadmin script to list all applications

Chapter 18. Deploying enterprise applications 631


Classpath
All the JAR files in the WebSphere lib folder are automatically in the classpath of
the WebSphere Application Server. If your enterprise application uses any
external JAR files that are not in the lib folder or in the system classpath, then
they must be added to the classpath. One way to accomplish this is by copying
the JAR files into the WebSphere lib folder.

For example, if you create a Web service from an SQL statement (we did not do
this in this document, but it is possible), then the Web Services Object Runtime
Framework (WORF) is used at runtime. In this case you have to add the WORF
runtime classes to the classpath. You can find the worf.jar file in:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.webservice_5.0.1\runtime

Summary
In this chapter we described the basic steps for setting the deployment
descriptors and exporting an application from Application Developer and then
installing it in WebSphere Application Server, including the configuration that is
required in the server.

Note that WebSphere Application Server has many performance and tuning
options that we do not cover in this redbook.

632 WebSphere Studio Application Developer Version 5 Programming Guide


19

Chapter 19. Building applications with


Ant
In this chapter we show how to use the Ant tool to build your projects and perform
some special customizations in order to generate the output that you want.

Traditionally, building applications have been performed by using shell scripts or


batch files in UNIX® or Windows environments, or by using tools such as make.
While these approaches are still valid, developing Java applications—especially
in a heterogeneous environment—introduces new challenges. A particular
limitation with traditional tools is the close-coupling to a particular operating
system. With Ant you can overcome these limitations and perform the build
process in a standardized fashion regardless of platform.

© Copyright IBM Corp. 2003. All rights reserved. 633


What is Ant?
Ant is a Java-based, platform independent, open source build tool. It was
formerly a sub-project in the Apache Jakarta project, but in November 2002, it
was migrated to an Apache top-level project. Ant’s function is similar to the make
tool but, at least according to Ant’s Web page, without its wrinkles. As it is
Java-based and does not make use of any OS-specific functions, it is platform
independent, allowing you to build your projects using the same build script on
any Java-enabled platform.

To control what operations Ant should perform during your build, you supply it an
XML-based script file. This file not only defines what operations to perform but
also in which order they should be performed and any dependencies between
them.

Ant comes with a large number of built-in tasks sufficient to perform many
common build operations. However, if the tasks included are not sufficient, you
also have the ability to extend Ant’s functionality by using Java to develop your
own specialized tasks. These tasks can then be plugged into Ant.

Not only can Ant be used to build your applications, but it can also be used for
many other operations such as retrieving source files from a version control
system, storing the result back in the version control system, transferring the
build output to other machines, deploying the applications, generating Javadoc,
and sending messages, for example, when a build is finished.

To find out more about Ant, visit the Ant Web site at:
http://ant.apache.org/

This chapter provides a basic outline of the features and capabilities of Ant. For
complete information you should consult the Ant documentation included in the
Ant distribution or available on the Internet at:
http://ant.apache.org/manual/index.html

Note: Application Developer includes Ant version 1.4.1.

634 WebSphere Studio Application Developer Version 5 Programming Guide


Sample demo project and application
To show you the basic concepts of Ant we wrote a really simple Java application,
HelloAnt. This is simply a Hello World program that prints a message to stdout.

We created a new Java project for this that we called ItsoProGuideAnt. In this
project we created a Java package called itso.ant.hello and a class called
HelloAnt. Since these steps are basic Application Developer tasks and the
application does nothing but a simple System.out.println("Hello Ant") we do
not show them here. The source code is available in:
\sg246957\sampcode\deploy-ant\simple

Ant build files


Ant uses XML build files to define what operations must be performed to build a
project. These are the main components of a build file:
򐂰 project—A build file contains build information for a single project. It may
contain one or more targets.
򐂰 target—A target describes the tasks that must be performed to satisfy a goal,
for example compiling source code into class files may be one target, and
packaging the class files into a JAR file may be another target. Targets may
depend upon other targets, for example the class files must be up to date
before you can create the JAR file. Ant resolves these dependencies.
򐂰 task—A task is a single step that must be performed to satisfy a target. Tasks
are implemented as Java classes that are invoked by Ant, passing
parameters defined as attributes in the XML. Ant provides a set of standard
tasks (core tasks), a set of optional tasks, and an API which allows you to
write your own tasks.
򐂰 property—A property has a name and a value. Properties are essentially
variables that can be passed to tasks through task attributes. Property values
can be set inside a build file, or obtained externally from a properties file or
from the command line. A property is referenced by enclosing the property
name inside ${}, for example ${basedir}.
򐂰 path—A path is a set of directories or files. Paths can be defined once and
referred to multiple times, easing the development and maintenance of build
files. For example, a Java compilation task may use a path reference to
determine the classpath to use.

Chapter 19. Building applications with Ant 635


Ant tasks
A comprehensive set of built-in tasks are supplied with the Ant distribution. The
tasks that we use in this example are described below:
delete Deletes files and directories
echo Outputs messages
jar Creates Java archive files
javac Compiles Java source
mkdir Creates directories
tstamp Sets properties containing date and time information

Creating a simple build file


We created a simple build file that compiles the Java source for our HelloAnt
application and generates a JAR file with the result. The build file is called
build.xml, which is the default name assumed by Ant if no build file name is
supplied. Our simple build file has the following targets:
init Performs build initialization tasks—all other targets depend upon this
target
compile Compiles Java source into class files
dist Creates the deliverable JAR for the module—depends upon the
compile target
clean Removes all generated files—used to force a full build

Each Ant build file may have a default target. This target is executed if Ant is
invoked on a build file and no target is supplied as a parameter. In our case the
default target is dist. The dependencies between the targets are illustrated in
Figure 19-1.

636 WebSphere Studio Application Developer Version 5 Programming Guide


dist clean

depends on
compile

init
Figure 19-1 Ant example: dependencies

To create the simple build file, do the following:


򐂰 Select the ItsoProGuideAnt project and select New -> File from its context
menu.
򐂰 Enter build.xml as the filename and click Finish (Figure 19-2).

Figure 19-2 Creating a build.xml file

򐂰 Then paste the text in Figure 19-3 into the file.

Chapter 19. Building applications with Ant 637


<?xml version="1.0" encoding="UTF-8"?>
<project name="HelloAnt" default="dist" basedir=".">

<!-- set global properties for this build -->


<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<property name="source" value="."/>
<property name="build" value="build"/>
<property name="disributet" value="dist"/>
<property name="outFile" value="helloant"/>

<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>

<target name="compile" depends="init">


<!-- Compile the java code from ${source} into ${build} -->
<javac srcdir="${source}" destdir="${build}"/>
</target>

<target name="dist" depends="compile">


<!-- Create the distribution directory -->
<mkdir dir="${distribute}/lib"/>

<!-- Put everything in ${build} into the output JAR file -->
<!-- Add a timestamp to the output filename as well -->
<jar jarfile="${distribute}/lib/${outFile}-${DSTAMP}.jar" basedir="${build}"/>
</target>

<target name="clean">
<!-- Delete the ${build} and ${distribute} directory trees -->
<delete dir="${build}"/>
<delete dir="${distribute}"/>
</target>

</project>

Figure 19-3 build.xml file

We will now walk you through the different sections of this file, explaining each of
them.

Project definition
The project tag in the build.xml file defines the project name and the default
target. The project name is an arbitrary name, it is not related to any project
name in your Application Developer workspace.

638 WebSphere Studio Application Developer Version 5 Programming Guide


The project tag also sets the working directory for the Ant script. All references to
directories throughout the script file are based on this directory. A dot (".") means
to use the current directory which, in Application Developer, is the directory
where the build.xml file resides.

Global properties
Properties that will be referenced throughout the whole script file can be placed
at the beginning of the Ant script. Here we define the property build.compiler
that tells the javac command what compiler to use. We will tell it to use the
Eclipse compiler.

We also define the names for the source directory, the build directory, and the
distribute directory. The source directory is where the Java source files reside.
The build directory is where the class files end up, and the distribute directory is
where the resulting JAR file is placed:
򐂰 We define the source property as ".", which means it is the same directory as
the base directory specified in the project definition above.
򐂰 The build and distribute directories will be created as build and dist
directories.

Properties can be set as shown below, but Ant can also read properties from
standard Java properties files or use parameters passed as arguments on the
command line:
<!-- set global properties for this build -->
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<property name="source" value="."/>
<property name="build" value="build"/>
<property name="distribute" value="dist"/>
<property name="outFile" value="helloant"/>

Build targets
The build file contains four build targets: init, compile, dist and clean.

Initialization target
The first target we describe is the init target. All other targets (except clean) in
the build file depend upon this target. In the init target we execute the tstamp
task to set up properties that include timestamp information. These properties
are then available throughout the whole build. We also create a build directory
defined by the build property.

Chapter 19. Building applications with Ant 639


<target name="init">
<!-- Create the time stamp -->
<tstamp/>
<!-- Create the build directory structure used by compile -->
<mkdir dir="${build}"/>
</target>

Compilation target
The compile target compiles the Java source files in the source directory and
places the resulting class files in the build directory.
<target name="compile" depends="init">
<!-- Compile the java code from ${source} into ${build} -->
<javac srcdir="${source}" destdir="${build}"/>
</target>

With these parameters, if the compiled code in the build directory is up-to-date
(each class file has a timestamp later than the corresponding Java file in the
source directory), the source will not be recompiled.

Distribution target
The distribution target creates a JAR file that contains the compiled class files
from the build directory and places it in the lib directory under the dist directory.
Because the distribution target depends on the compile target, the compile target
must have executed successfully before the distribution target is run.
<target name="dist" depends="compile">
<!-- Create the distribution directory -->
<mkdir dir="${distribute}/lib"/>

<!-- Put everything in ${build} into the output JAR file -->
<!-- We add a time stamp to the filename as well -->
<jar jarfile="${distribute}/lib/${outFile}-${DSTAMP}.jar" basedir="${build}"/>
</target>

Cleanup target
The last of our standard targets is the cleanup target. This target removes the
build and distribute directories which means that a full recompile is always
performed if this target has been executed.
<target name="clean">
<!-- Delete the ${build} and ${distribute} directory trees -->
<delete dir="${build}"/>
<delete dir="${distribute}"/>
</target>

Note that our build.xml file does not call for this target to be executed. It has to
be specified when running Ant.

640 WebSphere Studio Application Developer Version 5 Programming Guide


Running Ant
Ant is a built-in function in Application Developer. You can launch it from the
context menu of any XML file although it will run successfully only on valid Ant
XML build script files. When launching an Ant script, you are given the option to
select which targets to run and if you want to view the output in a special Log
Console window.

To run our build script, we select the build.xml file, open its context menu and
select Run Ant as shown in Figure 19-4.

Figure 19-4 Launching Ant

Application Developer displays the Run Ant dialog (Figure 19-5), which allows
you to select the targets to run.

The default target specified in the build file is already selected as one target to
run. You can check, in sequence, which ones are to be executed, and the
execution sequence is shown next to each target.

Note that because dist depends on compile, even if you only select dist, the
compile target is executed as well.

Chapter 19. Building applications with Ant 641


Figure 19-5 Selecting Ant targets to run

In the Arguments field, you can supply additional parameters to Ant, but we leave
that empty for now. If Show execution log in console is selected, messages from
Ant are displayed in the Log Console. If this is not selected, you will not see any
output from Ant, so make sure it is checked for now. Then click Finish to run Ant.

When Ant is running, you see the output in the Log Console (Figure 19-6).

Figure 19-6 Log Console

The Log Console view opens automatically when running Ant, but if you want to
open it manually, select Window -> Show view -> Log Console.

The Log Console shows that Ant has created the build directory, compiled the
source files, created the dist\lib directory, and generated a JAR file.

642 WebSphere Studio Application Developer Version 5 Programming Guide


Where is the output?
The Package Explorer view does not show any of the generated files. Application
Developer does not know automatically that Ant generated files in the project.

Select the ItsoProGuideAnt project and Refresh (context). Now you can see the
JAR files in the Package Explorer view. To see the class files you have to open
the Navigator view (Figure 19-7).

Figure 19-7 Ant generated files

Rerunning Ant
If you launch Ant again with the same target selected, you will see the following
in the Log Console.

Figure 19-8 Log Console on second run

As you can see, Ant did not do anything at all, because the build and dist\lib
directories were already created and the class files in the build directory were
already up-to-date.

Chapter 19. Building applications with Ant 643


Forced build
To generate a complete build, select the clean target as the first target and the
dist target as the second target to run. You have to de-select dist, select clean,
and then select dist again to get the execution order right (Figure 19-9).

Figure 19-9 Launching Ant to generate complete build

Classpath problem
The classpath specified in the Java build path for the project is, unfortunately, not
available to the Ant process. If you are building a project that references another
project, the classpath for the javac compiler must be set up in the following way:
<javac srcdir="${source}" destdir="${build}" includes="**/*.java">
<classpath>
<pathelement location="../MyOtherProject"/>
<pathelement location="../MyThirdProject"/>
</classpath>
</javac>

Building J2EE applications


As we have just shown, building a simple Java application using Ant is quite
easy. Now we will also show you how to use Ant to build your J2EE projects.

EAR, WAR, and EJB JAR files all contain a number of deployment descriptors
that control how the artifacts of the application are to be deployed onto an

644 WebSphere Studio Application Developer Version 5 Programming Guide


application server. These deployment descriptors are mostly XML files and are
standardized in the J2EE specification.

While working in Application Developer, some of the information in the


deployment descriptors is stored in XML files, but these files also contain
information in a format convenient for interactive testing and debugging. That is
part of the reason it is so quick and easy to test J2EE applications in the internal
WebSphere Application Server included with Application Developer.

The actual EAR being tested, and its WAR, EJB, and client application JARs, are
not actually created as a standalone file. Instead, a special EAR is used that
simply points to the build contents of the various J2EE projects. Because these
individual projects can be anywhere on the development machine, absolute path
references are used.

When an Enterprise Application project is exported, a true standalone EAR is


created, including all the module WARs, EJB JARs, and Java utility JARs it
contains. Therefore, during the export operation, all absolute paths are changed
into self-contained relative references within that EAR, and the internally
optimized deployment descriptor information is merged and changed into a
standard format. To create a J2EE compliant WAR or EAR, we therefore have to
use Application Developer’s export function.

Using or importing a J2EE project


In this example we use the ItsoProGuide enterprise application we developed in
the previous chapters. This application consists of one EJB module, several Web
modules, a J2EE client application, and a utility JAR file (from a Java project).

You can use the ItsoProGuide enterprise application that you have in your
workspace, or you can import our sample application as described in “Installing
the ItsoProGuide.ear file” on page 812.

Ant J2EE build script


To build the ItsoProGuide enterprise application, we wrote a new Ant build script
that utilizes the Application Developer’s J2EE Ant tasks. Because this build script
is not really tied to either Web projects or the EJB project, we chose to put it in
the enterprise application project’s META-INF directory. To add this script, do the
following:
򐂰 Make sure the J2EE perspective is shown and that the J2EE Navigator view
is selected.
򐂰 Expand the ItsoProguide project, select the META-INF directory and New ->
Other (context), then select Simple -> File and click Next.

Chapter 19. Building applications with Ant 645


򐂰 Enter build.xml as the file name and make sure that the folder says
ItsoProGuide/META-INF. Then click Finish.
򐂰 Switch to the Source tab and paste the code in Example 19-1 into the
build.xml file. The source code is available in:
\sg246957\sampcode\deploy-ant\j2ee\build.xml

Example 19-1 J2EE Ant script


<?xml version="1.0" encoding="UTF-8"?>
<project name="ITSO Pro Guide Ant" default="Total" basedir=".">

<!-- Set global properties -->


<property name="work.dir" value="c:/ItsoProGuideTest" />
<property name="dist" value="${work.dir}/dist" />
<property name="project.ear" value="ItsoProGuide" />
<property name="project.ejb" value="ItsoProGuideEJB" />
<property name="project.war.1" value="ItsoProGuideBasicWeb" />
<property name="project.war.2" value="ItsoProGuideStrutsWeb" />
<property name="project.util" value="ItsoProGuideJava" />
<property name="project.client" value="ItsoProGuideJavaClient" />
<property name="type" value="incremental" /> <==== or full
<property name="debug" value="false" />
<property name="source" value="false" />
<property name="meta" value="false" />
<property name="noValidate" value="false" />

<target name="init">
<!-- Create the time stamp -->
<tstamp />
<!-- Create the dist directory where the output files are placed -->
<mkdir dir="${dist}" />
</target>

<target name="info">
<!-- Displays the properties for this run -->
<echo message="debug=${debug}" />
<echo message="type=${type}" />
<echo message="source=${source}" />
<echo message="meta=${meta}" />
<echo message="noValidate=${noValidate}" />
<echo message="Output directory=${dist}" />
<echo message="project.ear=${project.ear}" />
<echo message="project.ejb=${project.ejb}" />
<echo message="project.war.1=${project.war.1}" />
<echo message="project.war.2=${project.war.2}" />
<echo message="project.util=${project.util}" />
<echo message="project.client=${project.client}" />
</target>

646 WebSphere Studio Application Developer Version 5 Programming Guide


<target name="deployEjb">
<!-- Generates deployed code for the EJBs -->
<ejbDeploy EJBProject="${project.ejb}" NoValidate="${noValidate}" />
</target>

<target name="buildEjb" depends="deployEjb">


<!-- Builds the EJB project -->
<projectBuild ProjectName="${project.ejb}" BuildType="${type}"
DebugCompilation="${debug}" />
</target>

<target name="buildWar1">
<!-- Builds the WAR project -->
<projectBuild ProjectName="${project.war.1}" BuildType="${type}"
DebugCompilation="${debug}" />
</target>

<target name="buildWar2">
<!-- Builds the WAR project -->
<projectBuild ProjectName="${project.war.2}" BuildType="${type}"
DebugCompilation="${debug}" />
</target>

<target name="buildUtil">
<!-- Builds the utility project -->
<projectBuild ProjectName="${project.util}" BuildType="${type}"
DebugCompilation="${debug}" />
</target>

<target name="buildClient">
<!-- Builds the application client project -->
<projectBuild ProjectName="${project.client}" BuildType="${type}"
DebugCompilation="${debug}" />
</target>

<target name="buildEar">
<!-- Builds the EAR project -->
<projectBuild ProjectName="${project.ear}" BuildType="${type}"
DebugCompilation="${debug}" />
</target>

<target name="exportEjb" depends="init">


<!-- Exports the EJB JAR -->
<ejbExport EJBProjectName="${project.ejb}"
EJBExportFile="${dist}/${project.ejb}.jar" ExportSource="${source}"
overwrite="true" />
</target>

Chapter 19. Building applications with Ant 647


<target name="exportWar1" depends="init">
<!-- Exports the WAR file -->
<warExport WARProjectName="${project.war.1}"
WARExportFile="${dist}/${project.war.1}.war" ExportSource="${source}"
overwrite="true" />
</target>

<target name="exportWar2" depends="init">


<!-- Exports the WAR file -->
<warExport WARProjectName="${project.war.2}"
WARExportFile="${dist}/${project.war.2}.war" ExportSource="${source}"
overwrite="true" />
</target>

<target name="exportClient" depends="init">


<!-- Exports the application client JAR file -->
<appClientExport AppClientProjectName="${project.client}"
AppClientExportFile="${dist}/${project.client}.jar"
ExportSource="${source}" overwrite="true" />
</target>

<target name="exportEar" depends="init">


<!-- Exports the EAR file -->
<earExport EARProjectName="${project.ear}"
EARExportFile="${dist}/${project.ear}.ear" ExportSource="${source}"
IncludeProjectMetaFiles="${meta}" overwrite="true" />
</target>

<target name="buildAll"
depends="buildEjb,buildWar1,buildWar2,buildClient,buildUtil,buildEar">
<!-- Builds all projects -->
<echo message="Built all projects" />
</target>

<target name="exportAll"
depends="exportEjb,exportWar1,exportWar2,exportClient,exportEar">
<!-- Exports all files -->
<echo message="Exported all files" />
</target>

<target name="Total" depends="buildAll,exportAll">


<!-- Buidl all projects and exports all files -->
<echo message="Total finished" />
</target>

<target name="clean">
<!-- Delete the output files -->
<delete file="${dist}/${project.ejb}.jar" failOnError="false" />
<delete file="${dist}/${project.war.1}.war" failOnError="false" />

648 WebSphere Studio Application Developer Version 5 Programming Guide


<delete file="${dist}/${project.war.2}.war" failOnError="false" />
<delete file="${dist}/${project.client}.jar" failOnError="false" />
<delete file="${dist}/${project.ear}.ear" failOnError="false" />
</target>

</project>

This script provides you with a selection of useful J2EE operations you can
combine to produce the desired results. We will not go through all the different
Application Developer Ant tasks that we use because their names describe their
purpose.

Note: Documentation for the Application Developer Ant tasks can be found in:
<wsad>\wstools\eclipse\plugins\com.ibm.etools.j2ee.ant_5.0.1\doc\index.htm

There are also tasks for regenerating EJB Access Beans and some other
utility tasks.

We have included some dependencies between the targets:


򐂰 Building the EJB project relies on generating the deployed code
򐂰 Build all executes all the build targets
򐂰 Export all executes all the export targets
򐂰 A total target executes build all and export all

In the global properties for this script we define a number of useful variables,
such as the project names and the target directory. We also define a number of
properties that we pass on to the Application Developer Ant tasks. These
properties allow us to control whether the build process should perform a full or
incremental build, if debug statements should be included in the generated class
files, and if Application Developer’s metadata information should be included
when exporting the project.

When launching this Ant script, we can also override these properties by
specifying other values in the arguments field, allowing us to perform different
kinds of builds with the same script.

We only included two of the Web projects for separate build and export. The
script could be expanded to include all the Web projects of the enterprise
application.

Chapter 19. Building applications with Ant 649


Running Ant for J2EE
When launching the build.xml script, we can select which targets to run and the
execution order. As an example we export some of the projects with their source
code by calling the following targets (in the order as shown below):
info Shows the properties that will be used
clean Removes old output files, if they exist
init Creates the output directory
buildWar1 Builds one Web project
exportWar1 Exports one Web project
exportEjb Exports the EJBs
exportEar Exports the EAR project

Select the build.xml file in the J2EE Navigator view and Run Ant (context).
Select the targets in the correct sequence and enter arguments to build the class
files with debugging information, include the source code, and include
Application Developer metadata in the generated EAR file:
-DDebug=true -Dsource=true -Dmeta=true

. The output EAR file is placed in the directory:


c:\ItsoProGuideTest\dist

Figure 19-10 shows the target selection dialog with the argument. On the
right-hand side, the Log Console view shows the operations performed and their
results. At the very beginning, the properties used in the script are displayed.

650 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 19-10 Launch Ant to build and export a J2EE project

To build a production-ready EAR file, you would have to execute the total target
with an argument of -Dtype=full so that all the classes are recompiled without
debugging information.

We have now shown you two examples of using Ant within Application Developer.
These are basic operations that you could perform using the Application
Developer GUI.

With Ant you can also automate more complex tasks, for example, to perform a
complete build of a project, export the resulting EAR file, deploy it to a
WebSphere Application Server, start it, run regression tests using JUnit, and
send you an e-mail with the results. This is outside the scope of this book.

Building Javadoc with Ant


See “Using Ant to generate Javadoc” on page 136 for an Ant build script to
generate Javadoc.

Chapter 19. Building applications with Ant 651


Running Ant outside of Application Developer
To automate the build process even further, you may want to run Ant outside of
Application Developer by running Ant in a so called headless mode for this
purpose.

Preparation of the command file


Application Developer provides a runAnt.bat file in:
<wsad>\wstools\eclipse\plugins\com.ibm.etools.j2ee.ant_5.0.1

This command file invokes Ant in headless mode and passes the parameters
that you specify. The file must be tailored with the workspace location.

To build our J2EE project, we copied the runAnt.bat file to a new file called
itsoRunAnt.bat and changed it as shown in Figure 19-11.

echo off
setlocal
REM The root directory of your WSAD installation
set WSAD=D:\WSAD5\eclipse

REM ************* The location of your workspace *****************


set WORKSPACE=E:\WSAD5sg246957
REM ************* The location of your workspace *****************
if not exist %WORKSPACE% echo ERROR: incorrect workspace=%WORKSPACE%,
edit this runAnt.bat and correct the WORKSPACE envar
if not exist %WORKSPACE% goto done

:run
@echo on
%WSAD%\jre\bin\java -cp %WSAD%\startup.jar org.eclipse.core.launcher.Main
-consolelog -application com.ibm.etools.j2ee.ant.RunAnt
-data %WORKSPACE% %*

:done

Figure 19-11 Modified runAnt.bat file

We updated the WSAD variable to point to the directory where Application


Developer is installed (also include the \eclipse subdirectory) and the WORKSPACE
variable to point to our workspace directory. We provide the modified file in:
\sg246957\sampcode\deploy-ant

Note that you have to tailor the file with correct directory locations.

652 WebSphere Studio Application Developer Version 5 Programming Guide


Running the command file

Note: When running Ant in headless mode, Application Developer must not
be started. If Application Developer is started on the machine where
runAnt.bat is invoked, it does not do anything.

To run the command file, start a Windows command prompt and change to the
directory where the itsoRunAnt.bat file is located. Then execute the following
command:
itsoRunAnt -buildfile c:\WSAD5sg246957\ItsoProGuide\META-INF\build.xml
clean exportWar1 -Dsource=true -Dmeta=true

The -buildfile parameter should specify the fully qualified path of the
build.xml script file. We can pass the targets to run as parameters to itsoRunAnt
and we can also pass Java environment variables by using the -D switch.

In this example we chose to run the clean and exportWar1 targets and we chose
to include the Java source and metadata files in the resulting EAR file. The
output from the script is shown in Example 19-2.

Example 19-2 Ant headless output


Headless RunAnt started
RunAnt.run antArgs.length=11
RunAnt.run about to null HeadlessWorkspaceSettings
RunAnt.run about to create new HeadlessWorkspaceSettings
RunAnt.run DONE create new HeadlessWorkspaceSettings
RunAnt.runAntCommands args=[Ljava.lang.String;@1b3f0c97
RunAnt.runAntCommands about to create new AntRunner
RunAnt.runAntCommands DONE create new AntRunner
RunAnt.runAntCommands args=[Ljava.lang.String;@1b3f0c97

clean:

init:

exportWar1:
[warExport] Exporting: ItsoProGuideBasicWeb ...
[warExport] Exporting: ItsoProGuideBasicWeb ... Building:
/ItsoProGuideBasicWeb.
Invoking Java Builder on /ItsoProGuideBasicWeb....
[warExport] Exporting: ItsoProGuideBasicWeb ... Building:
/ItsoProGuideBasicWeb.
Reading saved built state for project ItsoProGuideBasicWeb....
[warExport] Exporting: ItsoProGuideBasicWeb ... Building:
/ItsoProGuideBasicWeb.
Preparing for build...

Chapter 19. Building applications with Ant 653


......
Scrubbing output folder...
Analyzing sources...
Compiling ItsoProGuideBasicWeb/Java Source/itso/bank/facade...
Compiling ItsoProGuideBasicWeb/Java Source/itso/basicweb/control...
Compiling ItsoProGuideBasicWeb/Java Source/itso/basicweb/filter...
Compiling ItsoProGuideBasicWeb/Java Source/itso/basicweb/listener...
Compiling ItsoProGuideBasicWeb/Java Source/itso/jbwp...
Reading saved built state for project ItsoProGuideEJB....
Reading saved built state for project ItsoProGuideJava....
Build done....
......
[warExport] Exporting: ItsoProGuideBasicWeb ... Updating....
[warExport] Exporting: ItsoProGuideBasicWeb ... Done.

BUILD SUCCESSFUL

Total time: 5 seconds


RunAnt.run done

The output file ItsoProGuideBasicWeb.war was created in the output directory


c:\ItsoProGuideTest\dist as specified in the build.xml script.

Summary
In this chapter we introduced you to the Ant build tool and explained how to
perform a build of both a simple Java application and a full J2EE application.

We also described how to run the Ant tool outside of Application Developer for
easier integration into your build process.

654 WebSphere Studio Application Developer Version 5 Programming Guide


20

Chapter 20. Profiling applications


In this chapter, we discuss the architecture for profiling, the process of profiling
Java processes, and the performance analysis tools provided with Application
Developer.

© Copyright IBM Corp. 2003. All rights reserved. 655


Profiling architecture
Application Developer provides the developer with a set of tools to allow for early
analysis of performance related issues in Java applications. The profiling tools
can be used to gather performance information on applications that are running:
򐂰 Inside an application server, such as WebSphere
򐂰 As a standalone Java application
򐂰 On the same machine as Application Developer
򐂰 On a remote machine from Application Developer
򐂰 In multiple JVMs

Using filters, you can focus on classes that you are interested in and omit tracing
for others.

Traditionally, performance profiling is done once an application is getting close to


deployment or when it has already been deployed. Using the Application
Developer profiling tools allows you to move this analysis to a much earlier phase
in the development cycle, therefore giving you more time to modify your
architecture based on any problems detected.

Profiling creates a number of different graphical and tabular views of a Java


program’s run-time behavior, and simplifies identifying and diagnosing
performance related problems.

The basic architecture of the profiling tools involves the JVM, (Java Virtual
Machine), where the application is running, an agent running inside the JVM
capturing profiling information, an agent controller that controls the agent and
retrieves profiling information, and the performance analyzer inside Application
Developer. The relationships between the components is shown Figure 20-1.

The agent runs inside the JVM and uses the Java Virtual Machine Profiler
Interface, (JVMPI), to interface with the JVM. If you are interested in more
information about JVMPI, the following Sun Web site has details:
http://java.sun.com/products/j2se/1.3/docs/guide/jvmpi/jvmpi.html

656 WebSphere Studio Application Developer Version 5 Programming Guide


Deployment Host(s) Development Host

Application Developer

Java Virtual Machine

Performance Analyzer
User
App Control Interface
Agent

data control
Viewer
control

Agent Controller data Formatter

Figure 20-1 Application Developer profiling architecture

Profiling Java processes


In this section, we will use the ItsoProGuide enterprise application that we
developed so far. We start a server in profiling mode, and use this application to
collect profiling data, and later analyze the collected data.

We also run some of the Web application processes to collect and analyze data.

Agent Controller
Before you can start using the profiling tools, be sure that you have the Agent
Controller installed, and that it is started as a service on the host where the
application to profile is running.

Installing the Agent Controller is explained in “Installing the Agent Controller” on


page 792.

Once the Agent Controller is installed, ensure that it is started as a service. Click
Start -> Settings -> Control Panel, then select Administrative tools and Services.
You should see an entry for the IBM Agent Controller in the list of services
(Figure 20-2).

Chapter 20. Profiling applications 657


Figure 20-2 IBM Agent Controller service entry

Profiling an application in the WebSphere Test Environment


When you have made sure that the Agent Controller is installed and started, you
are ready to start profiling your application.

We assume here that you have created the ItsoServer test server, as described
in “Creating a server for testing” on page 224.

To begin, you must start your test server in profiling mode. To do so, switch to
Server perspective and select the ItsoServer in the Servers view, then select
Profile from the context menu.

Figure 20-3 shows the server in the Server view once it has started in profiling
mode.

Figure 20-3 Server started in profiling mode

Attaching to a Java process


To start a new profiling session, select Profile -> Attach -> Java Process. We
want to run the profiling against the process that is already running, namely the
server process that we started earlier. From this menu you could also launch a
new process, as described in “Launch Java process for profiling” on page 663.

658 WebSphere Studio Application Developer Version 5 Programming Guide


In the dialog that is displayed, you should see the process ID of the server
process listed. Expand unknown[PID:XXXX] in the Agents list to see the
available agents (Figure 20-4).

Figure 20-4 Attach Java process - select agent

There are two agents available for you to select: Java Profiling Agent and J2EE
Request Profiler.

The Java Profiling Agent collects data within the boundaries of a single Java
Virtual Machine's (JVM) execution space. The agent is attached to a JVM in
which the profiled application runs. Profiling focuses on the level of an agent or
process and provides the following types of sequence diagrams:
򐂰 Object interactions
򐂰 Class interactions
򐂰 Thread interactions

The J2EE Request Profiler is an agent that resides within the application server
process for the purpose of collecting data from the interception points of the
application's requests. The J2EE Request Profiler uses the Agent Controller to
externalize this data so that it can be rendered by the various views provided by
the Profiling perspective of the Workbench.

The J2EE Request Profiler collects data from requests arriving in EJB containers
as well as Web containers. This data collection mechanism enables the creation
of sequence diagrams, which represent interactions among servlets, JSPs, and

Chapter 20. Profiling applications 659


enterprise beans, while ignoring other artifacts of the application infrastructure
that do not represent the business logic of the application. The collected data
enables the creation of a variety of different diagrams, which are defined for
specific levels of the profiling hierarchy (monitors, hosts, processes, and agents).
The Sequence Diagram views of the Profiling perspective offer the following
diagram types:
򐂰 Host interactions
򐂰 Process interactions
򐂰 Thread interactions
򐂰 Object interactions
򐂰 Class interactions

Click All>> to select both the Java Profiling Agent and the J2EE Request Profiler.

Click Next to proceed to the next page of the wizard. On this page, you can
change the default name of the monitor. Normally you will leave the defaults on
this page (Figure 20-5).

Figure 20-5 Attach Java process - select project and monitor

Click Next to proceed to the Profiling Filters page (Figure 20-6). On this page,
there are several existing sets of filters for you to select from.

You can select one of the predefined filters, edit a filter, or add a new one.

Note: A filter limits the profiling data that is collected by package or class
name.

660 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 20-6 Attach Java process - set filters

򐂰 Default—Normally you do not want to include system classes in profiling. The


default filter does this for you.
򐂰 WebSphere J2EE—Filters com.tivoli* and db2j* in addition to the default.
򐂰 WebSphere Studio—Stricter filter that changes two filters: com.ibm.etools*
and org.eclipse*.

Click Next, and you are taken to a page where you an specify more profiling
options (Figure 20-7):
򐂰 Start profiling after a number of invocations or time period (remove startup
invocations)
򐂰 Collect boundary classes and instance-level information in the execution flow

Click Finish.

Chapter 20. Profiling applications 661


Figure 20-7 Attach Java process - profiling options

Start monitoring
The profiling perspective with the Profiling Monitor view opens with the two
agents. You are reminded with a pop-up window that you have to start
monitoring. We have connected so far, but we have not started monitoring.

The process along with both monitors are shown in the Profiling Monitor view
(Figure 20-8). Select them both and select Start Monitoring from the context
menu to begin gathering statistics.

Figure 20-8 Profiling Monitor

662 WebSphere Studio Application Developer Version 5 Programming Guide


To collect data, run some of the Web transactions, for example:
򐂰 Select the ItsoProGuideBasicWeb project and Run on Server.
򐂰 Enter a customer number, then select an account, run a deposit, and list the
transactions records.
򐂰 If you have implemented the EJBs and the Banking facade that calls the
BankEJB session bean (see “Adapting the Web applications” on page 436)
then the EJBs are used to access the EJBBANK database.
򐂰 Retrieve the collected data using the Refresh Views icon or select
Refresh Views from the context menu of an agent.
򐂰 Run a second sequence of deposit and list transactions for another customer.
򐂰 Refresh the view.

Stop monitoring by selecting Pause Monitoring in the Profiling Monitor view.

Performance analysis views


To access the different profiling views, use the icons on the toolbar:
򐂰 for Heap view
򐂰 for Object References view
򐂰 for Execution Flow view.
򐂰 for Package Statistics view
򐂰 for Class Instance Statistics view
򐂰 for Class Method Statistics view
򐂰 for Instance Statistics view
򐂰 for Method Statistics view

See “Performance analysis” on page 666 for further details.

Launch Java process for profiling


In addition to attaching to running processes, as you did when profiling Web
applications, you can also launch Java processes for profiling.

We use the ItsoProGuideJava Java project, described in “Creating a Java


project” on page 94.

Select Profile -> Launch -> Java Process and the Launch Java Process wizard
opens (Figure 20-9).

Chapter 20. Profiling applications 663


Select the ItsoProGuideJava project, and enter itso.bank.main.BankMain as the
main class.

Figure 20-9 Launch Java Process

The remainder of the wizard is the same as the Attach to Java Process wizard.
We leave the default options, so click Finish.

Your are automatically taken to the Profiling perspective, the Java process is
launched and monitored, and the output is displayed in the Profiling Console
view, as shown in Figure 20-10.

Retrieve the data using Refresh Views. You can now analyze the profiling data
that was collected, as explained in “Performance analysis” on page 666.

664 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 20-10 Profiling Console view

Profiling remote processes


The profiling feature in Application Developer allows you to monitor applications
running on a remote host. The only requirement is that the host has to have the
IBM Agent Controller installed and running.

If Application Developer is not installed on the remote host, the Agent Controller
has to be installed separately. IBM Agent Controller is available for many different
environments, including AIX®, HP, Windows, zOS, i-series, Linux, and Solaris.

Attaching a Java process on a remote machine is done by creating a remote


server and starting it in profiling mode. Details about creating a remote server
can be found in “Creating a remote server and file transfer mechanism” on
page 520.

Profiling a remote server uses the same process as a local one, as described in
“Profiling an application in the WebSphere Test Environment” on page 658.

Chapter 20. Profiling applications 665


Performance analysis
Before we analyze the performance, we must simulate end user usage using a
Web browser. In this section we analyze the data collected by running the
ItsoProGuideBasicWeb application we EJB access. As you use the Web
application, the profiling agents collect data.

Using the performance analysis data gathered by the agent, you can identify
potential problems by focusing on:
򐂰 Time consuming classes and methods
򐂰 Memory intensive classes and methods
򐂰 Garbage collection statistics
򐂰 Objects that are not garbage collected
򐂰 Thread activity

To help you analyze the data returned by the profiler, Application Developer
provides a number of different views that focus on different aspects of the data.
They include:
򐂰 Package statistics (statistical)
򐂰 Class method statistics (statistical)
򐂰 Method statistics (statistical)
򐂰 Heap (graphical)
򐂰 Execution flow (graphical)
򐂰 Object interactions (graphical)
򐂰 Class interactions (graphical)

The different views should be used in conjunction to gather the complete picture
of your application performance. This will provide you with the information
required to determine where you can most productively concentrate your efforts
to improve performance.

The views are linked together; that is, if you have selected something in one
view, the other views will show information about the same object. This makes it
easy to collect all information about a particular object.

As an example, if you select a class from the Package Statistics view, you can
switch to the Class Method Statistics view to get details about the execution of
the methods of that class.

To update the information in the profiling views to show the latest data captured
by the profiler, select Refresh Views from the view menu. This will refresh all the
views, not just the one you are currently in.

666 WebSphere Studio Application Developer Version 5 Programming Guide


Package statistics
The Package Statistics view shows information about the packages in your
application (Figure 20-11).

Figure 20-11 Package Statistics view

By default this view shows the following information about the packages:
򐂰 Total base time for all classes in the package
򐂰 Total cumulative time for all classes in the package
򐂰 Number of calls made to each class
򐂰 Number of live object instances of the class for which garbage collection has
not occurred
򐂰 Active size of memory consumption by each live object instance of this type

Base time of a method is the time spent executing this method only. It does not
include time spent in other Java methods that this method calls.

Cumulative time of a method is the time the method spends on the execution
stack, including both time spent in the method itself and in other methods that it
calls.

In statistical profiling views, the following icons appear:


򐂰 Indicates that there is an increase in the numeric value for that particular
cell in the table since the last time the view was refreshed.
򐂰 Indicates that there is a decrease in the numeric value for that particular
cell in the table since the last time the view was refreshed.
򐂰 Indicates that the class, instance, or method is new since the last time the
view was refreshed. This icon shows up in the narrow second column.

Chapter 20. Profiling applications 667


You can tailor the display by adding and deleting columns. Select Choose
Columns from the context menu (Figure 20-12). You can add or remove columns
from the view by selecting or deselecting them from the list.

Figure 20-12 Choose columns dialog

You can sort on different columns by clicking in the column header. If you are
interested in determining the package with the longest base time, you would click
in the header of the Base Time column.

Class method statistics


The Class Method Statistics view shows information about individual classes and
their methods in your application. This view goes into more detail about each
class and method than Package Statistics view (Figure 20-13).

By default, this view shows the following information about your methods:
򐂰 Class names
򐂰 Method names (when the class name is expanded)
򐂰 Package to which each class belongs
򐂰 Total base time spent in each class, and broken down by method
򐂰 Average base time spent in each class, and broken down by method
򐂰 Total cumulative time spent in each class, and broken down by method
򐂰 Number of calls made to each class, and broken down by method

668 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 20-13 Class Method Statistics view

Method statistics
The Method Statistics view is essentially the same as the Class Methods
Statistics view, except that it lists all methods together instead of separating them
by class. This allows us to sort by base and cumulative times to compare all
methods. The view is shown in Figure 20-14.

This view has the same columns as the Class Method Statistics view, except
here the package column is replaced by a class name column.

Chapter 20. Profiling applications 669


Figure 20-14 Method Statistics view

Heap
The Heap view is the most versatile profiling view and can be used to help you in
a number of performance analyzing tasks, such as:
򐂰 Identifying time-consuming objects and methods
򐂰 Identifying memory-intensive classes
򐂰 Gauging garbage collection
򐂰 Gauging program concurrency
򐂰 Identifying memory leaks
򐂰 Browsing method execution as a function of time.

The Heap view is color coded to make it easier to identify trouble spots in the
code (Figure 20-15).

670 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 20-15 Heap view

This version of the Heap view shows base time per class. Red is used to indicate
classes that have a relatively high base time. To switch to other types of
information in this view, you select from the Color by drop-down combo box
(Figure 20-16).

Figure 20-16 Heap view options

Chapter 20. Profiling applications 671


Each of the options will show a different perspective on the application
performance. You can switch between showing objects and showing methods by
using the icons in the toolbar at the top of the view, ( and ).

The status line at the bottom of the Heap view displays information about the
currently selected object or method in the view.

The following sections describe how you can use the Heap view to help you with
the tasks listed above. Note that the other profiling views can also be used for
some of the tasks or to provide additional information.

Identifying time consuming objects and methods


Select Cumulative Time in the Color by combo box. As the default, the slider is
positioned at the maximum value along the scale and you see mostly blue and
black colored class instances.

Move the slider, adjusting the color coding until you see a variation in the color of
the rectangles that represent object instances, or diamonds that represent class
objects in Objects mode; or the rectangles that represent the methods in
Methods mode (Figure 20-17).

Slider

Figure 20-17 Heap view before and after adjusting the slider

672 WebSphere Studio Application Developer Version 5 Programming Guide


Select the object or method instance that is a color other than blue or black.
Observe the status line, and note the instance of the object or method. The
status line also tells you the amount of base time that this instance consumed, as
well as other statistics.

The same process can be repeated for all entries in the Color by combo box.

Note: A class name might be red, but the rectangle representing it in the
histogram might be blue. The reason for this difference is that there are many
instances of the class, but each one alone does not occupy much memory
(blue). However, the total combination of all such instances takes up a lot of
memory (indicated by the red font color for the class and the length of the bar
in the histogram).

Gauging garbage collection


The objects for which garbage collection has occurred are represented by empty
rectangles. By positioning the mouse over such objects, you get information (in
the status line) on the time at which garbage collection occurred for the object.

Identifying memory leaks


The histogram that is displayed in the Heap view in Objects mode shows the
garbage collection status of instances of objects. The color-filled rectangles
denote instances for which garbage collection has not occurred.

Unexpectedly large numbers of such instances may suggest a memory leak.


Source code analysis can help you to investigate these objects, and find their
creators, and any objects that refer to them.

Browsing method execution as a function of time


Click to switch to Methods mode. Instead of class instances, you now see
the heading class methods in the right column. Each square represents one
method for the class on that line (Figure 20-18).

Select a method in the Heap view. The status line displays the name of the
method, the base time, the cumulative time, and the number of calls of that
particular method. This information gives you an indication of the time (in
seconds) that was spent executing that method. In our case, we select
PerformTransaction.doPost.

Chapter 20. Profiling applications 673


Figure 20-18 Heap view by methods

Method invocation
In the Heap view or in one of the statistics view, select the
PerformTransaction.doPost method and Show Method Invocation from the
context menu to display the Method Invocation view (Figure 20-19).

This view shows a representation of one method and the calls that are executed
from that method and the called methods. Clicking or scrolling over each method
(the vertical bar) shows its cumulative time.

Using the zoom icons (+ and -) you can zoom into areas of the graph.

674 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 20-19 Method Invocation view

From the context menu, click Show Caller to see the caller(s) of the selected
method in the view.

Figure 20-20 shows the callers of BankEJB.getAccounts. The highlighted area is


the selected method.

Chapter 20. Profiling applications 675


Figure 20-20 Method Invocation: show caller of getAccounts

Each time you do this, one method higher up in the calling sequence is
displayed.

Select the method. The vertical length of the selected area indicates the base
time for the method. You can determine the execution time for this method by
checking the vertical time scale on the right side of the view. The status line gives
you the cumulative time for the method.

Note: Selecting Next and Previous in the context menu navigates through all
the invocations of the current method.

Select Show Method Invocation Table from the context menu, to see the related
tabular view of this (Figure 20-21).

676 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 20-21 Method Invocation: table view

Each method can be expanded to show other methods that it invoked.

Method execution
Open the Method Execution view by selecting Show Method Execution from the
context menu of a selected method.

The Method Execution view summarizes the information in the Method


Invocation view and therefore shares most of its interpretations, but at a more
abstract level.

Figure 20-22 shows the Method Execution view for the listAccounts.doPost
method. This is an accumulation of all instances. It shows the invoked methods.
In our case we can see the findByPrimaryKey method took a long time.

The Method Execution view displays a single pattern at a time. However, it may
contain hidden patterns or sub-patterns, which are points of variance in the
pattern. If it does display any hidden patterns or sub-patterns, you will see one or
more indicators of the form n/m. To see these hidden variants, click the indicator
repeatedly. There may be several such indicators throughout the view.

Chapter 20. Profiling applications 677


Figure 20-22 Method Execution view

678 WebSphere Studio Application Developer Version 5 Programming Guide


Execution flow
The Execution Flow view displays the execution of the entire program, while the
method views display the execution of a single method at a time. You can use the
Execution Flow view to identify active threads, long-lived or frequently called
methods, and phases of program execution.

Note: Zoom In from the view menu to focus on specific parts of the graph and
Zoom Out to see the bigger picture.

When you are in the Execution Flow view, or in the Method Invocation or
Executions views, you can open the editor on a method by selecting Open
Source from the context menu. This is true for classes whose source files exist in
the Workbench.

An example of an Execution Flow view is shown in Figure 20-23. When you move
the cursor over the vertical bars, the status line at the bottom of the view shows
the method name and other related information.

Figure 20-23 Execution Flow view

Horizontally you can see the active threads, with the garbage collection thread,
(GC), always shown at the far left (not shown in Figure 20-23). At the far right of
the graph is the time scale showing elapsed time in seconds.

Chapter 20. Profiling applications 679


Each vertical bar represents a method and the height of the bar represents the
time of execution for that method. The color of the bar identifies the class of the
object.

Note: By default, all objects show the same color. Selecting Graph Colors
from the context menu opens a dialog where you can change the preferences
so that each class has a unique color. Then bars of the same color would
represent methods belonging to the same class.

You can use the Zoom In action on the view menu to show parts of the graph in
higher resolution. As you do this, you will see the time scale at the right of the
graph get more granular. If you want to see more details about a method’s
execution, select it in this view and then select Show Method Execution from the
context menu.

To reduce the amount of information in the view, you can remove threads from it.
To do this, select Threads from the view’s context menu and deselect any
threads that you are not interested in at the moment. From the menu you can
also show or hide all repetitions of methods.

Sequence diagram
The Sequence Diagram view presents the execution flow of an application
according to the notation defined by UML. The view presents a sequence of
dependent events, where events are defined as method entries and exits as well
as outbound calls and return calls.

To show this view, select Window -> Show View -> Sequence Diagram.
Figure 20-24 shows the Sequence Diagram view.

680 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 20-24 Sequence Diagram view

The Zoom In and Zoom Out buttons enable you to view either more or less detail
of the view. The Home button returns the view to its original size.

Within the Sequence Diagram view in the Profiling perspective, any two
consecutive events have the same vertical distance between them. This does not
take into account the time elapsed between the occurrence of these two events.
The vertical bar to the left of the diagram, with rectangles of equal height and
different shades of red, corresponds to the representative distance between
events. Scrolling over the red rectangles will show the elapsed time between
events.

Chapter 20. Profiling applications 681


To enable working with large-scale sequence diagrams, an overview is provided.
Click the Overview button in the lower right corner of the Sequence Diagram
view to activate the overview (Figure 20-25).

Figure 20-25 Sequence Diagram view with overview

On activation, the button moves up along with the upper frame of the overview,
and clicking it at this time closes the overview.

The overview presents the same sequence diagram as the main view, but it is
complete, scaled-down, and simplified to the vertical object life span lines and
the call lines. This compact view of the diagram provides you with the means to
find interesting sections of the diagram, which may be obvious in this scaled
down view. On finding an interesting section of the diagram, you can move the
main view to that position by double-clicking the spot or dragging and dropping
the light red rectangle within the overview boundaries.

Instance statistics
The Class Instance Statistics view shows the number of objects of each class
(Figure 20-26).

When a class is expanded, you can see the actual objects. The icons are the
same as in the Package Statistics view.

682 WebSphere Studio Application Developer Version 5 Programming Guide


The Instance Statistics view shows the same objects with their base and
cumulative times (Figure 20-27).

Figure 20-26 Class Instance Statistics view

Figure 20-27 Instance Statistics view

Chapter 20. Profiling applications 683


Object references
The Object References view shows patterns of references in varying detail, both
to and from a set of objects (if such references exist). To display information, this
view requires profiling data that contains object reference information. You can
use this view to locate objects that still have references to them, study data
structures, and find memory leaks. An example of an Object References view is
shown in Figure 20-28.

Note: To interpret this view, you need to have a good understanding of how
objects are allocated and referenced in your application and how Java handles
object referencing.

Figure 20-28 Object References view

This view displays the following information:


򐂰 Base set of objects—Appears in the gray area on the left. Each new object
resides in this area once, but its instances also reside elsewhere. The view
shows references to and from this base set of objects. You can select the
base set of objects from the Display field.
򐂰 Objects—Represented by squares, each colored uniquely by class. Squares
come in two forms:
– A single square denotes a single instance
– Twin squares represent multiple instances
򐂰 Class objects—Represented by diamonds.

684 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 References between instances—Denoted by black arrows between the
instances. An arrow points to the objects being referenced. Arrows point right
to left.
򐂰 Repetition of an object—Represented by a blue, upward-pointing arrow.
Click this arrow to display a long, blue arrow that leads to another place
where the same object is displayed.
򐂰 Old objects—Denoted by a red font color for the number of objects and the
class name, both of which appear to the right of each instance.

Note: Old objects are those created prior to a certain point during the
profiling session. You can specify that point as you create a dump of the
object references using the Collect Object References icon in the
toolbar. Objects that are created after that point in time are referred to as
New-generation objects.

򐂰 New-generation objects—Denoted by a black font color for the number of


objects and the class name, both of which appear to the right of each
instance.

Some things to be aware of


Here are some further considerations:
򐂰 Because communications with the IBM Agent Controller is done via TCP/IP
sockets, firewalls may block the communication.
򐂰 Views have to be refreshed to show the latest data by using Refresh Views
from the context menu in any profiling view, or by clicking in the Profile
Monitor view.
򐂰 You cannot use profiling and debugging at the same time.

Summary
In this chapter, we covered the profiling tools of Application Developer and
included examples of the different statistics that are accumulated.

Chapter 20. Profiling applications 685


686 WebSphere Studio Application Developer Version 5 Programming Guide
Part 5

Part 5 Team programming


Part 5 covers how to use Application Developer in a team development
environment. We cover team development with both Common Versions System
(CVS) and Rational ClearCase LT.

© Copyright IBM Corp. 2003. All rights reserved. 687


688 WebSphere Studio Application Developer Version 5 Programming Guide
21

Chapter 21. Version control


Application Developer is a file based integrated development environment (IDE).
It operates on a workspace where all of the data relative to the environment
options and to the loaded projects is stored. This workspace has a root directory
and is composed of regular files. You may have as many workspaces as you
want, but you can only work with one at a time per each IDE instance.

A local history of resource changes is maintained within the workspace. This


allows developers to compare and replace resources with earlier editions.

In most cases, though, developers do not work alone, but rather as part of a
team. Application Developer’s open architecture allows software configuration
management (SCM) systems to be plugged-in to support such kinds of
development effort.

This chapter includes the following topics:


򐂰 Workspace activities in standalone development
򐂰 Team development and terminology
򐂰 SCM integration with Application Developer

© Copyright IBM Corp. 2003. All rights reserved. 689


Local history
In Application Developer, a local history of changes is maintained when you
create or modify and save a file. This allows you to compare the current file
edition to a previous one, replace the file with a previous edition, or even restore
a deleted file. Each edition in the local history is identified by the date and time
the file was saved.

Note: Only files have local histories. Projects and folders do not. The local
history is independent of the team development environment and the shared
team repository.

Comparing files
To compare the current edition of a file with a different one, choose Compare
With -> Local History from the file’s context menu. You can select different local
editions and compare them against the currently loaded edition (Figure 21-1).

Figure 21-1 Comparing the TransRecordBean class with its local history

There are three panels in the Compare with Local History window:
򐂰 The top left panel lists all the available editions in the local history for the
selected file. These editions are grouped by the save date.

690 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 The top right panel lets you select what Java structure you want to compare.
The default is to compare the whole file, but if you had more than one class in
the compilation unit, you could want to limit the comparison to just on class by
selecting it in the list.
򐂰 The bottom panel shows the current edition on the left and the selected
edition on the right. Graphical cues indicate where the code has changed and
what kind of change occurred. You can see in Figure 21-1, for instance, that
the setAccount method that exists in the current edition did not exist in the
previous edition. There are also two arrow buttons that let you scroll through
the individual changes.

Replacing files
A similar dialog (Figure 21-2) lets you replace the loaded edition of a file for
another one. To do that, select Replace With -> Local History from the file’s
context menu.

Figure 21-2 Replacing the loaded edition with another one from the local history

This time around, the dialog presents you with just two panels. It would make
little sense to show the Java Structure panel because a replace would affect the
whole compilation unit.

Chapter 21. Version control 691


Restoring deleted files
To restore a deleted file, select the container where the file used to be (like a
folder or a Java package) and select Restore From Local History from its context
menu. The dialog in Figure 21-3 is displayed:

Figure 21-3 Restoring a deleted file from the local history

Preferences
Finally, you can set how Application Developer manages the local history by
selecting Window -> Preferences and then selecting Workbench -> Local History
(Figure 21-4).

Figure 21-4 Setting the local history preferences

692 WebSphere Studio Application Developer Version 5 Programming Guide


Team development
The Eclipse platform is based on the concept of letting users create and edit
resources that are stored in the file system. Unfortunately, network file systems
do not offer the necessary flexibility and set of services to support team
development. If you project calls for more than just one person, chances are that
you are going to need a software configuration management (SCM) system, or at
least a subset of it.

The U.S Department of Defense, in its standard on software development


(DOD-STD-2167A), defines SCM as follows:
Software Configuration Management is the discipline of identifying the
configuration of software systems at discrete points in time for the purpose of
controlling changes and maintaining traceability of changes throughout the
software life cycle.

These tools must support a set of related and sometimes overlapping functional
areas, among which are:
򐂰 Version control—This is the ability to store and retrieve snapshots of the
state of components at any given point in time. The mechanism usually
employed to store these versions is called forward-delta versioning, that
enables version branching with a minimum of storage wasted.
򐂰 Problem tracking—Problem tracking usually works through two
mechanisms: defects and features. Defects track the life cycle of a problem
with any of the software components from identification all the way through to
final resolution. Features are additional requirements that must be
implemented in the system.
򐂰 Change management—It is the process of identifying, tracking, and
controlling changes to software components.
Change management commonly provides an audit track that identifies which
files have gone through what changes, when these changes occurred, who
modified the files, and why. A defect or feature may result in the modification
of hundreds of files across more than one product, including documentation
and test cases.
Change management, through the mechanism of tracks, should produce and
keep records of each file modified in each separate product as related to the
particular defect or feature. When you are ready to include the changes for
the defect in the release and build the release, you should only need to
specify the track number and all the changes would be committed to the
repository and included in the release.
򐂰 Build and deployment management—Gives you the ability to build and
deploy your software product in a repeatable manner.

Chapter 21. Version control 693


򐂰 Access control—This is normally done at the component level, and inherited
downward from parent components to children components. Advanced
systems support fine-grained access control policies, that go beyond simple
read and write permissions.
򐂰 Process management—The above-mentioned functions are not
independent from each other. They should work in a concerted manner. At
least, the functions should be embedded into a set of procedures to follow
when applying changes to IT solutions. Given the importance of this aspect, it
calls for a tool that supports and enforces an SCM process while at the same
time providing flexibility in this respect.

To enable such features, Application Developer has a plug-in called Team


Support. It lets the environment take advantage of external SCM systems
through the use of adapters. Each SCM product requires a specific adapter, that
should be supplied by the product vendor. Application Developer includes an
adapter for Concurrent Version System (CVS).

Note: The support for Rational ClearCase and ClearCase LT is provided


through a separate plug-in, also included in Application Developer.

The choice of a particular SCM usually affects the users’ workflow, because the
steps for retrieving files, comparing their content with local content, returning
updated files to the repository, and so forth, depend on the product that offers
these services. For this reason, this chapter only covers the concepts relative to
Application Developer’s support for SCM systems.

Repository
SCM systems store software components in a persistent storage called a
repository. Repositories coordinate multi-user access to the artifacts shared by
the development team. Projects in a repository can be of two forms: a branch
(modifiable) or a version (immutable).

Branches
A branch is a shared work area that lets team members release their work and
use code updates from others. Teams share and integrate their ongoing work in
branches. Thus, a branch represents the current state of a shared project.

A repository can contain multiple branches, such as one for new development
and another one for maintenance. Projects may be developed in multiple parallel
branches. You could, for example, be making fixes to Version 1.3 of a product in
order to evolve to Version 1.3.1, while at the same time working on the
development of Version 2.

694 WebSphere Studio Application Developer Version 5 Programming Guide


Resources normally do not exist in isolation but typically have implicit or explicit
dependencies on other resources. For example, Web pages have links to other
Web pages, and source code has references to artifacts defined in other source
code resources.

As resources are released to the branch, these dependencies can be affected.


Ensuring the integrity of the dependencies is important because a branch
represents a current valid project state. At any point, a team member should be
able to take the branch contents as a basis for new work.

Synchronizing
Resources can be changed in the team members’ individual workspaces without
affecting the branch. Each developer must explicitly commit changed resources
to the branch, while taking care not to overwrite resources changed by other
developers. This process is called synchronization.

In Application Developer, you may choose to synchronize your workspace with


the branch in just one step, or by first updating your workspace and then
committing your changes to the branch.

Updating is the process of copying changes other developers have made into
your local workspace. This ensures that you will have the latest work from the
other team members incorporated in your work as well.

During update, conflicts due to parallel changes may arise. These conflicts must
be resolved in your local workspace. Application Developer offers you the
necessary tooling that makes this process easier. Do not forget to do the
appropriate testing before considering the update process successful.

Important: If you do not resolve conflicts between your local workspace and
the branch before committing your work, you run the risk of overwriting
resources that were updated by other team members. Application Developer
will let you do that, because that might be just what you want to do. Exercise
special care when proceeding this way.

After you have updated your workspace with the latest resources in the branch,
merging any conflicting changes and making the appropriate tests locally, you
can safely commit your changes to the branch.

When you commit your changes, they get copied from your local workspace to
the branch. As a result, these changes will be seen by other developers as
incoming changes when they later update their workspaces.

Chapter 21. Version control 695


Versions
A version constitutes the baseline of a project at a particular point in time. When
a resource is versioned, a non-modifiable copy of it is released to the repository.
If you later change the resource in your workspace, the version you created will
not be affected.

Important: It is often preferable to synchronize resources with the repository


before versioning. This will ensure that there are no standing incoming or
outgoing changes that might be accidentally excluded from the version.

It is possible to version a resource without versioning the project that contains it.
You would do that if you wanted to create temporary baselines that alone were
not enough for a new project version. Most of the time, though, you will version
entire projects. During the synchronization of a whole project, the contained
resources are implicitly versioned.

You may create versions of resources that are either on your workspace or on the
branch. When you version a set of resources from your workspace, their current
state will be frozen and made a version. This is the preferred method of
versioning because when you do so, you know exactly what will be released into
the version.

When you version set of resources from the branch, the current state of the
branch frozen and versioned. You should not do that unless you are sure what is
currently committed to the branch.

Concurrency strategy
Application Developer uses an optimistic concurrency strategy in the sharing of
the repository resources. This means that any member of the team can make
changes to any resource he or she has access to. Because two team members
can commit to the branch changes to the same resource, conflicts can occur and
must be dealt with. This model is termed optimistic because it is assumed that
conflicts are rare.

696 WebSphere Studio Application Developer Version 5 Programming Guide


Note: The optimistic concurrency strategy is essential to the development of
J2EE applications. Some resources, for example deployment descriptors,
must be maintained by the whole team at the same time, because they contain
information that pertain to the work of every developer on the team.

Take an EJB module, for instance. If the traditional pessimistic concurrency


strategy were to be adopted, developers would have to take turns when
creating and editing EJBs, because most of the time the process involves
altering the EJB deployment descriptor. The use of such model is a practical
impossibility for J2EE.

The secret to the success of the optimistic strategy is a good synchronization


tool that eases the process of resolving conflicts that will certainly appear.
Fortunately, Application Developer offers such a tool.

Figure 21-5 shows how two developers would work on the same resource at the
same time:

Initial
Project Load
or
Development
Change #2
Developer 1
commit update commit

Branch
update update
commit

Developer 2
Change #1
Time
Figure 21-5 Concurrency workflow

Chapter 21. Version control 697


The ideal workflow is one in which the stream integrity is always preserved and
change conflicts are detected and dealt with. Such a work flow should follow
these steps:
򐂰 Start fresh—Before starting to work, the developer should update his or her
workspace with the content of the branch. If there is no local work that has to
be preserved, the fastest way to achieve this is to select the whole project on
the branch and add it to the workspace. This will overwrite any local copies of
the project resources with those from the branch.
򐂰 Make changes—The developer can now work locally in the workspace. New
resources can be created and existing ones modified. All changes are saved
locally in the workspace file system.
򐂰 Synchronize your work in two steps:
– Update—The developer can examine all incoming changes and add them
to the local workspace. In this way, it can be determined whether there are
changes which might affect the integrity of what is about to be released.
The developer has to resolve conflicts, retest, then run integrity checks (for
example check for broken hypertext links, ensure the code compiles, and
so forth).
– Commit—When the developer is confident that the changes are well
integrated with the latest branch contents, they can be committed to the
branch. To be absolutely sure, the update step might be repeated before
the final release to check that there are no new incoming changes.

Under some circumstances, this work flow may be simplified. You may be
confident that incoming changes do not affect you, and choose to commit without
updating. In general, however, team members should be encouraged to follow a
flow similar to the one presented above to ensure that the branch’s integrity is not
accidentally compromised.

Application Developer team support


Application Developer delivers adapters for two SCM products: Concurrent
Versions System (CVS) and Rational ClearCase LT. Both adapters are included
with the default installation, but neither of the SCM product servers will be
installed automatically. You have to install the desired server manually, either
before you begin your Application Developer installation or after it has been
completed.

The diagram in Figure 21-6 shows a comparison of the functionality of the two
SCM products for which adapters are shipped with Application Developer.

698 WebSphere Studio Application Developer Version 5 Programming Guide


ClearCase
Version control
Parallel development
Life cycle integration
UCM out of the box
Web Browser interface
ClearCase LT Promotion Model
Version control Baseline Comparison
Parallel development Snapshot views
Life cycle integration Dynamic views
UCM out of the box Binary Sharing
CVS Web Browser interface Auto build dependency
Version control Promotion Model Distributed builds
Parallel development Baseline Comparison Distributed servers
Life cycle integration Snapshot views Support for MultiSite

Freeware. Open source Included with Application Sold exclusively by Rational


community. Developer. Low cost of Software. Upgrade for
adoption ClearCase LT
Figure 21-6 SCM tools: functionality comparison

SCM adapters for other commercial SCM products are provided by the vendors
of these products. To find a list of SCM products and adapters provided by IBM
Business Partners, go to the SCM Adapters page on the Application Developer
site:
http://www.ibm.com/software/ad/studioappdev/partners/scm.html

Terminology comparison
When working with Application Developer, you will use the terminology provided
by the team development environment. When you use facilities of SCM systems
outside of Application Developer, you also have to understand their terminology.

Table 21-1 shows the mapping between terms used in Application Developer,
CVS, and ClearCase.

Chapter 21. Version control 699


Table 21-1 Application Developer, CVS and ClearCase terminology comparison
Application Developer CVS ClearCase

Workspace File system Work area

Repository Repository VOB

Branch Branch (tag) Stream and project

Project Module View

Resource File Element

Commit Commit Check-in

Update Update Compare with

Version Version (tag) Version

Summary
In this chapter we introduced version control, the local history, and the basic
terms of team programming.

In Chapter 22, “Using Concurrent Versions System” on page 701 we explore


CVS in detail.

In Chapter 23, “Using ClearCase” on page 747 we explore Rational ClearCase


LT in detail.

700 WebSphere Studio Application Developer Version 5 Programming Guide


22

Chapter 22. Using Concurrent Versions


System
In this chapter we introduce you to Concurrent Versions System (CVS), a widely
adopted open-source version control system. It can be used by individual
developers as well as by large, distributed teams. We discuss how to set up a
CVS server on the Windows platform and use it with Application Developer’s
client interface.

Note: To complete the steps described in this chapter, you need two instances
of Application Developer, one for each of the two simulated team members. It
is much easier and more efficient to do so using two different machines, but
you can also open two Workbenches on just one machine with two
workspaces. Refer to the “Workspace basics” on page 23 for detailed
instructions.

This chapter describes the following:


򐂰 What is CVS?
򐂰 How to install CVSNT on the Windows platform
򐂰 How to create a new repository and configure it in Application Developer
򐂰 CVS Resource History view
򐂰 Branches in CVS
򐂰 Working with patches

© Copyright IBM Corp. 2003. All rights reserved. 701


Introduction
Concurrent Version System (CVS) is a simple open-source software
configuration management (SCM) system. Of the SCM features listed in the
previous chapter, CVS implements only version control. It can be used by
individual developers as well as by large, distributed teams.

Some of the main features of CVS are:


򐂰 Multiple client-server protocols over TCP/IP, that let developers access the
latest code from a wide variety of clients virtually anywhere an Internet
connection exists.

Note: Application Developer supports two communication protocols:


pserver (password server) and ssh. The default is pserver. The other
protocols have to be manually configured through Window -> Preferences
-> Team -> CVS -> Ext Connection Method.

򐂰 It stores all the versions of a file in a single file using forward-delta versioning,
which stores only the differences among the versions.
򐂰 It insulates the different developers from each other. Every developer works in
his own directory, and CVS merges the work in the repository when each
developer is done. Conflicts should be resolved in the process.

Important: CVS and Application Developer have a different understanding


of what a conflict is:
򐂰 For CVS, a conflict arises when two changes to the same base file are
close enough to be noticed by the merge command.
򐂰 For Application Developer, a conflict exists when the base revision of a
modified file is different from the revision stored in the repository.

򐂰 It uses an unreserved checkout approach to version control that helps avoid


artificial conflicts common when using an exclusive checkout model.
򐂰 It keeps your shared projects’ data in repositories. Each repository has a root
directory on your file system.
򐂰 CVS maintains a history of the source code revisions. Each change is
stamped with the time it was made and the user name of the person who
made it. It is recommended that developers also provide a description of the
change. Given that information, CVS can help you find answers to questions
such as: Who made the change? When was it made, and why?

702 WebSphere Studio Application Developer Version 5 Programming Guide


The CVS server code for Linux and UNIX platforms is available at the project’s
site:
http://www.cvshome.org

Please refer to it for information about how to install and configure your CVS
repository.

Installing CVS on the Windows platform


Application Developer comes with a CVS client, but you still have to install the
server. Even though it is recommended to use CVS on platforms other than
Windows for large-scale development, for simplicity we will use a Windows
server throughout this chapter: CVSNT.

Important: CVSNT is not officially supported by the Eclipse platform.


Depending on the version, different bugs may occur. In our case, we used
CVSNT 2.0.0rc3 without any problems.

An important note about CVSNT support can be found at:


http://dev.eclipse.org/viewcvs/index.cgi/%7Echeckout%7E/platform-vcm-home
/docs/online/cvs_features2.0/cvs-faq.html

You can download CVSNT straight from the server site:


http://www.cvsnt.org/

Follow these steps to install CVSNT. Note that you must have Windows
administrative rights to be able to follow these instructions:
򐂰 Download and execute the installer, in our case cvsnt-2.0.0rc3.exe.
򐂰 Select the typical install and leave all the options at their default values.
򐂰 Reboot your machine, even if the installer does not tell you to do so. This step
will guarantee that the environment variables are properly set up.

Creating a CVS repository on CVSNT


First you have to create a new repository. Open your control panel by selecting
Start -> Settings -> Control Panel. Double-click the CVS for NT icon to open the
service configuration dialog (Figure 22-1).

Chapter 22. Using Concurrent Versions System 703


Figure 22-1 CVSNT service configuration (Service Status page)

On the Service Status page, stop the CVS services by clicking both Stop buttons.
Click Repositories to switch to the page to configure our new repository.

Select the Repository Prefix option because we want our repositories to be under
a common root directory. This is just an organizational feature, and is not really
mandatory for your own setups. You have to manually create a C:\Repositories
directory in your file system before configuring it.

Now click Add to create the new /RedBank repository and complete the dialog as
shown in Figure 22-2.

Figure 22-2 New repository path

Click OK. A confirmation dialog informs you that C:/Repositories/RedBank does


not exist. Click Yes to create it.

Note: CVS users must have the appropriate access rights to the repository
directory structure (full control in Windows).

After you are done, the Repositories page should look like Figure 22-3.

704 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-3 CVSNT service configuration (Repositories page)

CVSNT uses either the domain or the local server directory for user
authentication under the pserver protocol. You have to choose the correct value
for your environment. This setting only applies if your machine is connected to a
Windows domain. This specification is in the Advanced page (Figure 22-4).

Figure 22-4 CVSNT service configuration (Advanced page)

Chapter 22. Using Concurrent Versions System 705


Click Apply to commit your new repository. Switch back to the Service Status
page and restart both CVS services (Figure 22-5).

Figure 22-5 CVSNT service configuration (Service Status page)

Configuring CVS in Application Developer


The team support for CVS had some major improvements in Application
Developer Version 5.

What is new in Application Developer Version 5?


These are the most important improvements in team support:
򐂰 CVS Repository Exploring perspective to browse the content of repositories
򐂰 CVS Console view showing messages returned from the CVS server
򐂰 Consistent CVS terms used throughout, for example, branch instead of
stream
򐂰 File compression options for transferring files to the CVS repository
򐂰 Requirement that new resources must be explicitly added to CVS control
򐂰 Text/binary support by identifying what file types are text or binary
򐂰 Synchronization of outgoing change optimizations (only outgoing changes are
synchronized, which reduces network traffic)
򐂰 Showing of CVS decorators as visual indicators next to resources

This list does not include all the new features, but points to the major differences
compared to previous versions of WebSphere Studio products.

706 WebSphere Studio Application Developer Version 5 Programming Guide


CVS preferences
Before you start working with CVS, you should look through the CVS
preferences. Select Windows -> Preferences and expand the Team section
(Figure 22-6).

Figure 22-6 CVS preferences

Also expand the CVS section and verify the settings of the subsections. For
example, you can change these options:
򐂰 Show the CVS Console when there is output
򐂰 Name of the CVS server (in case you renamed the server during installation)

Keyword expansion
It is interesting to get the versioning information that is inside of CVS in the
Javadoc that is created for each file. One way to accomplish this is through
keyword expansion.
򐂰 On the CVS preferences page, set Default keyword substitution to ASCII with
keyword expansion (-kkv).
򐂰 Some of the available keywords (case sensitive) are:
– $RCSfile$—Adds the file name without the path

Chapter 22. Using Concurrent Versions System 707


– $Revision$—Adds the latest version number
– $Date$—Adds the date and time when the last revision was checked in
– $Author$—Adds the name of the author
– $Id$—Adds all of the above in one string
– $Log$—Adds the comments written on every check in.
򐂰 These keywords will be expanded anywhere in the source file. There is
unfortunately no way to selectively turn off keyword substitution.
򐂰 You can add the keywords to the Javadoc for the classes as in:
/**
* class comment goes here.
*
* <pre>
* Date $Date$
* CVS History:
* $Log$
* </pre>
* @author $Author$
* @version $Revision$
*/
򐂰 If you want all your new Java files to contain this header, it is easy to add it to
the default class level template. Select Window -> Preferences -> Java ->
Templates. Now select the typecomment template. Click Edit and replace the
text with this code (Figure 22-7):
/**
* class comment goes here.
*
* <pre>
* Date $$Date$$ <=== $ must be written as $$
* CVS History:
* $$Log$$
* </pre>
* @author $$Author$$
* @version $$Revision$$
*/
򐂰 To make the same change for files generated by the Application Developer
wizards, also change the filecomment template.

708 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-7 Using CVS keywords in Java comments

After committing a new class to CVS, you can see the comments in the source:
/**
* class comment goes here.
*
* <pre>
* Date $Date: 2003/04/20 02:14:05 $
* CVS History:
* $Log: Test.java,v $
* Revision 1.1 2032/04/20 02:14:05 UELI
* Change 2
*
* </pre>
* @author $Author: UELI $
* @version $Revision: 1.1 $
*/

Chapter 22. Using Concurrent Versions System 709


What changes could impact your work?
In Version 4, after adding an EJB project to CVS, you can delete the project from
the workspace and, when necessary, import it again. In this case, all the
components are reloaded.

In Version 5, this scenario will lead to many errors, such as missing classes, and
you have to redeploy the EJBs. The reason is that some of the components, such
as the deployed code, are not stored in the CVS repository in the default setup.

Ignored Resources
To store the deployed code in the CVS repository, you have to change the
preferences of the Workbench:
򐂰 Select Window -> Preferences -> Team -> Ignored Resources (Figure 22-8).
򐂰 Remove the check marks to store EJB deployed code in CVS.

Figure 22-8 CVS ignored resources preferences

More details on the ignored Resources preference


On the Ignored Resources page, you can specify file name patterns to be
excluded from the version control management system.

710 WebSphere Studio Application Developer Version 5 Programming Guide


Files are matched against the list of patterns, before they are considered as
version control candidates. A file or directory that matches any one of the
patterns will be ignored during update or commit operations. The patterns may
contain the wildcard characters * (any sequence of zero or more characters) and
? (any one character).

To add a file type to the ignore list, click the Add button. In the window, enter a file
type (for example, *.class). To remove a file type from the ignore list, select the
file type in the ignore list and click Remove. You can temporarily disable ignoring
the file pattern by de-selecting it from the list; you do not have to remove the
specified file pattern from the list.

Ignoring resources from version control


When synchronizing resources, you may not want to commit all resources to the
repository. There are two ignore facilities provided, allowing the user to specify
which resources should be excluded from update and commit operations:
򐂰 The first is a global ignore facility, provided by the Workbench as shown in
Figure 22-8.
򐂰 The second is the CVS ignore facility, which reads the contents of a special
.cvsignore file to determine what to ignore.

CVS ignore facility


The Eclipse CVS client recognizes a file named .cvsignore in each directory of a
project. This is a standard CVS facility and many existing CVS projects may
contain such a file.

This text file consists of a list of files, directories, or patterns. In a similar way to
the global ignore facility, the wildcard * and ? may be present in any entry in the
.cvsignore file. Any file or subdirectory in the current directory that matches any
one of the patterns is ignored.

It is important to note that the semantics of this file differ from that of the global
ignore facility in that they apply only to files and directories in the same directory
as the .cvsignore file itself. A project may contain one .cvsignore file in each
directory. For more information, visit http://www.cvshome.org.

Resources that have not been added to CVS control can be ignored by selecting
Team > Add to .cvsignore from the context menu of the resource in the Navigator
view. This menu option is also available in the Synchronize view.

Chapter 22. Using Concurrent Versions System 711


Label decorations
By default, Application Developer does not show CVS label decorations that give
you a visual indication of when a project, folder, or file is linked to a repository,
and whether or not the file has been updated in the workspace, but not in the
repository.

Before we begin working with CVS in Application Developer, select Window ->
Preferences, then select Workbench -> Label Decorations in the Preferences
window.

Select CVS in the label decorations list, as shown in Figure 22-9.

Click OK to save these preferences. The results of this are evident in this chapter
in all figures that show the Navigator view.

Figure 22-9 Workbench Label Decorations

CVS console
In the CVS Console view, you can see all the interactions between Application
Developer and CVS. Select Window -> Show View -> Other -> CVS -> CVS
Console to open the view.

712 WebSphere Studio Application Developer Version 5 Programming Guide


Development scenario
To show you how to work with CVS in Application Developer, we will follow a
simple but typical development scenario, shown in Table 22-1.

Two developers, stade1 and stade2, work together to create three entity beans:
Customer, TransRecord and Account. These are the same entity beans created in
Chapter 12, “Developing EJB applications” on page 373, so you can refer to that
chapter for additional details.

Table 22-1 Sample development scenario


Step Developer 1 (stade1) Developer 2 (stade2)

1 Creates a new EJB project named


ITSOProGuideCVS, adds it to version
control and commits it to the
repository.

2 Imports the ITSOProGuideCVS CVS


module as a Workbench project.
Creates the Customer entity bean,
adds it to the version control and
synchronizes the project with the
repository.

3 Synchronizes the project with the


repository before doing new
development.

4 Creates the Account entity bean. Creates the TransRecord entity bean,
adds it to the version control and
synchronizes the project with the
repository.

5 Adds the Account bean to the version


control and synchronizes the project
with the repository, resolving conflicts
in the process.

6 Versions the project.

Steps 1 through 3 are serial development—no parallel work is being done.


During steps 4 and 5, both developers work in parallel, resulting in inevitable
conflicts. These conflicts are resolved using Application Developer’s tooling.

In the sections that follow, we will perform each of the steps and explain the team
actions in detail.

Chapter 22. Using Concurrent Versions System 713


Creating and sharing the project (step 1 - stade1)
Application Developer offers a perspective specifically designed for viewing the
contents of CVS servers: the CVS perspective. For additional information
concerning this perspective, please refer to the “CVS Repository Exploring
perspective” on page 73.

Adding a CVS repository


Open the CVS Repository Exploring perspective. We use the CVS Repositories
view to add the repository location created in “Creating a CVS repository on
CVSNT” on page 703.

Select New -> Repository Location from the context menu to open the Add CVS
Repository dialog (Figure 22-10).

Substitute for you own user ID


and password

Figure 22-10 Adding a CVS repository

Type localhost (or the server name or IP address of your CVS server) in the
Host field. In the Repository path field, type /RedBank. Recall that /RedBank was
the path specified when you created the repository, including the leading slash.

714 WebSphere Studio Application Developer Version 5 Programming Guide


Type the appropriate authentication data in the User and Password fields for the
first developer. Connect with the server using the pserver protocol and the
default port, and select Validate Connection on Finish .

Important: With pserver, passwords are stored on the client side in a trivial
encoding and transmitted in the same encoding. The encoding is done only to
prevent inadvertent password compromises, and will not prevent an attacker
from obtaining the password. The other supported protocol, ssh, does not
have this problem, but has to be manually set up.

Click Finish, and the CVS Repositories view now contains the new repository
location (Figure 22-11).

Figure 22-11 CVS Repositories view

Expanding a location in CVS Repository view reveals branches and versions. A


special branch, called HEAD, is shown detached because of its importance. It is
the main integration branch, holding the project’s current development state.

You can use the CVS Repositories view to checkout repository resources as
projects on the Workbench. You can also configure branches and versions, view
resource histories, and compare resource versions and revisions.

We must first create a project and share it before making full use of the
repository.

Create a project
Switch to the J2EE perspective and create a new EJB project called
ItsoProGuideCVS by selecting File -> New -> EJB Project.

In the wizard’s first page, select Create 2.0 EJB Project and click Next to proceed
to the second page (Figure 22-12).

Chapter 22. Using Concurrent Versions System 715


Figure 22-12 Create EJB project

Click Finish to create the project. The new project now appears in the J2EE
Navigator view. Share the project by selecting Team -> Share Project from its
context menu. The Share Project wizard opens (Figure 22-13).

Figure 22-13 Share project using CVS (page 1)

Select CVS as the repository type. Sharing a project using Rational ClearCase is
explained in “Adding a project to ClearCase source control” on page 762.

716 WebSphere Studio Application Developer Version 5 Programming Guide


Note: The third option, File System Example, allows you to get and put files
from and to a shared network directory without any kind of locking or version
control.

Click Next and select the existing repository location that you defined earlier. You
could also create a new repository location from here, if it was not already
defined (Figure 22-14).

Figure 22-14 Share project using CVS (page 2)

Click Next to proceed to the next page of the wizard. Here you could specify a
different name for the CVS module than the project name, but we do not want to
do that. We leave the default, as shown in Figure 22-15, and click Finish to
complete the wizard.

Figure 22-15 Share project using CVS (page 3)

Chapter 22. Using Concurrent Versions System 717


After sharing the project in CVS, Application Developer opens the Synchronize
view (Figure 22-16).

Figure 22-16 Synchronizing project with repository before adding to version control

The question marks indicate that the resources do not exist in the repository;
only the project is in the repository for now.

Select the project folder (ItsoProGuideCVS) and select Add to Version Control
from the context menu. The Synchronize view is updated (Figure 22-17).

Figure 22-17 Synchronizing project with repository after adding to version control

Now select Commit from the ItsoProGuideCVS project’s context menu to commit
the changes to the repository.

You are prompted to enter a commit comment. It is important to describe the


changes to the files that are committed to the repository. In our case, we are just
adding the empty project, so we enter Initial Project Load as the description
(Figure 22-18).

718 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-18 Comment for files committed to repository

Click OK to commit the changes to the repository. The project is now shared.

Adding a shared project to the workspace (step 2 - stade2)


The point of using CVS is to allow multiple developers to work in a team on the
same project. We have created the project in one developer’s workspace, shared
it using CVS, and now wish to add the same project to a second developer’s
workspace.

First of all, the second developer must add the CVS repository location to the
workspace using the CVS Repositories view in the CVS perspective, as
described in “Adding a CVS repository” on page 714.

The difference is now that the HEAD branch in the repository, if expanded,
contains the ItsoProGuideCVS module, as shown in Figure 22-19.

Figure 22-19 CVS Repository with ItsoProGuideCVS project

Select the ItsoProGuideCVS module and Check Out As Project (context). The
current project in the HEAD branch is added to the workspace.

Chapter 22. Using Concurrent Versions System 719


Developing the Customer bean
Now that both developers have exactly the same synchronized HEAD branch of
the ItsoProGuideCVS project on their workspaces, it is time for the second
developer to create the first EJB: Customer.

Define the Customer bean as described in “Define the Customer bean” on


page 389, but use the ItsoProGuideCVS project.

When you are done, the generated files are shown in the J2EE Navigator view
(Figure 22-20).

Figure 22-20 J2EE Navigator view after creating the Customer entity bean

Tip: The “greater than” sign in front of a resource name means that the
particular resource is not synchronized with the repository. You can always
use this visual cue to determine when a project requires synchronization.

Synchronizing with the repository


To update the repository with these changes, select the ItsoProGuideCVS project
and select Team -> Synchronize with Repository from its context menu. The
project is compared with the repository, and the differences are displayed in the
Synchronize view (Figure 22-21).

720 WebSphere Studio Application Developer Version 5 Programming Guide


new folders/files

Figure 22-21 Synchronizing ItsoProGuideCVS after creating the Customer bean

This view allows you to update resources in the Workbench with newer content
from the repository, commit resources from the Workbench to the repository, and
resolve conflicts that may occur in the process. The question mark icons indicate
that the files do not exist in the repository.

Add these new resources to version control by selecting ItsoProGuideCVS in this


view and then Add to Version Control from its context menu. Figure 22-22 shows
the updated Synchronize view.

Figure 22-22 Synchronize view with files added to version control

Chapter 22. Using Concurrent Versions System 721


To actually add the files to version control, you must commit the changes. Select
the ItsoProGuideCVS project on the Synchronize view and select Commit from its
context menu. You are prompted to enter a commit comment (Figure 22-23).

Figure 22-23 Customer commit comment

Click OK to add the comment and commit the files to the repository.

Synchronizing with repository (step 3 - stade1)


The first developer now wants to start developing his or her own beans. Before
doing that, though, it is recommended that the project be synchronized with the
repository, to guarantee that it contains the most up-to-date files. This make
future merging of changes easier.

In the J2EE Navigator view, select the ItsoProGuideCVS project and Team ->
Synchronize with Repository (context). The Synchronize view opens
(Figure 22-24).

new

modified
new

Figure 22-24 Synchronizing workspace with repository

722 WebSphere Studio Application Developer Version 5 Programming Guide


Because the first developer has not created or changed anything since the last
synchronization with the repository, there are absolutely no conflicts to resolve;
only the deployment descriptor must be replaced and five new files must be
added to the workspace.

Select the ItsoProGuideCVS project in the Synchronize view and select Update
from Repository (context). Figure 22-25 shows the updated J2EE Navigator view.

Figure 22-25 J2EE Navigator on the first developer’s machine after synchronization

Parallel development (step 4 - stade1 and stade2)


Up to this point, we have created the repository and the EJB project, added the
project to the repository, developed an entity bean, and synchronized both
developers’ workspaces with these changes. None of these steps were carried
out in parallel by the two developers.

Now it is time to do some parallel development, just like you would do in a real life
scenario. The first developer create the Account bean and the second developer
creates the TransRecord bean. The synchronization of workspaces will happen
only after both are done, so that conflicts show up and can be resolved.

First developer creates the Account bean


Create the Account entity bean with two CMP fields and no extra logic:
򐂰 id—String, key attribute
򐂰 balance—int, promote to local

Important: Do not commit to the repository yet. We want the second


developer to create the TransRecord bean so that conflicts arise.

Chapter 22. Using Concurrent Versions System 723


Second developer creates the TransRecord bean
Create the TransRecord entity bean with three CMP fields and no extra logic:
򐂰 timeStamp—java.util.Date, key attribute
򐂰 transType—String, promote to local
򐂰 transAmt—int, promote to local

Second developer synchronizes with repository


To update the repository, select the ItsoProGuideCVS project and then Team ->
Synchronize with Repository from its context menu. The project is then
compared with the repository, and the differences shown in the Synchronize
view.

There are still no conflicts, because the first developer has not yet synchronized
the changes. Add the new files to version control and commit the changes to the
repository. When asked, enter the commit comment:
Added TransRecord bean

Resolving conflicts (step 5 - stade1)


In this step, we will have the first developer synchronize the changes to the
repository. This time around, though, some conflicts will arise. These conflicts are
related to files that both developers changed.

Open the J2EE Navigator view and select the ItsoProGuideCVS project. Select
Team -> Synchronize with Repository from its context menu to open the
Synchronize view.

The Synchronize view lets you inspect the changes to both the workspace and
the repository. By clicking the mode buttons on the view’s toolbar, you can limit
what it displays. The available modes are:
򐂰 Incoming mode—Shows changes to the repository that have to be copied to
the workspace, as well as conflicts.
򐂰 Outgoing mode—Shows local changes to the workspace that have to be
copied to the repository, as well as conflicts.
򐂰 Incoming / outgoing mode—Shows both workspace and repository
changes, as well as conflicts.
򐂰 Conflicts only—Shows only the conflicts

Click Incoming / Outgoing Mode in the toolbar (Figure 22-26).

724 WebSphere Studio Application Developer Version 5 Programming Guide


Incoming / Outgoing Mode Mode buttons

Outgoing

Incoming

Conflicts

Figure 22-26 Synchronize view showing conflicts

Note that we have three steps to take to synchronize the first developer’s
workspace with the repository:
򐂰 Add the Account bean related files to the repository (outgoing).
򐂰 Retrieve the TransRecord bean related files from the repository (incoming)
򐂰 Resolve conflicts with the deployment descriptor (ejb-jar.xml) and the
WebSphere extensions descriptor (ibm-ejb-jar-bnd.xmi).

Select the itso folder and select Commit from its context menu. When asked,
enter the Commit comment:
Added Account bean

Note that the files related to the Account bean have disappeared from the
Synchronize view, because they are now synchronized with the repository.

Select the itso folder again, but this time select Update from Repository from its
context menu. The whole folder is removed from the Synchronize view.

We now have to handle the conflicts. Double-click the ejb-jar.xml file (the EJB
deployment descriptor) to open the Text Compare pane, which shows you the
differences between the file in the workspace and in the repository
(Figure 22-27).

Chapter 22. Using Concurrent Versions System 725


Workspace Repository

Figure 22-27 Resolving conflicts with the EJB deployment descriptor (step 1)

Merging the changes


Our task is to merge the changes of both developers:
򐂰 The left-hand side shows the file as it is in the workspace, with two entity
EJBs: Customer and Account.
򐂰 The right-hand side shows the file as it is in the workspace, with another pair
of EJBs: Customer and TransRecord.
򐂰 The only difference between the files is that one has a TransRecord bean
declared exactly where the other declares an Account bean. The compare
tool perceives this as a change, and not as a parallel addition. We have to
make up for it manually.

In the right-hand pane, select the TransRecord bean declaration, that spans from
the <entity id="TransRecord"> tag to the </entity> tag, and select Copy from
its context menu.

726 WebSphere Studio Application Developer Version 5 Programming Guide


Now position your cursor right before the </enterprise-beans> tag on the
left-hand panel. Select Paste from the panel’s context menu and format the
addition as shown in Figure 22-28.

Figure 22-28 Resolving conflicts with the EJB deployment descriptor (step 2)

Now click Save on the left-hand pane’s context menu to save the changes.
Application Developer informs you that the changes have been saved and that
you should select Mark as Merged to make this file an outgoing change
(Figure 22-29).

Figure 22-29 Mark as merged informational dialog

Chapter 22. Using Concurrent Versions System 727


This means that Application Developer is assuming, as you have saved the local
file, that you have manually corrected the conflicts that were displayed. Thus, the
next step is to copy the local file over the file in the repository., but first you must
mark the file as merged.

Click OK to close the dialog. The Synchronize view shows you that the EJB
deployment descriptor have been saved and should be marked as merged by
placing an asterisk right next to the file name (Figure 22-30).

Figure 22-30 Marking the EJB deployment descriptor as merged

Select the ejb-jar.xml file and select Mark as Merged from its context menu.
The Synchronize view is updated to reflect an outgoing change (Figure 22-31).

Figure 22-31 EJB deployment descriptor marked as merged

We now have to apply a similar procedure to the WebSphere extensions


descriptor. Double click the ibm-ejb-jar-bnd.xmi to open the Text Compare
pane (Figure 22-32).

728 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-32 Resolving conflicts with the WebSphere extensions descriptor (step 1)

Similarly to the deployment descriptor, the file in the workspace declares JNDI
bindings for the Customer and Account beans. The file in the repository declares
JNDI bindings for the Customer and TransRecord beans. These three bindings
have to be combined in the workspace.

Select the binding declaration for the TransRecord bean on the right-hand pane,
copy it and paste it on the left pane after the binding declaration for the Account
bean (Figure 22-33).

Figure 22-33 Resolving conflicts with the WebSphere extensions descriptor (step 2)

Chapter 22. Using Concurrent Versions System 729


Save your changes by selecting Save from the left-hand pane’s context menu.
Mark the file as merged just like you did before.

Finally, select the META-INF folder and select Commit from its context menu.
Enter the commit comment: Added Account bean.

The Synchronize view should go empty because there are no more differences
between the workspace and the repository, and the J2EE Navigator view should
be updated as shown in Figure 22-34.

Figure 22-34 J2EE navigator view showing all the entity beans synchronized

Versioning (step 6 - stade1)


Now that all the changes are synchronized with the repository, we want to create
a version to milestone our work.

Select the ItsoProGuideCVS project in the J2EE Navigator view and select Team
-> Tag as Version from its context menu. The Tag Resources dialog opens
(Figure 22-35).

730 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-35 Tagging the project as a version

Type EntityBeansCreated as the version tag and click OK. If you now switch to
the CVS Repository Exploring perspective, you can see the version in the CVS
Repositories view (Figure 22-36).

project version

Figure 22-36 Project version

If you expand the ItsoProGuideCVS project you can also see the versions of all
the files.

CVS resource history


At any time, a developer that has the shared project in their workspace can view
the resource history of a file. This is the list of all the revisions of a resource in the
repository, shown in the CVS Resource History view. From this view you can
compare two revisions, replace or revert the corresponding workspace file to the
revision, or open an editor on a revision.

Select the ejb-jar.xml file in the J2EE Navigator view and Team -> Show in
Resource History (context). The CVS Resource History view opens (if not
already open) and shows the change history of the file (Figure 22-37).

Chapter 22. Using Concurrent Versions System 731


Figure 22-37 CVS Resource History view

For each resource the table displays:


򐂰 Revision—The revision number of the revision in the history. A * in this
column indicates that this is the current revision in the workspace.
򐂰 Tags—The tags that are associated with the revision. Selecting a revision line
will list the tags in the lower left pane of the view.
򐂰 Date—The date and time when the revision was created.
򐂰 Author—The name of the person who created and authored the revision.
򐂰 Comment—The comment (if any) supplied for this revision at the time it was
committed. Selecting a revision line displays the complete comment in the
lower right pane of the view.

In our case, the developer has version 1.3 of the resource, as indicated by the *
in the Revision column.

Note: Figure 22-37 displays the resource history for developer 2, who has not
synchronized with the repository to pick up the merge done by developer 1.
The same resource history for developer 1 would mark revision 1.4 as current.

To compare differences between revision 1.3 and 1.4, select both lines and
Compare (context). The compare view is displayed (Figure 22-38).

We can see the differences between the two revisions: the Account entity was
added to the XML file.

732 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-38 Compare ejb-jar.xml version 1.3 to version 1.4

Branches in CVS
In CVS, teams share and integrate their ongoing work in branches. Think of a
branch as a shared work area that can be updated at any time by team
members. In this way, individuals can work on a team project, share their work
with others on the team, and access the work of others during all stages of the
project. The branch effectively represents the current shared state of the project.

Resources can be changed in the Workbench without affecting the branch.


Individuals must explicitly provide their changed resources to the branch.

Every CVS repository has at least one branch, referred to as HEAD. Under certain
conditions, more than one branch may exist in a repository. For example, one
branch may be for ongoing work, and another branch may be for maintenance
work.

Chapter 22. Using Concurrent Versions System 733


As you make changes locally in your Workbench, you are working isolated from
the rest of the team. When you are ready to make your local resource changes
available to other team members, you'll need to commit your work to the branch.
All such changes are classified as outgoing changes when you do a
synchronization.

Ideally, you should update your local workspace with any changes others have
made in a branch before committing your work. This ensures that you have the
very latest work from the other team members. After you have updated from the
branch, merged any conflicting changes in your local Workbench, and tested
your changes locally, you can more easily commit your Workbench's changes to
the branch.

When you commit changes to the branch, your changes are copied from your
local Workbench to the branch. As a result, these changes are then seen as
incoming changes when other developers update from the branch later.

There are a few particularities that we want to point out:


򐂰 When a repository connection is made to a CVS repository, only HEAD is
shown. Other branches are shown only after expanding Versions, then
expanding a project that uses another branch.

򐂰 To determine what branch a project is a part of, select the project, then select
Properties from the context menu. Select CVS in the properties window. The
Tag field shows the current branch or version.
򐂰 When you create a new branch, the names of all existing projects in the
repository show up as children of the branch node in the repository browser
tree.
򐂰 Discarding a branch from the CVS Repositories view removes the definition
from the Workbench only. The underlying CVS branch is left untouched.

In the following sections, we create a new branch, make changes to that branch,
then merge the changes back with the HEAD branch.

Branching
Creating a branch and releasing resources to that branch is useful in cases
where you are not yet ready to put your changes in the main development flow. It
is also useful for creating incremental patches to existing versions.

To create a branch, select ItsoProGuideCVS and Team -> Branch (context). Enter
Maintenance as the branch name. We require a new version as the starting point
for the branch. A version name is generated for us in the text area, and we leave
the default name (Figure 22-39).

734 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-39 Create a new CVS Branch

If you would like to start working in the branch immediately, make sure the check
box is selected. Click OK to create the new branch.

Note: The version name is important; you will need it when you want to merge
the branches later. It identifies the point at which the branch was created.

In CVS Repositories view, expand Branches to see the new Maintenance branch
that you just created. Expanding Versions reveals the newly created
ItsoProGuideCVS Root_Maintenance version (Figure 22-40).

Figure 22-40 CVS Repositories view after branch

The project has now been versioned, and is split from the HEAD branch. We make
a few changes to the project, so that when we merge back with the HEAD branch,
there are changes.

Chapter 22. Using Concurrent Versions System 735


Note that this is not a real-life example that would justify using a separate branch.
It will merely be used in the next section to show how to merge branches.

Create session bean


In the ItsoProGuideCVS project, create a session bean named Banking as
described in “Creating the session bean” on page 416 (where we used BankEJB
as the name). Do not add any logic or references.

The J2EE Navigator view is updated, as shown in Figure 22-41.

Figure 22-41 J2EE Navigator after created Banking session bean

We must now synchronize these changes with the Maintenance branch in the
repository. Select ItsoProGuideCVS then select Team -> Synchronize with
Repository. Commit your changes, as explained in “Synchronizing with repository
(step 3 - stade1)” on page 722. We now have a new branch with contents that
differ from the original branch.

Merging
After creating and working in a CVS branch for some time, you may want to
merge your changes from the branch into another branch, or into HEAD. This is
typical if a development team keeps their work separate for a long period of time,
then merges after their code has stabilized.

To merge two branches, you have to know:


򐂰 The name of the branch or version that contains your changes.
򐂰 The version from which the branch was created. This is the version name that
you supplied when branching.

736 WebSphere Studio Application Developer Version 5 Programming Guide


In our case, the branch is Maintenance, and the version is Root_Maintenance.

To merge the branch, ensure that the destination branch is loaded into your
workspace. Because we want to merge our changes into HEAD, we must make
sure the project is shared with HEAD in the workspace. Select the project and
Replace With -> Branch or Version (context). Then select HEAD (Figure 22-42).

Figure 22-42 Replace project from HEAD branch

Click OK to replace the project. We can now merge the HEAD branch with the
Maintenance branch. Select ItsoProGuideCVS and Team -> Merge (context). The
Merge wizard opens (Figure 22-43).

Figure 22-43 Select the merge start point

Select Root_Maintenance as the start point of the merge. This is the version from
which the branch was created. Click Next.

Chapter 22. Using Concurrent Versions System 737


Select Maintenance, the branch which contains the changes you want to merge
(Figure 22-44). Note that you could select a branch or version here.

Figure 22-44 Select where to merge from

Click Finish, and the changes from the Maintenance branch are compared with
the HEAD branch.

The Merge editor opens, showing all differences between your workspace and
the Maintenance branch (Figure 22-45).

Figure 22-45 Merge editor

In a real-life scenario, you would likely run into conflicts at this point. In our case,
we keep it simple. More information on dealing with conflicts is explained in
“Resolving conflicts (step 5 - stade1)” on page 724.

738 WebSphere Studio Application Developer Version 5 Programming Guide


Load all of the desired changes into the workspace. This may be accomplished
by either manually merging changes and then selecting Save from the text
editor's context menu, or by selecting Update from Repository, Override and
Update, or Merge Changes Into Local Copy from the tree's context menu.

After all desired changes are in the workspace, select Team -> Synchronize with
Repository (context). This is where you commit all the changes to the repository,
as explained in “Synchronizing with the repository” on page 720.

Defining branch tag


If a branch exists on the server, you must define it in your workspace to be able to
access it. The CVS Repositories view does not obtain a list of all branches from
the server by default.

To define a branch manually to a repository, go to the CVS Repositories view and


select the repository where you want to create the new branch.

Note: If there are no repository locations listed in the Repositories view, you
have to add a location as explained in “Adding a CVS repository” on page 714.

From the context menu, select Define Branch Tag. The Enter Branch Tag dialog
opens, where you enter the name of the branch you want to use (Figure 22-46).

Figure 22-46 Adding a branch to repository

Note: Defining a branch tag does not add the tag to the repository. If the tag
already exists in the repository, defining the tag in the CVS Repositories view
allows the contents of the branch to be browsed. If the tag does not exist, then
the contents of the branch will be empty.

In the Repositories view, expand Branches and observe that it now contains the
new Development branch. You can now check files out from this branch, if they
exist.

Chapter 22. Using Concurrent Versions System 739


Working with patches
Patches allow developers to share work without storing it in a repository. This is
helpful when a developer wants to contribute to a project that is shared through a
repository but does not have write access to the repository.

In this situation, the developer can create a patch and either e-mail it to a
developer who does have write access or attach it to an error in the error
reporting system used by project management, depending on the process
defined by the project. A developer that does have write access can then apply
the patch to the project and commit the changes.

Creating a patch
To create a patch from a CVS project, select the resources that contains the
modifications to be included in the patch. Although this can be any folder, it is
easiest to select the project itself because the patch must be applied to the same
resource it is generated from.

Follow the steps explained in “Create session bean” on page 736 to create a
session bean called Test. We then create a patch that includes this new bean.

The patch should also be applied to the same file revision that it is based on.
Therefore steps should be taken to ensure that the patch is applied to the same
resource revision; the easiest way to enforce this is to create the patch on top of
a version.

From the context menu, select Team -> Create Patch. The Create Patch wizard
opens (Figure 22-47).

Choose where the patch should be saved:


򐂰 Save to Clipboard—his will place the patch on the clipboard so it can be
pasted into a text editor such as an e-mail program.
򐂰 Save to File System—his will place the patch in the specified file in the local
file system.
򐂰 Save in Workspace—his will place the patch in the specified file inside one of
the existing Workbench projects.

740 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 22-47 Create Patch

For small patches it may be reasonable to transfer the patch using the clipboard
but in most cases the local file system in the best option to use. Click Next to
configure how the patch is generated (Figure 22-48).

Figure 22-48 Create Patch: advanced options

Choose how to configure the patch:


򐂰 Recurse into sub-folders—If disabled, only the direct children of the selection
are included in the patch. Otherwise, all descendants are included.

Chapter 22. Using Concurrent Versions System 741


򐂰 Include new files in patch—If disabled, only files that are under CVS version
control are included. Otherwise, files that have been newly created but were
not added or are ignored will also be included.
򐂰 Diff output format—Allows the choice of several common diff output formats.
Unified is the format used by many patch application tools including Eclipse.

Click Finish.

Transfer the patch as appropriate for the project being patched. Typically, you
would e-mail the patch or send the file to someone with write access to the
repository.

Applying a patch
Before applying the patch, restore your workspace to be the same as the current
branch. This removes the Test session bean from your workspace, so that you
can add it with the patch. Select the ItsoProGuideCVS project and Replace With
-> Latest From Repository (context).

To apply a patch, you must first select the resource that the patch was generated
on. This resource should contain the same file revisions on which the patch was
generated. Select Compare with -> Patch (context). The Resource Patcher
wizard opens (Figure 22-49).

Figure 22-49 Resource Patcher

742 WebSphere Studio Application Developer Version 5 Programming Guide


Indicate where the patch is to be found:
򐂰 File—the patch is in a file on the local file system. Enter the full path to the file
or click Browse to find the file.
򐂰 Clipboard—the patch is on the clipboard. Warning: It is safer to use a file
based patch. Line endings may not be handled properly if the clipboard is
used and the patch was generated on a different platform (Linux versus
Windows).

In our case, the patch is found in the clipboard. Click Next to see the effect of
applying the patch (Figure 22-50).

Figure 22-50 Resource Patcher - Verify Patch

The top pane of this page shows whether the patch could be successfully applied
to files in your workspace. If you select an item in the tree, the bottom pane
shows the a comparison of the original and with the patch applied.

A checked item indicates that a patch could be successfully applied to a


workspace resource. You can exclude patches by deselecting them.

Chapter 22. Using Concurrent Versions System 743


A red exclamation mark may indicate that there is a problem with the patch. The
reason for the failure is found in parenthesis. In our case, the exclamation mark
indicates that we are adding new files.

Note: To apply the full patch successfully you have to eliminate the problems
(red exclamation marks) and get checked items everywhere by tweaking the
options on this wizard page (see “Options for applying a patch” on page 744).

If all is well, click Finish to apply the patch. The workspace now contains outgoing
changes for each file modified by the patch, as indicated with > signs in the J2EE
Navigator view (Figure 22-51).

Figure 22-51 Results of the patch

As you can see, Test.java, TestBean.java, and TestHome.java files have been
added, and ejb-jar.xml and ibm-ejb-jar-bnd.xmi files have been updated by
the patch, and are ready to be committed to the CVS repository.

Options for applying a patch


To get successful matches of a patch file you have the following options in the
wizard:
򐂰 Go back to the first page of the Resource Patcher wizard and select the
correct resource to which the patch should be applied.
򐂰 If a common prefix of the path names stored in the patch file does not match
the path names in you current workspace, you can select Ignore leading path
name segments (Figure 22-50 on page 743).

744 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Select the Ignore white space option to make the matching process
independent from white space differences between the patch file and files in
your workspace.
򐂰 Adjust the maximum fuzz factor that determines how far from its original line a
patch is allowed to match. The default is two. If a patch does not match at the
line given in the patch file, the Resource Patcher tries to match the patch fuzz
number of lines before or after the position.
򐂰 Use the Reverse patch option for patch files that already have been applied to
your workspace. This option is also useful to undo or redo a patch.

Disconnecting a project
You can disconnect a project from the repository. Select the ItsoBank5Utility
project and Team -> Disconnect. You are prompted to confirm and also if you
want to delete CVS control information (Figure 22-52).

Figure 22-52 Disconnect confirmation

CVS adds special directories named CVS to the project and its folders. These
directories can be deleted or kept on disconnect.

Reconnect
You can reconnect a project to the repository ( Team -> Share Project).
Reconnect is easier if the CVS folders are still in the project. If they were deleted,
you are prompted to synchronize your code with the existing repository code.

Chapter 22. Using Concurrent Versions System 745


Summary
This chapter describes how to set up and configure CVS for working with
Application Developer.

Through a simple scenario we showed how developers interact with CVS in


serial and parallel development. We also showed the compare and merge tools
and the resource history.

CVS provides a simple but efficient team development environment. You should
consider CVS even in a single workstation environment so that you get the
benefits of versioning your own code.

746 WebSphere Studio Application Developer Version 5 Programming Guide


23

Chapter 23. Using ClearCase


In this chapter we demonstrate how to use ClearCase LT with Application
Developer. The following topics are covered:
򐂰 What is Rational ClearCase?
򐂰 Basic ClearCase terminology
򐂰 Installing ClearCase LT Server and Client
򐂰 ClearCase integration with Application Developer
򐂰 A simple scenario using ClearCase with Application Developer

© Copyright IBM Corp. 2003. All rights reserved. 747


What is Rational ClearCase?
Rational ClearCase is a software configuration management (SCM) product that
helps to automate the tasks required to write, release, and maintain software
code.

Rational ClearCase offers the essential functions of version control, workspace


management, process configurability, and build management. By automating
many of the necessary and error-prone tasks associated with software
development, Rational ClearCase helps teams of all sizes build high quality
software.

ClearCase incorporates Unified Change Management (UCM), Rational's best


practices process for managing change at the activity level and controlling
workflow.

UCM can be applied to projects “out-of-the-box”, enabling teams to get up and


running quickly. However, it can be replaced with any other process that you
already have in place at your site.

ClearCase provides support for parallel development. With automatic branching


and merge support, it enables multiple developers to design, code, test and
enhance software from a common code base.

Snapshot views support a disconnected use model for working away from the
office. All changes since the last snapshot are automatically updated once you
are connected again.

Rational offers two version of the ClearCase product:


򐂰 ClearCase
򐂰 ClearCase LT

ClearCase LT is a light version for support of small teams that do not need the full
functionality of the complete ClearCase product (distributed servers, database
replication, advanced build management, transparent file access). For the
full-sized ClearCase, Rational also provides an add-on MultiSite feature.

Note: Application Developer 5.0 includes ClearCase LT.

For more information see:


http://www.rational.com/products/clearcase

748 WebSphere Studio Application Developer Version 5 Programming Guide


Basic ClearCase terminology
򐂰 Activity—A unit of work performed by an individual. In UCM an activity tracks
a change set, that is, a list of versions of files created to perform the work
(for example, Developer 1 fixing problem report #123). When you work on an
activity, all versions you create are associated with that activity.
򐂰 Component—A set of related directory and file elements. Typically, elements
that make up a component are developed, integrated, and released together.
In Application Developer, a component contains one or more projects.
򐂰 Baseline—A version of a project.
򐂰 Development stream—Each developers’ own working area.
򐂰 Integration stream—A shared working area for the team, containing the
versions of the components that are available to all developers.
򐂰 Deliver stream—The act of making a developer’s development stream
available to the integration stream, publishing a developer’s work.
򐂰 Rebase—The act of retrieving a project to work on locally, or to synchronize
your development stream with what is available in the integration stream.
򐂰 Check in and check out—A file that is to be edited must be checked out.
This lets other developers know that the file is opened by another developer.
Once a developer completes any edits on a file, it must be checked back in
before making the files available to others.
򐂰 VOB (versioned object base)—The permanent data repository where
ClearCase stores files, directories, and metadata.
򐂰 View—A selection of resources in a VOB, a window to the VOB data.

Installing ClearCase LT
Application Developer 5.0 includes both the Rational ClearCase LT Server and
Rational ClearCase LT Client products. From the Application Developer product
installation dialogs you can start the installation of ClearCase LT. You can also
start the ClearCase LT installation from the Rational_ClearCase_LT directory on
the Application Developer 5.0 CD.

Installing the ClearCase LT Server component also installs the ClearCase LT


Client component. We recommend you install the ClearCase LT Server
component before installing ClearCase LT Client on any additional machines.
Detailed instructions on how to install Rational ClearCase LT are provided in the
cc_install.pdf file, which is located on the Application Developer 5.0 CD in:
Rational_ClearCase_LT\Rational_ClearCase_LT

Chapter 23. Using ClearCase 749


Installing ClearCase LT Server
Application Developer includes a license for the ClearCase LT Server product
that enables you to install the product locally on your Application Developer
machine to try it out, but not to install it on another machine. To install it on
another machine, you must acquire a separate ClearCase LT Server license.

Notes:
򐂰 When installing the ClearCase LT Server, you can be logged on either
locally on your Windows machine or logged on to a Windows domain. If
installing while logged on locally, you will only be able to connect to the
server from your local machine. Other people in your development team
will not be able to connect to your machine and use your ClearCase LT
Server. The user account used when installing must be a member of the
local Administrators group.
򐂰 To use ClearCase LT in a team environment and let other team members
use your ClearCase LT Server, you must be logged on to a Windows
domain with a user account having Domain Administrator privileges while
installing ClearCase LT Server. The domain must also have a group for the
ClearCase users and all members of your development team must be
members of this group. This group should also be the Primary Group for
these users. You can use the Domain Users group for this.

It is highly recommended to use the Windows domain approach. In our


example we used this approach.

Figure 23-1 shows our setup.

Windows 2000
logon Domain Controller logon

Developer 1 Developer 2

Application ClearCase ClearCase ClearCase Application


Developer LT Client LT Server LT Client Developer
connect

Figure 23-1 ClearCase LT setup for this chapter

750 WebSphere Studio Application Developer Version 5 Programming Guide


To install ClearCase LT Server, perform these steps:
򐂰 To start the installation, run setup.exe from the Rational_ClearCase_LT
directory on the Application Developer 5.0 CD.
򐂰 Click Next on the first welcome page.
򐂰 On the Choose Product page, select ClearCase LT Server and click Next.
򐂰 In the popup window that is displayed, click OK to install the product without
licensing configured (the license comes with Application Developer 5.0).
򐂰 Select Yes to accept the licensing agreement on the next page and click Next.
򐂰 On the Select Configuration page, select Typical configuration and verify the
install path (we use the default of C:\Program Files\Rational). Click Next.
򐂰 If the Update Shared Components dialog is displayed, click Next.
򐂰 Click Next on the Confirmation dialog to start the installation.
򐂰 When the product is installed, select Restart and then click Finish to reboot
your machine.
򐂰 After the machine has rebooted the installation continues and when done it
displays an Error Summary asking you to associate a license with the
ClearCase LT Server. You do not have to do this so click Next on the Error
Summary page.
򐂰 On the Installation Complete page, click Finish.
򐂰 The ClearCase LT Server Wizard is now displayed. The wizard guides you
through the process of creating a ClearCase storage directory, a ClearCase
VOB and setting up a ClearCase project. On the first page of the wizard click
Next.
򐂰 On the second page, select a directory to store your ClearCase VOB files.
Keep the default and click Next.
򐂰 On the third page, keep the default VOB name sources and deselect the
Import projects. Click Next.
򐂰 On the fourth page, keep the default project name InitialProject and click
Next.
򐂰 On the Summary page, click Next and when the setup is done click OK on the
final dialog.

When you have installed the ClearCase LT server, review the Rational
ClearCase: Upgrades, Patches and Service Releases page on the Rational Web
site and make sure that the latest fixes have been applied. The Web site can be
found at:
http://www.rational.com/support/downloadcenter/upgrades/index.jsp

Chapter 23. Using ClearCase 751


Note: Installing the ClearCase LT Server component also installs the
ClearCase LT Client component so you do not have to install the client
separately on the server machine to access the server.

Installing the ClearCase LT client


To install ClearCase LT Client perform these steps:
򐂰 To start the installation, run setup.exe from the Rational_ClearCase_LT
directory on the Application Developer 5.0 CD.
򐂰 Click Next on the first welcome page.
򐂰 On the Choose Product page, select ClearCase LT Client and click Next.
򐂰 In the popup window that is displayed, click OK to install the product without
licensing configured (the license comes with Application Developer 5.0).
򐂰 Select Yes to accept the licensing agreement on the next page and click Next.
򐂰 On the Select Configuration page, select Typical configuration and verify the
install path (we use the default of C:\Program Files\Rational). Click Next.
򐂰 If the Update Shared Components dialog is displayed, click Next.
򐂰 Click Next in the Confirmation Dialog.
򐂰 On the ClearCase LT Server Name page, enter the host name of the machine
where ClearCase LT Server is installed. Click Next.
򐂰 When the product is installed, select Restart and click Finish to reboot your
machine.
򐂰 After the machine has rebooted, the installation continues and displays the
Installation Complete page. Click Finish.

ClearCase integration with Application Developer


Application Developer integrates support for ClearCase, allowing easy access to
ClearCase features.

Note: The ClearCase Adapter is a feature during Application Developer


installation. It must be installed to make use of ClearCase LT.

752 WebSphere Studio Application Developer Version 5 Programming Guide


ClearCase help in Application Developer
Application Developer provides limited documentation for using ClearCase. To
access the help documentation, select Help -> Help Contents to open the new
help window. Select Rational ClearCase from the Contents view to open the
ClearCase help book (Figure 23-2).

Figure 23-2 ClearCase online help

ClearCase preferences
There are a number of ClearCase preferences that you can modify by selecting
Window -> Preferences -> Team -> Rational ClearCase (Figure 23-3).

We recommend that you check out files from Rational ClearCase before you edit
them. However, if you edit a file that is under ClearCase control but is not
checked out, Application Developer can automatically check it out if you select
Automatically checkout for the setting: When checked-in files are saved by an
internal editor.

You can specify if you want to automatically connect to ClearCase when you
start Application Developer. Select Automatically connect to ClearCase on
startup to enable this option.

Chapter 23. Using ClearCase 753


Figure 23-3 ClearCase preferences dialog

If you click Advanced Options and then select the Operations tab, you can select
if you want ClearCase to generate backup copies of files you perform an undo
check out operation on. The backup copies will have a .keep extension.

Note: You must be connected to ClearCase for the Advanced Options button
to be active.

The ClearCase online help in Application Developer contains a detailed


description about each option of the preferences page.

Using ClearCase with Application Developer


This section describes a scenario with two developers, developer 1 and 2,
working on a Web project called ITSOProGuideCCWeb. Developer 1 is assigned the
role of project integrator and is responsible for setting up the environment.

754 WebSphere Studio Application Developer Version 5 Programming Guide


Developer 1:
򐂰 Creates a new VOB, ITSO_VOB
򐂰 Creates a new ClearCase project, ITSO_Project
򐂰 Joins the ClearCase project by creating views
򐂰 Creates a new Web project, ITSOProGuideCCWeb
򐂰 Moves the project under ClearCase source control
򐂰 Adds a servlet, ServletA
򐂰 Checks in the servlet
򐂰 Delivers the work to the integration stream
򐂰 Makes a baseline

Developer 2:
򐂰 Joins the ClearCase project by creating views
򐂰 Imports the project into Application Developer
򐂰 Adds a servlet, ServletB
򐂰 Checks in the servlet
򐂰 Verifies that no other developers has modified the project by performing a
Rebase preview operation
򐂰 Delivers the work to the integration stream
򐂰 Makes a baseline

Developer 1:
򐂰 Updates his view to get the latest changes

The setup of this scenario and its flow is shown in Figure 23-4. ClearCase
terminology is used for the tasks.

___________________Workstation 1_______________ _____Workstation 2_____

Developer 1 ITSO_VOB Developer 2

dev2_View
dev1_View ITSO_Project

Update ITSO_ Update Deliver


Deliver Rebase Project_ View
View Stream Rebase
Stream Stream Integration
Stream
Baselines
dev2_IntegrationView
dev1_IntegrationView
Make Make
Baseline Baseline

Figure 23-4 Scenario setup

Chapter 23. Using ClearCase 755


Note that the integration view is like a window to the integration stream. The
integration stream should be reserved for only that code that has passed the
developer’s inspection and is sharable to the entire team.

Basically, the developer retrieves the latest version of the code from the VOB to
the integration view by using the ClearCase Update View function. Once this is
done the developer can use the Rebase Stream function to update the
development view and start working with the code.

When finished with the changes, the developer delivers the development stream
back to the integration stream. A project integrator (or any of the developers) can
then make a new baseline freezing the latest code changes.

Setting up ClearCase for a new project


Developer 1 (user ID dev1) works on the machine where the ClearCase LT
Server is installed and developer 2 (dev2) works on the machine where only the
ClearCase LT Client is installed.

Creating a new VOB


As developer 1, select Start -> Programs -> Rational ClearCase LT Server ->
Create VOB. This brings up the VOB Creation Wizard (Figure 23-5). Enter
ITSO_VOB as the VOB name. Then click Finish.

Figure 23-5 Creating new VOB

On the confirmation page, click OK. ClearCase now creates a new VOB. Click
Close on the summary dialog.

756 WebSphere Studio Application Developer Version 5 Programming Guide


Creating new ClearCase project
Developer 1 create a new project under ClearCase control:
򐂰 As developer 1, select Start -> Programs -> Rational ClearCase LT Server ->
Rational ClearCase LT Project Explorer.
򐂰 Select File -> New -> Project. This opens the New Project Wizard
(Figure 23-6). Enter ITSO_Project as the project name and click Next.

Figure 23-6 Creating new project: step 1

򐂰 In the Step 2 dialog (Figure 23-7) make sure that No is selected. Click Next.

Figure 23-7 Creating new project: step 2

Chapter 23. Using ClearCase 757


򐂰 In the Step 3 dialog (Figure 23-8) click Add:
– In the Add Baseline dialog, select the component ITSO_VOB from the
drop-down list and select ITSO_VOB_INITIAL under Baselines.
– Click OK.
򐂰 Click Next.

Figure 23-8 Creating new project: step 3

򐂰 In the Step 4 dialog (Figure 23-9) select ITSO_VOB under Make the following
components modifiable. Leave the other values as their defaults. Click Next.

758 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 23-9 Creating new project: step 4

򐂰 In the Step 5 dialog, select No and click Finish.


򐂰 Click OK on the confirmation dialog. ClearCase now creates the project and it
shows up in the Project Explorer.

Joining a ClearCase project


The next step for developer 1 is to join the project and create a new Web project
in Application Developer.
򐂰 As developer 1, start Application Developer and select ClearCase -> Connect
to Rational ClearCase (unless you specified to automatically connect to
ClearCase when Application Developer starts).
򐂰 Select ClearCase Create -> New View.
򐂰 In the View Creation Wizard (Figure 23-10), select Yes to indicate we are
working on a ClearCase project. Expand projects and select the
ITSO_Project. Click Next.

Chapter 23. Using ClearCase 759


Figure 23-10 Creating a new view

򐂰 In the Create a Development Stream dialog (Figure 23-11) enter dev1_View


as the development stream name and make sure the integration stream name
is ITSO_Project_Integration. Click Next.

Figure 23-11 Creating a development stream

760 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 In the Choose Location for a Snapshot View (Development View) dialog
(Figure 23-12) change the location to C:\ITSO\dev1_View. Click Next and click
Yes on the confirmation dialog.

Figure 23-12 Specifying location for development view

򐂰 In the Choose Location for a Snapshot View (Integration View) dialog


(Figure 23-13) change the location to C:\ITSO\dev1_IntegrationView. Click
Next.

Figure 23-13 Specifying location for integration view

Chapter 23. Using ClearCase 761


򐂰 In the Choose Components dialog, leave the ITSO_VOB selected and make
sure Start component browser after creating view is deselected. Click Finish.
򐂰 In the Confirmation dialog (Figure 23-14) click OK.

Figure 23-14 View creation confirmation dialog

򐂰 In the View Creation Status dialog that is displayed after the views are
created, click OK.

Creating a Web project


Developer 1 has now created necessary views and joined the project. The next
task is to create a Web project and add it to ClearCase control
򐂰 As developer 1, open the Web perspective and select File -> New -> Web
Project. In the Create a Web Project dialog, enter ITSOProGuideCCWeb as
project name and make sure the Use Default location is selected (this is a
directory under the Application Developer workspace and is different from the
ClearCase view locations). Click Next.
򐂰 On the J2EE Settings page, select New and enter ITSOProGuideCCEAR as the
name for the Enterprise application project. Click Finish.

Adding a project to ClearCase source control


To add the new project under ClearCase control:
򐂰 As developer 1, select the ITSOProGuideCCEAR project in the J2EE
Navigator view and select Team -> Share Project from the context menu.
򐂰 In the Share Project dialog, select Rational ClearCase and click Next.

762 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 In the Move Project Into a ClearCase VOB dialog (Figure 23-15) click Browse
and select C:\ITSO\dev1_View\ITSO_VOB. Click OK and then Finish.

Figure 23-15 Moving project into ClearCase

򐂰 In the Add Elements to Source Control (Figure 23-16) leave all items selected
and deselect Keep checked out. Click OK.

Figure 23-16 Specifying elements to add to source control

򐂰 In the Select Activity dialog (Figure 23-17) select New and enter Developer 1
adds project to source control. Click OK to return and then click OK to
continue. The EAR project is now added to ClearCase source control.

Chapter 23. Using ClearCase 763


Figure 23-17 Specifying an activity

򐂰 Select the ITSOProGuideCCWeb project and add this to source control using the
same method (do not create a new activity, use the activity created when
adding the EAR project to source control).
򐂰 Both projects are now under ClearCase source control and their contents has
been moved from the Application Developer workspace (C:\WSAD5sg246957 in
our example) to C:\ITSO\dev1_View\ITSO_VOB.
򐂰 In Figure 23-18 you can see that the icons for the resources now have blue
background. This means that the resources are under ClearCase source
control.

Figure 23-18 Resources under ClearCase source control

764 WebSphere Studio Application Developer Version 5 Programming Guide


Development scenario
To show how to work with ClearCase we use a simple scenario where two
developers work sequentially on a common project.

Developer 1 adds a servlet


Developer 1 defines a servlet in the Web project:
򐂰 As developer 1, select File -> New -> Servlet. Enter itso.cc as the package
name and enter ServletA as the class name. Click Next. Make sure that Add
to web.xml is selected and click Finish.
򐂰 On the Check Out Elements dialog (Figure 23-19) make sure all three files
are selected as shown and click OK.

Figure 23-19 Specifying elements to check out

򐂰 On the Select Activity, select New and enter Developer 1 adds ServletA as
the name for the activity. Click OK twice. The servlet is generated.
򐂰 On the Add Element(s) to Source Control dialog, make sure the packages
and servlet are selected as shown in Figure 23-20. Deselect Keep checked
out and click OK.

Chapter 23. Using ClearCase 765


Figure 23-20 Adding new elements to source control

򐂰 On the Select Activity dialog, select Developer 1 adds ServletA and click OK.
The servlet is added to the project and to ClearCase source control.
򐂰 Click Yes on the File Changed dialog.
򐂰 As we only want to show how to work with ClearCase, we do not need to add
any real code to the servlet so simply enter your name in the author Javadoc
comment. As soon as you start typing in the editor, the servlet needs to be
checked out (it is checked in because we deselected the Keep checked out
option). The dialog shown in Figure 23-21 is displayed asking you to check
out the servlet. Click OK.

Figure 23-21 Check out elements

766 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 On the Select Activity dialog, select Developer 1 adds ServletA and click OK.
The file is now checked out which is indicated by the green check mark on the
servlet’s icon, .
򐂰 After adding your name as the author press Ctrl-S to save the servlet and
then close the editor. This change also updates the web.xml file.
򐂰 The changed files must now be checked in. Select both the itso.cc.ServletA
and the Web Content\WEB-INF\web.xml and select Team -> Check in from the
context menu.
򐂰 On the Check in Elements dialog (Figure 23-22) make sure both elements are
selected and then click OK. The green check marks of the resources icons
are removed indicating that the files are no longer checked out.

Figure 23-22 Checking in elements

򐂰 Before we can deliver the project to the stream, the ibm-web-bnd.xml and
ibm-web.ext.xmi files must be checked in as well. As their contents have not
changed, ClearCase default settings does not allow them to be checked in so
we need to undo their check out. Select both of them and select Team ->
Undo Check Out from the context menu. On the Undo Check Out for
element(s) dialog, make sure both files are selected and then click OK.
򐂰 Before delivering to the stream, it is good practice to make sure that nothing is
checked out. Select ClearCase -> Show Project Checkouts. On the Find
Criteria dialog (Figure 23-23) click Browse and select the
C:\ITSO\dev1_View\ITSO_VOB directory. Keep the other defaults as shown and
click OK.

Chapter 23. Using ClearCase 767


Figure 23-23 Finding checkouts

򐂰 No checked out files should be found. Click OK to dismiss the dialog and then
close the Find Checkouts window.

Developer 1 delivers work to the integration stream


To deliver the work into the integration stream:
򐂰 Select ClearCase -> Deliver Stream. On the Deliver from Stream dialog
(Figure 23-24) select the development stream dev1_View and click OK.

Figure 23-24 Delivering to Integration Stream

768 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 In the Deliver from Stream Preview dialog (Figure 23-25) make sure both
activities are selected and that the view to deliver to is dev1_IntegrationView.
Click OK.

Figure 23-25 Deliver from Stream Preview dialog

򐂰 After a while the Deliver from Stream - Merges Complete dialog


(Figure 23-26) is shown. Deselect Open a ClearCase Explorer and click OK.

Figure 23-26 Deliver from Stream - Merges Complete dialog

򐂰 On the Delivering to View dialog (Figure 23-27) click Complete.

Chapter 23. Using ClearCase 769


Figure 23-27 Delivering to View dialog

򐂰 Optionally you can click Details to see a list of the files delivered
(Figure 23-28), then click Close.

Figure 23-28 Showing files delivered

Developer 1 makes a baseline


To make a baseline:
򐂰 As developer 1, select Start -> Programs -> Rational ClearCase LT Server ->
Rational ClearCase LT Project Explorer.

770 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 In the left pane select ITSO_Project_Integration and select Make Baseline
from the context menu (Figure 23-29).

Figure 23-29 Make baseline

򐂰 In the Make Baseline dialog (Figure 23-30) click OK.

Figure 23-30 Make baseline settings

򐂰 Click OK on the confirmation dialog (1 new baseline was created) and then
close the Make Baseline dialog.
򐂰 You can now close the ClearCase Project Explorer. Developer 1 has now
finished his current task and developer 2 will now join the project and add a
servlet.

Chapter 23. Using ClearCase 771


Developer 2 joins the project
Developer 2 now joins the ClearCase project and adds it to his Application
Developers workspace.
򐂰 As developer 2, select ClearCase -> Connect to Rational ClearCase in
Application Developer.
򐂰 Create a new view by selecting ClearCase -> Create New View. In the View
Creation Wizard dialog (Figure 23-31) select Yes and select the ITSO_Project
and click Next.

Figure 23-31 View Creation View - Choose a Project

򐂰 In the Create a Development Stream dialog (Figure 23-32) enter dev2_View


as the name of the development stream and make sure that
ITSO_Project_Integration is selected as the integration stream. Click Next.

772 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 23-32 Creating a development stream for developer 2

򐂰 In the Choose Location for a Snapshot View (Development View) dialog


(Figure 23-33) enter C:\ITSO\dev2_View as the path for the new development
view and click Next.

Figure 23-33 Select location for development view

Chapter 23. Using ClearCase 773


򐂰 In the Choose Location for Snapshot view (Integration View) dialog
(Figure 23-34) select C:\ITSO\dev2_IntegrationView as the location for the
integration view. Click Next.

Figure 23-34 Select location for integration view

򐂰 In the Choose Components dialog, make sure ITSO_VOB is selected and


click Finish to create the views.
򐂰 Click OK when the confirmation dialog is displayed and then click OK in the
View Creation Status dialog.

Developer 2 imports projects into Application Developer


Developer 2 works on the same projects as developer 1 and has to import the
projects:
򐂰 As developer 2, select ClearCase -> Rebase Stream in Application Developer
to update your development stream with the contents of the integration
stream.
򐂰 In the Rebase Stream dialog (Figure 23-35) select Projects -> ITSO_Project
-> ITSO_Project_Integration -> dev2_View and click OK.

774 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 23-35 Rebase Stream dialog

򐂰 In the Rebase Stream Preview dialog (Figure 23-36) select


ITSO_VOB ITSO_Project_<date> from the baseline drop-down list and verify
that dev2_View is selected as the target view. Click OK.

Figure 23-36 Rebase Stream Preview - developer 2

򐂰 Click OK to dismiss the Hijacked Files Warning dialog. The contents of the
integration view is now copied to the developer 2’ development view.
򐂰 In the Rebasing in View dialog, click Complete to perform the rebase action.
After this click Close.
򐂰 In Application Developer, select File -> Import -> Existing Project into
Workspace and click Next (Figure 23-37).
򐂰 Click Browse and select the EAR project and click Finish.
C:\ITSO\dev2_View\ITSO_VOB\ITSOProGuideCCEAR

Chapter 23. Using ClearCase 775


Figure 23-37 Import EAR project

򐂰 Repeat the import process for the Web project:


C:\ITSO\dev2_View\ITSO_VOB\ITSOProGuideCCWeb

Note: By now developer 1 and developer 2 are setup with a new shared
project. Both can now check out files, work with these files, check them in, and
deliver their work to the stream.

Developer 2 adds a new servlet


Here are the short instructions for developer 2:
򐂰 Open the Web perspective and select File -> New -> Servlet. Enter itso.cc
as the package name and enter ServletB as the class name. Click Next.
򐂰 Verify that Add to web.xml is selected and click Finish.
򐂰 On the Check Out Elements dialog, make sure all three files are selected and
click OK.
򐂰 On the Select Activity click New and enter Developer 2 adds ServletB as the
name for the activity. Click OK twice. The servlet is being generated.
򐂰 On the Add Element(s) to Source Control dialog, make sure the servlet is
selected. Deselect Keep checked out and click OK.
򐂰 On the Select Activity dialog, select the Developer 2 adds ServletB activity
and click OK. The servlet is added to the project and to ClearCase source
control.
򐂰 Click Yes on the File Changed dialog.
򐂰 Add your name in the author Javadoc comment. As soon as you start typing
in the editor the servlet needs to be checked out (it is checked in because we

776 WebSphere Studio Application Developer Version 5 Programming Guide


deselected the Keep checked out option). Click OK on the Check Out
Elements dialog.
򐂰 On the Select Activity dialog, select the Developer 2 adds ServletB activity
and click OK. The file is now checked out which is indicated by the green
check mark on the servlet’s icon, .
򐂰 After adding your name as the author press Ctrl-S to save the servlet and
then close the editor. This change also updates the web.xml file.
򐂰 The changed files must now be checked in. Select both the itso.cc.ServletB
and the Web Content\WEB-INF\web.xml and select Team -> Check in
(context).
򐂰 On the Check in Elements dialog, make sure both elements are selected and
click OK. The green check marks of the resources icons are removed
indicating that the files are no longer checked out.
򐂰 Before developer 2 can deliver the project to the stream the ibm-web-bnd.xml
and ibm-web.ext.xmi files need to be checked in as well. As their contents
have not changed, ClearCase default settings does not allow them to be
checked in, so we need to undo their check out. Select both of them and
select Team -> Undo Check Out from the context menu. On the Undo Check
Out for Element(s) dialog, make sure both files are selected and click OK.

Developer 2 is now ready to deliver the changes to the stream and share the
code with the other developers. Before doing this, it is best practice to make sure
that no other developer has made changes.
򐂰 Select ClearCase -> Rebase Stream. In the Rebase Stream dialog, select
developer 2’s development stream as shown and click OK (Figure 23-38).

Figure 23-38 Selecting development stream to rebase

򐂰 In the Rebase Stream Preview dialog (Figure 23-39) make sure the
dev2_View view is selected, otherwise click Change -> Browse and select it.
Click OK.

Chapter 23. Using ClearCase 777


Figure 23-39 Rebase Stream Preview

򐂰 The Rebase Stream dialog is displayed and notifies you that the stream is
currently up-to-date. Click OK to dismiss the information dialog and click
Cancel to dismiss the Rebase Stream Preview dialog.

Note that what we did was to check to make sure developer 1 did not make any
changes to the stream.

Developer 2 delivers work to the integration stream


Developer 2 is ready to integrate the work:
򐂰 As developer 2, select ClearCase -> Deliver Stream. In the Deliver from
Stream dialog (Figure 23-40) select Projects -> ITSO_Project ->
ITSO_Project_Integration -> dev2_View. Click OK.

Figure 23-40 Deliver from Stream dialog

򐂰 On the Deliver from Stream Preview dialog (Figure 23-41) make sure the
dev2_IntegrationView is selected as the integration view. Click OK.

778 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 23-41 Deliver from Stream Preview

򐂰 The integration view is now updated with the contents of the development
view. In the Deliver from Stream - Merges Complete dialog, deselect Open a
ClearCase Explorer window.... and click OK.
򐂰 On the Delivering to View dialog, click Complete and then Close.

Developer 2 makes a new baseline


To make a new baseline:
򐂰 As developer 2, select Start -> Programs -> Rational ClearCase LT Client ->
Rational ClearCase LT Project Explorer.
򐂰 In the left pane select ITSO_Project_Integration and select Make Baseline
from the context menu.
򐂰 In the Make Baseline dialog, change the name of the baseline to
ITSO_Project_<date>-2 and click OK.
򐂰 Click OK on the confirmation dialog (1 new baseline was created) and then
close the Make Baseline dialog. Close the ClearCase Project Explorer.

Developers synchronize
Developer 2 has now finished his current task and developer 1 can now catch up
with the latest changes made by developer 2:
򐂰 As developer 1, connect to ClearCase
򐂰 Select ClearCase -> Update View.

Chapter 23. Using ClearCase 779


򐂰 On the Start Update dialog (Figure 23-42) select dev1_IntegrationView and
click OK.

Figure 23-42 Selecting view to update

򐂰 On the Snapshot View Update dialog (Figure 23-43) select Changed in the
left pane. The right pane changes and displays all the changed files.

Figure 23-43 Snapshot view update dialog

򐂰 In the right pane select web.xml and select Show Version Tree from its context
menu. This displays the Version Tree Browser as shown in Figure 23-44. This
window shows the version history for this file.

780 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 23-44 Version tree browser

򐂰 Close the Version Tree Browser and then close the Snapshot View Update
window. Click OK to dismiss the Save Update dialog.
The integration view is now updated with the latest changes made to the
integration stream. Before developer 1 can continue working his development
view needs to be refreshed.
򐂰 Select ClearCase -> Rebase Stream. From the Rebase Stream dialog, select
Projects -> ITSO_Project -> ITSO_Project_Integration -> dev1_View and click
OK.
򐂰 In the Rebase Stream Preview dialog (Figure 23-45) select the new baseline,
ITSO_VOB ITSO_Project_<date>-2, from the baseline drop-down list and
make sure the dev1_View is selected as the target view. Click OK.

Figure 23-45 Rebase Stream Preview - developer 1

򐂰 Click OK to dismiss the Hijacked Files Warning dialog. The contents of the
integration view is now copied to developer 1’s development view.

Chapter 23. Using ClearCase 781


򐂰 On the Rebase Stream - Merges Complete dialog, click OK.
򐂰 On the Rebasing in View dialog, click Complete and then click Close.
򐂰 To refresh Application Developer’s view, select the ITSOProGuideCCWeb
project and select Refresh from its context menu. The screen should now
show both ServletA and ServletB as in Figure 23-46.

Figure 23-46 Developer 1 Workbench updated

Summary
In this chapter we have shown you a very basic scenario with two developers
working on a common Web project.

One of the developers set up the initial environment, added a servlet, delivered
the development stream to the shared integration stream, and made a new
baseline.

The second developer then joined the project, imported its contents into the own
workspace, added a second servlet, delivered the contents to the integration
stream, and made a new baseline.

Developer 1 then retrieved the latest changes into the workspace.

782 WebSphere Studio Application Developer Version 5 Programming Guide


Part 6

Part 6 Appendixes
This part of the book includes the following supplementary information:
򐂰 Appendix A, “Product installation” on page 785
򐂰 Appendix B, “Keyboard shortcuts” on page 801
򐂰 Appendix C, “Additional material” on page 809

© Copyright IBM Corp. 2003. All rights reserved. 783


784 WebSphere Studio Application Developer Version 5 Programming Guide
A

Appendix A. Product installation


In this appendix we describe how to install Application Developer and
WebSphere Application Server. The installation instructions specifically apply to
Version 5.0, but also should be very similar for more recent versions of the
product.

The following topics are covered:


򐂰 Installing DB2 UDB
򐂰 Installing WebSphere Application Server
򐂰 Installing Application Developer
򐂰 Update Application Developer

© Copyright IBM Corp. 2003. All rights reserved. 785


Installing DB2 UDB
To run our samples, you require a relational database system. All our testing was
done with DB2 UDB Version 7.2 Fix Pack 7.

Although it may be possible to run most of the examples with another relational
database system, we only tested the examples with DB2 UDB.

Installing DB2 UDB Version 7.2 is straight forward. Just follow the installation
panels. You do not have to install all of the components, such as data
warehousing and performance tools.

The suggested installation directory is C:\SQLLIB.

After the base installation, you have to install Fix Pack 7 or later.

Also, it is required that you run the command file java12\usejdbc2.bat which is
located in the installation directory of DB2 (usually SQLLIB) to enable the JDBC
Version 2 support for data sources. This is not required if you use DB2 Version
8.1.

Installing WebSphere Application Server


This section describes how to install WebSphere Application Server.

Hardware prerequisites
Hardware requirements include:
򐂰 Any Intel®-based PC running Windows NT® Server V4.0, SP 6a or later,
Windows 2000 Server, or Advanced Server SP 2
򐂰 Intel Pentium® processor at 500 MHz, or faster
򐂰 Minimum 180 MB free disk space for installation (includes SDK)
򐂰 Minimum 384 MB memory; 512 MB recommended

Software prerequisites
The installation requires the following software to be installed:
򐂰 Windows NT Server or Windows 2000 Server
򐂰 Netscape Communicator 4.7.9 or Microsoft Internet Explorer 5.5 SP 2 and 6.0
򐂰 Web browser that supports HTML 4 and CSS

786 WebSphere Studio Application Developer Version 5 Programming Guide


For updated information about the hardware and software requirements please
refer to WebSphere Version 5 InfoCenter.

For the WebSphere installation, the database does not have to be configured.
Cloudscape can be used in test environment, however, other databases are
required for the production environment. The following databases are supported
with WebSphere Application Server V5 and WebSphere Network Deployment V5
on Windows platforms:
򐂰 Cloudscape 5.06
򐂰 DB2 UDB V7.2 Fixpack 7
򐂰 Informix Dynamic Server Versions 7.31 and 9.3
򐂰 Oracle Enterprise Edition 8i Release 3 (8.1.7)
򐂰 Oracle Enterprise Edition 9i Release 2 (9.2)
򐂰 SQL Server Enterprise 7.0 SP 4 and 2000 SP 2

IBM HTTP Server is bundled with base WebSphere Application Server V5.
However, the following HTTP servers can also be installed and configured to
work with WAS V5:
򐂰 Apache Server 1.3.26
򐂰 HTTP Server 1.3.26 AIX, Linux/390, Linux/Intel, NT
򐂰 Internet Information Server 4.0
򐂰 Sun ONE Web Server, Enterprise Edition (formerly iPlanet) 6.0 SP 4
򐂰 Lotus Domino™ Enterprise Server (as HTTP Server) 5.0.9a

Before we start the installation we also have to create the user with
administrative rights on the local machine.

Installation Application Server 5.0


The Install Shield Multi Platform (ISMP) is a new installer that is used to install
the product on Intel, AIX, Linux, Linux/390, and Solaris. It checks the installation
prerequisites. It also generates the uninstall program after the product has been
completely installed.

The administrative database of WebSphere Version 4 does not exist any longer.
All of the configuration information for the WebSphere Application Server Version
5 is now contained in XML files in the ${WAS_ROOT}\config directory. There are
many files that contain all the configuration information.

Appendix A. Product installation 787


Installation process
First we start the LaunchPad (launchpad.bat) to access the product overview,
the ReadMe file, and installation guides.
򐂰 Select Install the product to launch the installation wizard (Figure A-1).

Figure A-1 WebSphere Application Server LaunchPad

򐂰 In the first dialog panel, select the language and click OK.
򐂰 Click Next in the Welcome panel.
򐂰 After confirming that we agree with the licence agreement, we have to choose
between two installation choices: Typical and Custom. Choosing Typical
installs the entire product, whereas the Custom installation option allows you
to deselect components you do not want to install. We chose the Typical
installation.
򐂰 The installation directories for the selected components are entered in the
next panel. We chose:
C:\WebSphere\AppServer
C:\IBMHttpServer
C:\WebSphere MQ

788 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 In the following panel we enter a node name and host name or IP address. In
addition, we can select to install both WebSphere Application Server and IBM
HTTP Server as a service on NT or Windows 2000.
򐂰 After the Summary window, the installation starts.
򐂰 The FirstSteps dialog is started automatically at the end of the installation.

Verifying the installation


Installation verification can be started from the menu. In Windows 2000, select
Start -> IBM WebSphere -> Application Server v5.0 -> First Steps. Then select
Verify Installation. We can also start the command ivc localhost.

If the install was successful, you should see messages similar to the following:
OS: Windows 2000
locale: en_US
hostname: NODENAME
cmd.exe /c "C:\WebSphere\AppServer\bin\ivt" NODENAME 9080
C:\WebSphere\AppServer
IVT0006I: Connecting to the WebSphere Server NODENAME on Port:9080
IVT0007I:WebSphere Server NODENAME is running on Port:9080
IVT0060I: Servlet Engine Verification: Passed
IVT0065I: JSP Verification: Passed
IVT0066I: EJB Verification: Passed
IVT00100I: IVT Verification Succeeded
IVT0015I: Scanning the file
C:\WebSphere\AppServer\logs\server1\SystemOut.log for
errors and warnings
IVT0020I: 0 Errors/Warnings were detected in the file
C:\WebSphere\AppServer\logs\server1\SystemOut.log
IVT0110I: Installation Verification is complete.

Appendix A. Product installation 789


Installing Application Developer
Before you proceed with installation, please verify that your hardware and
software configurations meet the following prerequisites.

Note: Refer to the Migration Guide (these are the migrate.html and
migrate.pdf files in Application Developers installation directory) for
information on how to migrate from VisualAge for Java, WebSphere Studio,
and previous versions of Application Developer.

Hardware prerequisites
򐂰 Intel Pentium II processor minimum (Pentium III 500 MHz or higher is
recommended)
򐂰 512 MB RAM minimum (768 MB RAM is recommended)
򐂰 Disk space: You will require 940 MB minimum disk space for installing
Application Developer and additional disk space for your development
resources. Minimum disk space can be reduced if optional features and
run-time environments are not installed
򐂰 In addition to the space required to install the product, you must have at least
50 MB free on your Windows system drive, and your environment variable
TEMP or TMP must point to a valid temporary directory with at least 10 MB
free
򐂰 Note that you also require additional disk space if you download the electronic
image to install Application Developer
򐂰 Display resolution: 800 x 600 pixels minimum (1024 x 768 recommended)

Software prerequisites
The following software must be installed before you install WebSphere Studio
Application Developer:
򐂰 One of the following operating systems:
– Windows 2000 Professional with Service Pack 2 or higher
– Windows XP Professional
– Windows NT Workstation or Server Version 4.0 with Service Pack 6a
– Red Hat, Version 7.2
– SuSE, Version 7.2
򐂰 A Web browser to view the license agreements and the online help for the
WebSphere Studio Installation Launcher

790 WebSphere Studio Application Developer Version 5 Programming Guide


Note: If you had Application Developer Version 4.0 installed and you
downloaded and installed any third-party plug-ins, you need to get the
corresponding plug-ins for Version 5 and reinstall them.

For information about supported database servers, Web application servers, and
other software products, see the readme and the install files located in the root
of the installation CD directory.

Note: If you have VisualAge for Java or any version of WebSphere Studio
already installed, there is no need to un-install it before installing Application
Developer. You can install Application Developer 5 in a separate directory, but
do not install this version of Application Developer over an earlier version.

Installing Application Developer


Application Developer’s installation routine can be started from CD-ROM or the
folder where the setup.exe file is located. To install the product, log in as an
administrator and perform the following steps:
򐂰 Double-click setup.exe and the Installation Launcher dialog appears
(Figure A-2).

1. Install Application
Developer
2. Install IBM Agent
Controller
3. Embedded
messaging not
required for the
samples

Figure A-2 Application Developer Installation dialog

򐂰 Select Install IBM WebSphere Studio Application Developer.

Appendix A. Product installation 791


򐂰 In the Welcome page, click Next.
򐂰 In the Licence Agreement page, accept the agreement and click Next.
򐂰 In the Destination Folder page, select a folder of your choice and then click
Next. We installed the product into C:\WSAD5.
򐂰 In the Custom Setup page, select the ClearCase Adapter if you want to use
ClearCase LT, otherwise accept the defaults, and click Next.
򐂰 In the Ready to Install the Program page, click Install.
򐂰 When the wizard completes, click Finish.
򐂰 Start Application Developer. When prompted, specify the location of the
workspace (we used c:\WSAD5sg246957).
򐂰 You might want to install the IBM Agent Controller; it is required for profiling
and publishing to a remote server.

Installing the Agent Controller


You have to install the IBM Agent Controller on every machine where you want to
define remote WebSphere servers or perform profiling.

Select Install IBM Agent Controller from the WebSphere Studio Installation
Launcher (Figure A-2). For Windows you can also run the setup.exe from the
IBM_Agent_Controller\windows directory on the CD. In the installation dialog (for
Windows):
򐂰 Accept the license.
򐂰 Enter user name and organization.
򐂰 Select the installation directory. The default is:
C:\Program Files\IBM\IBM Agent Controller
򐂰 Select the Java runtime library, for example:
<wsadhome>\eclipse\jre\bin
򐂰 Select to enable or disable security. If you enable security, you have to prove
the user IDs of authorized users
򐂰 Select which host computers can access the Agent Controller:
– This computer only
– Any computer
– Specific computers: you provide a list of host names
򐂰 Start the installation.

The Agent Controller service is started automatically after installation.

792 WebSphere Studio Application Developer Version 5 Programming Guide


Update Application Developer
This section demonstrates how to search for updates and how to install updates
for Eclipse and Application Developer.

Using the Update Manager


Application Developer contains an Update Manager. The update manager can be
used to discover, download, and install updated features and plug-ins from
special web-based update sites.

The basic underlying mechanism of the update manager is simple:


򐂰 The files for a feature or plug-in are always stored in a subdirectory whose
name includes a version identifier (for example, 2.0.0).
򐂰 Different versions of a feature or plug-in are always given different version
identifiers, thereby ensuring that the multiple versions of the same feature or
plug-in can co-exist on disk.
򐂰 This means that installing or updating features and plug-ins requires adding
more files, but never requires deleting or overwriting existing files.
򐂰 Once the files are installed on the local computer, the new feature and plug-in
versions are available to be configured.
򐂰 The same installed base of files is therefore capable of supporting many
different configurations simultaneously. Installing and upgrading an existing
product are reduced to formulating a configuration incrementally newer than
the current one.
򐂰 Important configurations can be saved and restored to active service in the
event of an unsuccessful upgrade.

You can launch the update manager by selecting Help -> Software Updates ->
Update Manager from the menu bar. This opens the Install/Update perspective.
Note, that you can also open the perspective Install/Update directly.

The initial Install/Update perspective is shown in Figure A-3.

Note: A detailed description about the Install/Update perspective and its views
is provided in the section “Install/Update perspective” on page 75.

Appendix A. Product installation 793


Figure A-3 Update Manager

Click the Feature Updates link in the Feature Updates section of the welcome
page to launch the search site. Figure A-4 shows the search page.

Figure A-4 Search - Available Update page

794 WebSphere Studio Application Developer Version 5 Programming Guide


You can set some query settings and specify the scope of your search on this
page. Click Search Now to trigger the search. Once the search has been
finished, you should check the Feature Search Results view at the bottom of the
Workbench. Figure A-5 shows this view which displays two updates for
Application Developer.

Available Updates:
install in this sequence

Figure A-5 Feature Search Results

Select the update you would like to install from the list. Note that the Preview
view changes and displays detailed information regarding the selected update.
This is shown in Figure A-6.

Click here to
start the update

Figure A-6 Update Preview

Click the link More Info to open a document which provides more details about
the update. Click Update to launch the update.

Appendix A. Product installation 795


Figure A-7 shows the Feature Install dialog.

Figure A-7 Feature Install dialog

Click Next, to bring up the License Agreement dialog up. Carefully review the
license agreements for the upgraded features. If the terms of all these licenses
are acceptable, check I accept the terms in the license agreements and click
Next again, to continue the installation.

Another dialog named Optional Features might come up if the update lets you
choose the components you want to install (Figure A-8).

796 WebSphere Studio Application Developer Version 5 Programming Guide


Figure A-8 Optional Features dialog

Select the components you want to install and click Next. The Install Location
dialog comes up as shown in Figure A-9.

Figure A-9 Install Location dialog

Appendix A. Product installation 797


Application Developer determines its installation location and suggests it in the
location dialog. Click Finish to start the update.

Note: While the update is launched, there might another dialog be displayed,
which shows a warning that the feature has not been digitally signed. To
continue the installation process, confirm this dialog with Install.

When the update installation has finished, a dialog comes up which asks, if you
want to restart the Workbench (Figure A-10). It is always recommended to restart
the Workbench after installing an update. Clicking Yes saves the workspace,
closes it and restarts Application Developer.

Figure A-10 Restart Workbench dialog

Once you have installed an update and restarted the Workbench a page comes
up which provides you information about the new update.

Note: You can revert to a previous configuration of installed feature versions


by selecting the appropriate Configuration History tree in the Install
Configuration view and click Revert in the Preview view.

Manual update
To install fixes and updates without the Update Manager, download the
appropriate file from the Application Developer’s support web site:
http://www.ibm.com/software/awdtools/studioappdev/support/

Once you have download the update file, consult the installation instructions for
how to perform your update. Note that the Workbench should not be running
while the updates are being installed.

798 WebSphere Studio Application Developer Version 5 Programming Guide


Note: If you download the latest update from IBM's support site, you receive a
ZIP file (80 MB). To install this update, you have to extract the ZIP file, start
Application Developer, and switch to the Install/Update perspective.

In the Feature Update view, select the update by expanding the “My
Computer” tree to the folder where you have unzipped the package and click
Update in the Preview view. Then follow the instructions on the screen.

There is an install.html file that describes (in detail with screenshots) how to
install the downloaded update or PTF.

Appendix A. Product installation 799


800 WebSphere Studio Application Developer Version 5 Programming Guide
B

Appendix B. Keyboard shortcuts


Application Developer, to a large extent, can be controlled using the keyboard
only. This appendix lists the most commonly used keyboard shortcuts (for a
complete listing of all shortcuts available, open the Application Developer Help
system and search for keyboard shortcuts).

© Copyright IBM Corp. 2003. All rights reserved. 801


Workbench shortcuts
Table B-1 Common Workbench shortcuts
Key Key by itself Ctrl+Key Ctrl+Shift+Key

B Rebuild All

F1 Context-sensitive Help Context-sensitive Help Context-sensitive Help

F2 Rename (Navigator
view)

F4 File > Close File > Close All

F5 Refresh (Navigator and Refresh (Navigator


Properties view) view)

F6 Next editor Previous editor

F7 Next view Previous view

F8 Next perspective Previous perspective

F10 Show options for current Show context-sensitive


view menu for the view

F12 Activate editor

Editing shortcuts
Table B-2 Keyboard shortcuts for editing
Key Ctrl+Key Ctrl+Shift+Key

A Edit > Select All

C Edit > Copy

E Edit > Delete Line Edit > Delete Line to the End

F Edit > Find > Replace

H Edit > Search

I Indent highlighted text

J Edit > Incremental Find

K Edit > Find Next Edit > Find Previous

L Edit > Go to Line

802 WebSphere Studio Application Developer Version 5 Programming Guide


Key Ctrl+Key Ctrl+Shift+Key

N File > New > Other

P File > Print

S File > Save File > Save All

V Edit > Paste

W Edit > Show Rulers

X Edit > Cut

Y Edit > Redo

Z Edit > Undo

Period (.) Next problem

Comma (,) Previous problem

Java editor shortcuts


Table B-3 Java editor shortcuts using Ctrl modifier
Key Ctrl+Key Ctrl+Shift+Key

E Next problem Previous problem

F Format

G Search for declarations in workspace Search for references in workspace

H Open type in hierarchy

M Add import

O Organize imports

Space Content assist Parameter hints

Table B-4 Java editor shortcuts using Alt modifier


Key Ctrl+Key Alt+Key Alt+Shift+Key

Period (.) Navigate > Next

Comma (,) Navigate >


Previous

Appendix B. Keyboard shortcuts 803


Key Ctrl+Key Alt+Key Alt+Shift+Key

Front slash (/) Comment Content assist


(simplified
Chinese)

Back slash (\) Uncomment

Question mark (?) Parameter hints


(simplified
Chinese)

Left arrow Expand selection


to previous element

Right arrow Expand selection


to next element

Up arrow Expand selection


to enclosing
element

Down arrow Expand selection


to last element

1 Quick fix

Java development tools shortcuts


Table B-5 Java development tools shortcuts
Key Key by itself Shift+Key Ctrl+Shift+Key

F2 Show Javadoc Open external


Javadoc

F3 Open on selection

F4 Open type
hierarchy

T Open type

Y Refactor > Redo

Z Refactor > Undo

804 WebSphere Studio Application Developer Version 5 Programming Guide


Debug perspective shortcuts
Table B-6 Debug perspective shortcuts
Key Key by itself Ctrl+Key Ctrl+Shift+Key

B Add/Remove
breakpoint

D Display

Q Inspect

R Run to Line

U Run snippet

F5 Step into

F6 Step over

F7 Run to return

F8 Resume

F9 Relaunch last

F11 Run > Debug Last Run > Run Last


Launched Launched

Page and CSS Designer shortcuts


Table B-7 Page and CSS Designer shortcuts
Key Ctrl+Key Ctrl+Shift+Key Alt+Shift+Ke Ctrl+Alt+Key
y

A Add Column to
Left

B Bold

C Select Column

D Remove Tag Add Column to Design Page


Right (toggle)

E Align Horizontal
Center

G Insert Image

Appendix B. Keyboard shortcuts 805


Key Ctrl+Key Ctrl+Shift+Key Alt+Shift+Ke Ctrl+Alt+Key
y

I Italic

L Align Left

O Insert Form

P Preview Page
(toggle)

Q Link Add Row


Above

R Align Right Select Row

S Source Page
(toggle)

T Insert Table

U Underline

Z Add Row Below

Space Insert
Non-breaking
Space (&nbsp;)

Enter Insert Line Attributes


Break

Left arrow Previous Word Join Cell with


Cell on Left

Right arrow Next Word Join Cell with Split Cell into
Cell on Right Columns

Up arrow Focus Hierarchy Join Cell with


Up Cell Above

Down arrow Focus Hierarchy Join Cell with Split Cell into
Down Cell Below Rows

0 Insert Paragraph

1 Insert Heading 1

2 Insert Heading 2

3 Insert Heading 3

4 Insert Heading 4

806 WebSphere Studio Application Developer Version 5 Programming Guide


Key Ctrl+Key Ctrl+Shift+Key Alt+Shift+Ke Ctrl+Alt+Key
y

5 Insert Heading 5

6 Insert Heading 6

Page Designer source page shortcuts


Table B-8 Page Designer source page shortcuts
Key Ctrl+Key Ctrl+Shift+Key

C Cleanup Document

F Format Document

M Insert line separator

W Source page line number field Switch to editor


context menu appears

Space Content assist

Appendix B. Keyboard shortcuts 807


808 WebSphere Studio Application Developer Version 5 Programming Guide
C

Appendix C. Additional material


This redbook refers to additional material that can be downloaded from the
Internet as described below.

Locating the Web material


The Web material associated with this redbook is available in softcopy on the
Internet from the IBM Redbooks Web server. Point your Web browser to:
ftp://www.redbooks.ibm.com/redbooks/SG246957

Alternatively, you can go to the IBM Redbooks Web site at:


ibm.com/redbooks

Select the Additional materials and open the directory that corresponds with
the redbook form number, SG24-6957.

© Copyright IBM Corp. 2003. All rights reserved. 809


Using the Web material
The additional Web material that accompanies this redbook includes the
following files:
File name Description
sg246957code.zip Sample code for following the EJB samples throughout
the book
corrections.txt Corrections to the book after publishing

System requirements for downloading the Web material


The following system configuration is recommended:
Hard disk space 3 GB
Operating System Windows 2000 or Windows NT
Processor 700 MHz or better
Memory 512 MB, recommended 784 MB

How to use the Web material


Unzip the contents of the Web material sg246957code.zip file onto your hard
drive. This creates a folder structure c:\SG246957\sampcode\xxxx, where
xxxxx refers to a chapter in the book:
_setup Create the EJBBANK database
dev-java Java development
dev-db Database development
dev-web Web application development
dev-webdb Web application with database development
dev-proc Applications with stored procedures
dev-struts Web application using the Struts framework
dev-xml XML development
dev-ejb EJB development
dev-webserv Web services development
dev-visual GUI development
test-junit JUnit and component test
deploy-app Application deployment
deploy-ant Building applications with Ant
zSolution Exported EAR, WAR, JAR files for all projects

810 WebSphere Studio Application Developer Version 5 Programming Guide


Installing the EJBBANK database
The _setup directory contains the definitions and sample data for the database
that is being used in all the examples. To set up the database you must have
DB2 Version 7.2 or Version 8.1 installed. We only tested the samples with
Version 7.2, but they should work with Version 8.1 as well. Use either the
DB2V7.2 or the DB2V8.1 subdirectory (the name of the command line processor
has changed and the .bat files are different).

To set up the database, perform these steps:


򐂰 Run the createbank.bat file. This defines the EJBBANK database and tables.
򐂰 Run the loadbank.bat file to load sample data into the tables. You can rerun
this file at any time to reset the sample data to its original state.
򐂰 Optionally run the listbank.bat file to list the data.

EJBBANK database
The EJBBANK database is the same as is used in the IBM Redbook EJB 2.0
Development with WebSphere Studio Application Developer, SG24-6819. For
details about the data model and content, refer to Chapter 10, “Introducing and
preparing for the sample application” in that redbook.

In this document we are only using a subset of the tables:


򐂰 Customer—Bank customers with customer ID, title, first name, last name,
user ID, and password. There is also an address column that we do not use.
򐂰 Account —Bank account with account ID, balance, interest rate, and account
type (CHECKING or SAVINGS). The additional columns are not used.
򐂰 TransRecord—Transaction records for banking transactions performed on an
account. The columns are transaction ID (a timestamp), account ID (foreign
key to the account table), transaction type (C for credit and D for debit), and
transaction amount.
򐂰 CustAcct—Many-to-many relationship table between customer and account,
with two foreign key columns, customer ID and account ID.

Appendix C. Additional material 811


Installing the ItsoProGuide.ear file
The files in the zSolution directory can be used to load all the code into
Application Developer instead of developing the sample step-by-step.

To import the ItsoProGuide EAR file do the following:


򐂰 Select File -> Import and select EAR file as import source. Then browse to the
\sg246957\sampcode\zSolution\ItsoProGuide.ear and select it. As project
name, enter ItsoProGuide (Figure C-1).
If you already have worked on the ItsoProGuide projects, select Overwrite
existing resources without warning.
Click Next.

Figure C-1 Importing the solution EAR file

򐂰 On the next page (Figure C-2) select Create a new Java project defined as a
utility JAR or web library. This creates the ItsoProGuideJava project that is
used as a utility JAR file in other projects.
Click Next and go through the remaining pages (Figure C-3), but do not
modify anything, or click Finish now.

812 WebSphere Studio Application Developer Version 5 Programming Guide


Figure C-2 Specifying import settings

Figure C-3 Specify module and classpath information

Appendix C. Additional material 813


Fixing the classpath errors
Several errors are reported in the Tasks view. To fix the errors:
򐂰 Two Web projects (ItsoProGuideWebServ and ItsoProGuideWebServClient)
have errors because the SOAP runtime is missing.
Select the Web project and Properties. Select Java Build Path. On the
Libraries page, click Add Variable. Select SOAPJAR and click OK. Click OK to
close the Properties window and the errors should disappear.
򐂰 The XML project (ItsoProGuideXmlWeb) shows errors as well. Open the
properties and add the three variables XERCES, XMLPARSERAPIS, and XSDBEANS
to the Java build path.

Installing the server


To install a WebSphere Version 5 test server with a valid configuration:
򐂰 Create a server project named ItsoProGuideServers.
򐂰 Select the new project and Import -> Zip file. Browse to the
\sg246957\sampcode\zSolutions\ItsoProGuideServers.zip file and import it
into the ItsoProGuideServers project.
򐂰 Two servers appear in the Server Configuration view:
– ItsoServer—built-in WebSphere server
– WebSphere v5.0 on vertex (Copy)—a sample remote WebSphere server
򐂰 You can use the ItsoServer to test the ItsoProGuide enterprise application.
򐂰 You can configure the WebSphere v5.0 on vertex (Copy) server for a remote
machine that has WebSphere Application Server installed. You also have to
configure the remote file transfer instance, vertex-copy.rft, in the
ItsoProGuideServers project.

Installing other projects


Use the JAR or WAR file to import a single project into the workbench.

DB2 user ID and password


You may have to modify the DB user ID and/or password in:
򐂰 ItsoProGuideJava and ItsoProGuideJUnit: CustomerListingNet
򐂰 ItsoProGuideDatabaseWeb: TestDBBeans.jsp, deployment descriptor init
parameters for ListCreditMasterView and ListCreditDetailsView
򐂰 ItsoProGuideStoredProcWeb: GetCustomerBean
򐂰 Authentication alias in WebSphere v5.0 vertex server configuration

814 WebSphere Studio Application Developer Version 5 Programming Guide


Abbreviations and acronyms
AAT application assembly tool J2EE Java 2 Enterprise Edition
API application programming JAAS Java Authentication and
interface Authorization Services
BMP bean-managed persistence JAF Java Activation Framework
BMT bean-managed transactions JAR Java archive
CICS Customer Information Control JDBC Java Database Connectivity
System JDK Java Developer’s Kit
CMP container-managed JMS Java Messaging Service
persistence
JNDI Java Naming and Directory
CMR container-managed Interface
relationships
JSP JavaServer Pages
CMT container-managed
transactions JTA JavaTransaction API
DBMS database management JTS Java Transaction Service
system JVM Java Virtual Machine
DOM document object model LDAP lightweight directory access
EAR enterprise application archive protocol
EIS enterprise information system LTPA lightweight third-party
authentication
EJB Enterprise JavaBeans
MDB message-driven bean
EJB QL EJB query language
MVC model-view-controller
EJS Enterprise Java Server
OMG Object Management Group
GUI graphical user interface
ORB object request broker
HTML Hypertext Markup Language
OTS Object Transaction Service
HTTP Hypertext Transfer Protocol
RAD rapid application development
IBM International Business
Machines Corporation RAR resource adapter archive
IDE integrated development RDBMS relational database
environment management system
IDL interface definition language RMI Remote Method Invocation
IIOP Internet Inter-ORB Protocol SAM Security Access Manager
ITSO International Technical SAX simple API for XML
Support Organization SCCI source code control interface
J2CA J2EE connector architecture SCM software configuration
J2C J2EE connector architecture management

© Copyright IBM Corp. 2003. All rights reserved. 815


SCMS source code management
systems
SDK Software Development Kit
SOAP Simple Object Access
Protocol (also known as
Service Oriented Architecture
Protocol)
SQL structured query language
TCP/IP Transmission Control
Protocol/Internet Protocol
UDDI universal description,
discovery, and integration
UOW unit of work
URL uniform resource locator
UTC universal test client
WAR Web application archive
WSDL Web Service Description
Language
WWW World Wide Web
XHTML Extensible HyperText Markup
Language
XMI XML metadata interchange
XML eXtensible Markup Language
XSD XML schema definition

816 WebSphere Studio Application Developer Version 5 Programming Guide


Related publications

The publications listed in this section are considered particularly suitable for a
more detailed discussion of the topics covered in this redbook.

IBM Redbooks
For information on ordering these publications, see “How to get IBM Redbooks”
on page 819. Note that some of the documents referenced here may be available
in softcopy only.
򐂰 EJB 2.0 Development with WebSphere Studio Application Developer,
SG24-6819
򐂰 WebSphere Version 5 Web Services Handbook, SG24-6891
򐂰 The XML Files: Development of XML/XSL Applications Using WebSphere
Studio Version 5, SG24-6586
򐂰 Exploring WebSphere Studio Application Developer Integration Edition 5.0,
SG24-6200
򐂰 Linux Application Development Using WebSphere Studio 5, SG24-6431
򐂰 IBM WebSphere Application Server - Express V5.0 Handbook, SG24-6555
򐂰 IBM WebSphere Application Server Version 5.0 Handbook, SG24-6195
򐂰 IBM WebSphere V5.0 Security WebSphere Handbook Series, SG24-6573
򐂰 Legacy Modernization with WebSphere Studio Enterprise Developer,
SG24-6806
򐂰 WebSphere Studio Application Developer Programming Guide, SG24-6585
򐂰 Web Services Wizardry with WebSphere Studio Application Developer,
SG24-6292
򐂰 Self-Study Guide: WebSphere Studio Application Developer and Web
Services, SG24-6407
򐂰 WebSphere Version 4 Application Development Handbook, SG24-6134
򐂰 EJB Development with VisualAge for Java for WebSphere Application Server,
SG24-6144
򐂰 Design and Implement Servlets, JSPs, and EJBs for IBM WebSphere
Application Server, SG245754

© Copyright IBM Corp. 2003. All rights reserved. 817


Other publications
These publications are also relevant as further information sources:
򐂰 Design Patterns: Elements of Reusable Object-Oriented Software. Erich
Gamma, et al. Addison-Wesley Publishing Company, January 1995, ISBN
0201633612
򐂰 The Java Developer’s Guide to Eclipse, Sherry Shavor, Jim D'Anjou, Dan
Kehn, Scott Fairbrother, John Kellerman, Pat McCarthy. Addison Wesley
Professional, May 2003, ISBN 0321159640
򐂰 EJB Design patterns, Floyd Marinescu, John Wiley & Sons, February 2002,
ISBN 0471208310

Online resources
These Web sites and URLs are also relevant as further information sources:
򐂰 IBM WebSphere Studio Application Developer
http://www.ibm.com/software/awdtools/studioappdev/support
򐂰 IBM WebSphere Application Server
http://www.ibm.com/software/webservers/appserv/
򐂰 IBM WebSphere Developer Domain
http://www7b.software.ibm.com/wsdd/
򐂰 Eclipse workbench
http://www.eclipse.org
򐂰 Apache open source
http://jakarta.apache.org
򐂰 Apache Struts Project
http://jakarta.apache.org/struts
򐂰 Apache XML Project
http://xml.apache.org/
򐂰 Apache Tomcat Project
http://jakarta.apache.org/tomcat
򐂰 Apache Ant Project
http://ant.apache.org

818 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Common Versions System
http://www.cvshome.org
http://www.cvsnt.org
򐂰 Rational
http://www.rational.com
򐂰 SCM partners
http://www-3.ibm.com/software/ad/studioappdev/partners/scm.html
򐂰 Sun Java
http://java.sun.com/
򐂰 World Wide Web Consortium
http://www.w3.org/
򐂰 JUnit Organization
http://www.junit.org
򐂰 Partners for Software Confguration Management
http://www.ibm.com/software/ad/studioappdev/partners/scm.html
򐂰 Eclipse CVS
http://dev.eclipse.org/viewcvs/index.cgi/

How to get IBM Redbooks


You can search for, view, or download Redbooks, Redpapers, Hints and Tips,
draft publications and Additional materials, as well as order hardcopy Redbooks
or CD-ROMs, at this Web site:
ibm.com/redbooks

Related publications 819


820 WebSphere Studio Application Developer Version 5 Programming Guide
Index
J2EE
A applications 644
AAT 608
build
Abstract Windows Toolkit 470
script 645
access control 694
run 650
list 378
Javadoc 651
accessors 127
generation 136
ACCOUNT.dtd 357
run 641
ACCOUNT.xsd 354
script 135, 639
Account.xsl 362
simple build file 636
AccountDB 446
tasks 636
AccountDetails 181
Web site 634
accountDetails.jsp 183, 309, 326
Ant build files 635
AccountDetailsAction 336
Apache
AccountDoesNotExistException 113
Software Foundation 294
ACID 375
Tomcat 17, 539
ACL 378
API
Action 298
J2EE 80
ActionError 335
appearance
ActionErrors 314, 335
preferences 35
ActionForm 299, 313
Application Assembly Tool 608, 629
ActionForward 335
Application Client
ActionListener 503
Configuration Tool 629
ActionServlet 298
deployment descriptor 613
activity 749
module 81
administrative console 548, 617
project 85
AEs 17
Application Developer 4, 8
Agent Controller 515, 588, 657
Ant tasks 649
installation 792
ClearCase integration 752
remote machine 665
database tools 142
service 657
help 48, 50
AmountConverter 113, 314, 388
installation 790
Animated GIF Designer 13
Integration Edition 8
Ant 633–634
overview 10
build
migration 12
path 635
overview 10
project 635
preferences 26
property 635
profiling 656
target 635
team support 698
task 635
tools 12
classpath 644
Update Manager 793
dependencies 637
Version 5 11
documentation 634
application flow 309, 385
headless 652
Application Server 10

© Copyright IBM Corp. 2003. All rights reserved. 821


classpath 632 condition 555
configuration 617 JSP 556
Express 17 marker 554
installation 786 properties 555
Network Deployment 375 Breakpoints view 70, 561
Application Template wizard 88 broker 442
ApplicationResources 304 build 27
ApplicationResources.properties 306, 321 Ant 635
assembly 629 file 635
assertEquals 584 management 693
assertions 576 path 87
assertTrue 584 settings 96
atomicity 375 targets 639
Attributes view 61 build.compiler 639
audit file 230 build.xml 636
authentication 610 business methods
alias 534, 607 session bean 423
AutoCommit 263 business rule bean 10
automatic build 27, 128
AWT 470
C
caching
B HTML 196
backend folder 410 change
backupConfig 629 management 693
BankException 113, 307 variable value 562
banking application flow 185 check in 767
banking model 18, 111, 181 check in and check out 749
EJB 384 check out 766
BankingProxy 452 CICS 10
BankingTest 112 Class
BankingTestCase 590 Instance Statistics view 72, 682
BankMain 113 Method Statistics view 72, 668
Base time 667 Statistics view 667
baseline 749 class loader 545
make 770 policy 545
new 779 classpath
bean Ant 644
message 319 Application Server 632
bean-managed persistence 381 errors 814
BMP 381 JAR file 104
bookmark 132 variable 97
Bookmarks view 132 preferences 97
branch 694 variables 33
create 734 WebSphere extension 546
CVS 733 ClearCase 747
merge 736 add project 762
tag 739 check in 767
breakpoint 109, 554 check out 766

822 WebSphere Studio Application Developer Version 5 Programming Guide


connect 759 run 593
deliver 768 testing 573
help 753 Component Test perspective 72, 588
import 774 composer 386
plug-in 694 compression 706
preferences 753 concurrency 377–378, 696
project 757 workflow 697
rebase 777 Concurrent Versions System
scenario 754, 765 see CVS
setup 756 condition
synchronize 779 breakpoint 555
ClearCase LT 16, 748 conditions 168
Client 752 -configuration 24
installation 749 configuration file
Server 750 editor 300, 336
client Struts 298
Web service 465 conflict 702
ClientBankingProxy 462 resolution 724
clientConfig 629 connect to ClearCase 759
clone 375 connection
Cloudscape 147, 787 JDBC 140
CMP 381 pooling 141
attribute 391 consistency 375, 575
CMR 382 Console view 105, 225
code -consolelog 24
assist 38, 44, 118 container
formatter preferences 35 EJB 377
generation 126 container-managed
synchronization 483 persistence 381
Color by 671 relationships 382
Colors view 61 content assist 351
column context root 187, 302
create 159 controller
com.ibm.db.beans 260 MVC 181, 296
COM.ibm.db2.jdbc.app.DB2Driver 146, 175 converter 386
COM.ibm.db2.jdbc.net.DB2Driver 146, 175 copy file transfer 525
command create
design pattern 181 database 156
line tools 629 VOB 756
compare files 690 create method 404
compareTo 425 Create Web Pages from a JavaBean wizard 286
Compilation target 640 creating
compile errors 108 test case 582
compiler options CSS Designer 179, 200
preferences 36 custom finder 383, 406
component 749 CustomerDoesNotExistException 113
interface 382 CustomerGUI 473
plug-in 18 CustomerInfoForm 311
test CustomerListDS 177

Index 823
CustomerListing 100, 110, 498 create 256
CustomerListingDS 614 EJB access 428
CustomerListingNet 101 server configuration 533
customize server definition 256
perspective 54 data transfer object 385, 388, 425
server configuration 544 database
Visual Editor 478 application run 259
CVS 701 applications 139
branch 733 connection 145
configuration 706 create 155–156
console 712 tools 14
Console view 706, 712 Database Access
control information 745 Java Beans 250
decorators 706 Tag Library 250
ignore facility 711 Database Web Pages wizard 249
ignored resources 710 DB Beans 248, 260
installation 703 DB Output view 278
patch 740 DB Servers view 69, 143
preferences 707 DB2
reconnect 745 App Driver 146
Repositories view 73, 715 Command Window 163
repository 703 JDBC driver 104
add 714 Net Driver 146
Repository Exploring perspective 73, 706 UDB installation 786
Resource History view 74, 731 user ID and password 814
scenario 713 XML Extender 14, 445
server 707 DB2ConnectionPoolDataSource 619
services 704 db2java.zip 104, 176, 412, 618
share project 716 dbbeans.jar 261, 263
Web site 703 dbbeans_javadoc.zip 261
CVSNT 703 DBConnectionSpec 261
service configuration 705 DBProcedureCall 263
DBSelect 261
DDL 142
D generate 151, 161
dab
dds.xml 445, 456
dataSourceSpec 267, 291
Debug
getColumn 268
perspective 69, 109
parameter 268, 291
view 70, 111, 560
procedureCall 291
-debug 24
repeat 268
debugging 109
select 268
icons 560
DADX 445
JSP 564
Data
port 566
Definition view 69, 143, 272
remote 566
perspective 68, 142
source code 570
-data 24
step-by-step 558
data source 141, 177, 251
tools 16
Application Server 619
Web application 554

824 WebSphere Studio Application Developer Version 5 Programming Guide


decorations 712 overview 52
decorators 706 pane 59
Definition view 72, 591 EJB
deliver 768 2.0 specification 382
stream 749 application 385
delta versioning 702 architecture 376
demarcation 378 bean class 382
deployed code 426 client 381
deployment 608 component 379
management 693 component interface 382
deployment descriptor 608 container 80, 377
application client 613 data source 428
EAR 81 deployment descriptor 609
EJJB 609 editor 400
SOAP 445 JNDI name 427
Web 611 query 408
design references 418
considerations 112 relationship 404
patterns 112, 574 development 373
development stream 749, 760 home interface 382
Display view 71, 563 inheritance 383
distribution 374 JARs 645
doclet 134 mapping 410
document object model 450 module 81
doFilter 226 overview 374
doGet 207 project 84, 386, 514
DOM 450 create 387
doPost 207 QL 383
DriverManager 141, 174 custom finder 406
DTD 14, 346 query example 407
from XSD 357 Query Language 383
validator 358 reference 418
DTO 385 Web project 438
dumpNameSpace 629 server 377
durability 375 specification 377
dynamic Web resources 203 test client 15
tools 15
types 380
E universal test client 428
EAR 81, 645
EJBBANK
Eclipse 4
database 18
open standards 7
installation 811
platform 5
ejbCreate 405
plug-in 6
ejbDeploy 629
team development 8
ejbPostCreate 405
user interface 5
encapsulation 385
Workbench 4
encoding 450
Editing JSP 217
enterprise 10
editor
enterprise application

Index 825
archive 15 Struts
export 616 form bean 310
installation 622 formatting rules 35
Enterprise Application project 83, 514 fragment 18
Enterprise Developer 8 frameset 196
overview 10 front controller 252
enterprise generation language 10 FTP 520
Enterprise Java Server 377 file transfer 526
entity bean 381
create 389
event handling 502
G
Gallery view 60
Execution Flow view 72, 679
garbage collection 666, 673
Execution view 72
thread 679
export
generate
enterprise application 616
DDL 161
GUI application 508
DDL from XMI 142
Java class 106
getter methods 422
Expressions view 71, 562
getter/setter 127
extract
XML schema 152
method 123
Generate Deploy and RMIC Code wizard 426
variable 123
GenPluginCfg 629
extreme programming 574
getConnection 175
GetCustomberBean 281
F GetCustomerMain 280
facade 112, 184, 295, 436 Graph view 355
EJB 385 graphical user interface 469
Feature Updates view 75 GridBagLayout 492
file GridLayout 489
associations 28 GROUP BY 169
compare 690 GUI application 469
replace 691
restore 692
serving 613
H
hardware prerequisites
transfer mechanism 520
Application Developer 790
filter
Application Server 786
chaining 227
HEAD branch 719
create 227
headless 652
profiling 660
heap 547, 666, 670
servlet 226
Heap view 72, 670–671
Tasks view 122
help
finder method 383
Application Developer 48
findGoldAccounts 407
bookshelves 49
FirstHTTPTest 599
Hierarchy view 62, 65
firstSteps 629
history 29
Fix Packs 549
hit count 555
FlowLayout 492
home interface 382, 396
foreign key 162
horizontal integration 7
form bean 300
host variable 169

826 WebSphere Studio Application Developer Version 5 Programming Guide


hover help 118 initial context 421
HTML InitialContext 177, 422
appearance 202 Initialization target 639
cache 196 inline variable 123
link 218 insert JSP tag 267
page properties 197 Install Configuration view 75
syntax validation 194 install enterprise application 622
Template wizard 364 Install/Update perspective 75
html installableApps 616
errors 321, 335 installation
form 320 Agent Controller 792
hidden 322 Application Developer 790
reset 320 Application Server 786
submit 320, 322 ClearCase LT 749
text 320 CVS 703
HTTP DB2 UDB 786
scheduler 598 EJBBANK database 811
test case 598 test server 814
HTTP Server 529, 544, 787 Installed JREs
plug-in configuration 627 preferences 39
HttpServlet 205 Instance Statistics view 72, 683
HttpSession 232 InstantDB 147
HttpSessionAttributeListener 232 InsufficientFundsException 113
HttpSessionInspector 232 integrated development environment 48
HttpSessionListener 232 see IDE
integration 7
stream 749, 768
I Integration Edtion
icons for debugging 560
see Application Developer Integration Edition
IDE 8, 48
interface 379
ignore facility 711
Internet
ignored resources 710
preferences 32
image library 13
InvalidAmountException 113
import
InvalidateSession 181, 218
database objects 149
ISD 445
EAR file 608
isolation 375
from ClearCase 774
itso.ant.hello 635
JAR file 114
itso.bank.exception 113, 307
resources 192
itso.bank.facade 113, 193, 305
statement generation 120
itso.bank.main 113
tag library 265
itso.bank.model 113, 456
WAR file 192
itso.bank.util 113
Web content 305
itso.basicweb.control 193
IMS 10
itso.basicweb.filter 227
incremental compile 128
itso.basicweb.listener 233
index.jsp 309, 316
itso.databaseweb 249
Informix 14, 147, 787
itso.ejb.model.entity 390
inheritance 383
itso.ejb.model.facade 416
init 207
itso.gui 471

Index 827
itso.jbwp 238 JAAS 533
itso.junit 579 JAR 81
itso.storedproc 275 Java
itso.storedproc.bean 281 application development 93
itso.storedproc.main 280 Beans view 490
itso.strutsweb.forms 311 Browsing perspective 63
itso.strutsweb.resources 304 build path 87
itso.webserv.model 446 build settings 96
itso.xml 350, 371 class 100
ItsoProGuide 187, 302, 608, 616, 645, 657 development
ItsoProGuide.ear 812 preferences 33
ItsoProGuideAnt 635 tools 15
ItsoProGuideBasicWeb 186, 436, 554, 570, 611 Editor
ITSOProGuideCCEAR 762 preferences 37
ITSOProGuideCCWeb 762 package 99
ItsoProGuideCVS 715 perspective 61
ItsoProGuideDatabase 149 Profiling Agent 659
ItsoProGuideDataBaseWeb 248 project 82, 94
ItsoProGuideDatabaseWeb 538 Runtime Environment 39
ItsoProGuideEJB 388, 464 Scrapbook 115
ItsoProGuideGui 471 search 128
ItsoProGuideJava 95, 114, 180, 188 source folder 191
ItsoProGuideJavaClient 613–614 stored procedure 272
ItsoProGuideJUnit 578, 589 test case 589
ItsoProGuideServer 519 Type Hierarchy perspective 64
ItsoProGuideServers 224 utility JAR 645
ItsoProGuideStoredProcWeb 272, 539 Virtual Machine 656
ItsoProGuideStrutsWeb 302, 436 Profiler Interface 656
ItsoProGuideWebServ 446 java
ItsoProGuideWebServClient 452 comp/env 614
ItsoProGuideXmlWeb 350 JavaBean
ItsoServer 224, 259 from WSDL 445
from XSD 445
Web Pages wizard 237
J Javadoc 133
J2EE
Ant 136, 651
API 80
code assist 118
architecture 80
comment 101
Hierarchy view 57
generation 133
Navigator view 56, 60
preferences 40, 133
perspective 56
JavaScript 13, 218
projects 83
JavaServer Pages 7
Publishing Server 516
JAXP 346
Request Profiler 659
JDBC 140, 174
specification 9
2.0 Standard Extension API 141
technologies 80
connection 140
Web project 84
create 146
J2SE
data source 177
specification 9
driver 174, 619

828 WebSphere Studio Application Developer Version 5 Programming Guide


path 618 JVMPI 656
driver class 147
overview 140
resources 176
K
key
type 2 driver 175
class 382
type 3 driver 175
field 392
jdbc/ejbbank 177, 251, 256, 427, 610, 614
wrapper class 393
jdbc/mybank 614
keyboard
JDK 115
shortcuts 801
JMS 378
keyword
JNDI
expansion 707
data source 141
Explorer 429
namespace 378 L
join 168 label decorations 712
project 772 launch configuration 103
JRE 39 launchClient 629
JScrollPane 495 LaunchPad 788
JSP 9 lib directory 191
breakpoint 556 Library view 60
create 211 life cycle 377–378
data beans 261 life-cycle method 396
debugging 564 link 218
directive Links view 61, 210
taglib 264 ListAccounts 181, 205, 209
editing 217 listAccounts.jsp 182, 210, 309, 325
insert custom 267 ListAccountsAction 333
precompile 612 ListCredits 251
scriptlet 222 listener
SQL 262 create 233
stored procedure 291 servlet 232
Struts listTransactions.jsp 183, 309, 328
create 316 local
taglib component interface 396
data beans 262 history 29, 689–690
tags preferences 30, 692
Struts 300 interface 379
useBean 219 location independence 380
JspBatchCompiler 629 lockRows 263
jspsql.jar 263 Log Console view 642
JUnit 573–574 log files 26
methods 584 logic
project properties 578 iterate 330
run 586 Lotus Domino Enterprise Server 787
setUp and tearDown 582
testing 576
view 586
M
Maintenance 576
junit.framework.Assert 584 MAKE 634
junit.jar 578

Index 829
MANIFEST.MF 191 NFS 23
mapping
editor 414
strategies 409
O
object
marker 554
caching 375
Master.css 201
pooling 375
MDB 378, 381
Object References view 72, 684
mediator 112
object-relational mapping 409
memory analysis 666
ODBC 140
memory leaks 673
OMG 142
merging 736
Open Source 679
Merging from a stream 736
optimistic concurrency 696
message-driven bean 378, 381
Oracle 147, 787
MessageDrivenBean 382
ORDER BY 169
MessageListener 382
org.apache.struts 298
messaging 377–378
organize imports 121
metadata directory 82
preferences 42
META-INF 191
ost variable 253
Method
Outline view 57, 59–60, 62, 67, 72, 119
Execution view 72, 677
override methods 127
Invocation view 72, 674
Statistics view 72, 669
method P
execution 673 Package Explorer view 61, 119
extract 123 Package Statistics view 72, 667
override 127 Page Designer 60, 193
pull up 123 JSP tag rendering 323
migration 12 palette 475
model 295 parallel development 723
MVC 180 patch 740
model-view-controller 294 apply 742
modify parameters 123 path language 348
module dependency 189, 303 pattern
multiplicity 402 command 181
MVC 180 MVC 180, 294
controller 296 PDE 17
model 295 performance
pattern 297 analysis 663, 666
Struts 297–298 profiling 10
view 296 profiling tools 16
MySQL 147 PerformTransaction 181, 229
PerformTransactionAction 336
persistence 374, 377–378
N Persistence Builder 12
namespace 348, 378
perspective 22
naming 377–378
Component Test 72, 588
NamingException 422
customize 54
Navigator view 56, 59, 67, 144
CVS Repository Exploring 73, 706
network file system 23
Data 68, 142

830 WebSphere Studio Application Developer Version 5 Programming Guide


Debug 69, 109 refactoring 43, 124
default 54 templates 44
Install/Update 75 Tomcat 540
introduction 51 validation 358
J2EE 56 Visual Editor 478
Java 61 Preview view 75
Java Browsing 63 problem tracking 693
Java Type Hierarchy 64 process management 694
layout 52 Profiling
open 53 Monitor view 662
overview 47 perspective 71
Plug-in Development 76 profiling 655
preferences 31 Agent Controller 657
Profiling 71 attach 658
Resource 58 filter 660
Server 66, 513 remote 665
Web 59 start 662
XML 67 start server 658
XSL Debug 68, 369 tools 16
pluggable JDK 115 views 663
plug-in programming assists 115
component 18 project 79
configuration 627 add to version control 718
development environment 17 add to workspace 719
Eclipse 6 Application Client 85
fragment 18 ClearCase control 762
project 17 create 86
tools 17 Java 94
Plug-in Development perspective 76 directory structure 190
plugin-cfg.xml 544 disconnect from CVS 745
port EJB 84, 386
debugging 566 Enterprise Application 83
portabiliy 376 J2EE 83
preferences 26 Java 82, 94
appearance 35 join 772
Classpath Variable 97 organization 82
ClearCase 753 properties 87, 189
code formatter 35 JUnit 578
CVS 707, 710 Server 85, 519
file associations 28 server assignment 531
installed JREs 39 sharing 716
Internet 32 simple 82
Java compiler 36 Struts 84, 300
Java development 33 types 82
Java Editor 38 utility 93, 111
Javadoc 41, 133 version 731
local history 30, 692 Web 84
orgainze imports 42 promote 392
perspectives 31 business methods 398

Index 831
properties reconnect 745
project 87 request sequence 299
Properties view 58, 476 requestor 442
filter 489 Resource
provider 442 Patcher wizard 742
proxy 452 perspective 58
class 458 resource
proxy.soap 452 synchronization 711
pserver 702 resources
puggable 115 ignored 710
pull up method 123 restoreConfig 629
ResultSet 176
resume 560
R RMI 377
ramp-up time 576
role-based development model 4
RAR 545
root element 353, 360
Rational
Run on Server 259, 516
ClearCase
runAnt.bat 652
see ClearCase
RunBanking.jsp 446
Web site 748
run-time environment 514
rebase 749, 777
RunTranfer.jsp 291
Red Hat 790
RedBank 180
Redbooks Web site 819 S
Contact us xxiv sample code 18
refactoring 15, 122 scalability 375
example 124 schema
preferences 43, 124 create 157
preview 126 SCM 689
reference tools 699
EJB 418 scope 449
references 418 scrapbook 15, 115
relationship scriptlet 222
methods 404 search 50, 128
relationships 382 security 377–378
create 400 SOAP 449
remote SELECT
Application Server 566 statement 165
client view 416 self encapsulate 123
debugging 566, 629 Sequence Diagram view 680
file transfer instance 524 Server
profiling 665 Configuration view 66, 224, 529
server 520 perspective 66, 513
attach 567 project 85, 519
debug configuratoin 566 server
settings 523 configuration 514
user ID and password 538 create 519
rename 123 create manually 527
repository 694 customize 544

832 WebSphere Studio Application Developer Version 5 Programming Guide


create 224, 516 deployment descriptor 445
debugging 557 encoding 450
installation 814 router servlet 449
peference 87 security 449
profiling mode 658 soap.xml 456
remote 520 soapcfg.jar 456
start 225 software
start and stop 535 configuration management 16, 689, 748
tools 17, 514 prerequisites
Servers view 61, 66, 224 Application Developer 790
serverStatus 629 Application Server 786
service SortedSet 425
broker 442 SQL
provider 442 Assist 274
registry 442 procedures 272
requestor 443 query 249
service-oriented architecture 441 statement 166
services create 165
CVS 704 execute 170
servlet 9, 204 SQL Query Builder 14, 142, 165, 171
create 204 example 171
creation 13 SQL Server 14, 147, 787
filter 226 SQL Statement wizard 14, 165, 274
listener 232 example 165
SOAP 449 SQL to XML wizard 14
Struts 298 ssh 702
ServletContext 232 standardization 376
ServletContextAttributeListener 232 standards 7
ServletContextListener 232 startServer 627, 629
session bean 381, 415 startup parameters 24
business methods 421 stateless 415
create 416 static Web resources 193
session variable 214, 317 status bar 58
SessionBean 382 Step Into 561
Sessions view 370 Step Over 561
set breakpoint 554 step-by-step debugging 558
setUp 582 stopServer 627, 629
setupCmdLine 629 stored procedure 271–272
-setworkspace 24 build 278
sg246957code.zip 810 execute 279
share project 716 generate JavaBean 281
shortcuts 801 JSP 291
showException.jsp 184 multiple statements 287
Simple Object Access Protocol 15 parameters 275
simple project 82 properties 279
SingleThreadModel 206 tag library 285
Site Developer 8 Stored Procedure wizard 273
overview 9 Struts 11, 293
SOAP 15, 443 application flow 309

Index 833
configuration file 336 TCP/IP Monitor view 543
controller 297 TCP/IP Monitoring Server 516
create team development 8, 693
action 332 tearDown 582
form bean 311 template
JSP 316 application 88
framework 301 templates 43
JSP tags 300 preferences 44
logic tag 330 terminate 560
model 297 terminology comparison 699
MVC 297–298 test case
project 84, 300 create 578, 582
request sequence 299 HTTP 598
servlet 298 prepare 591
tag libraries 317 report 595
view 297 TestCase 577
struts.jar 304 TestClient.jsp 459
strutsbank.gph 308, 340 TestDBBeans.jsp 261, 538
struts-bean.tld 319 TestSuite 577, 584
struts-config.xml 304, 314, 336 TestTagLib.jsp 264
struts-html.tld 319 Text Editor 150
struts-logic.tld 324 theme 191
struts-xxxx.tld 304 thread activity 666
style sheet 200 Threads 680
Styles view 61 Thumbnail view 61
Sun ONE Web Server 787 time
SuSE 790 analysis 666
suspend 560 consuming objects and methods 672
Swing 470 Tomcat 515, 539
Sybase 14, 147 download 539
synchronization 484, 695 preferences 540
synchronize 779 tools 12
Synchronize view 718 transaction 377
syntax demarcation 378
highlighting 118, 351 TransactionAuditingFilter 228
HTML 194 transactions
EJB 375
transfer object 385
T
table
create 157 U
join 168 UDDI 15, 444
tag library 213 registry 454
data beans 248 UML view 402
import 265 Unified Change Management 748
stored procedure 285 unique identifier 395
Tasks view 57, 67, 108, 121 unit test
TCP/IP Monitor 540 case 575
port 542 environment 17

834 WebSphere Studio Application Developer Version 5 Programming Guide


unit testing 574 CVS Resource History 74, 731
framework 575 Data Definition 69, 143, 272
Universal Description Discovery and Integration 15 DB Output 278
universal test client DB Servers 69, 143
array 435 Debug 70, 111, 560
bean page 431 Definition 72, 591
EJB 428 Display 71, 563
run program 280 Execution 72
Web service 460 Execution Flow 72, 679
Update Manager. 793 Expressions 71, 562
URL 175 Feature Updates 75
useBean 248 Gallery 60
user interface Graph 355
Eclipse 5 Heap 72, 670
user-defined tasks 121 Hierarchy 62, 65
utility Install Configuration 75
JAR 81, 188 Instance Statistics 72, 683
project 93, 111 J2EE Hiearchy 57
J2EE Navigator 60
Java Beans 490
V JUnit 586
validate method 311
Library 60
validation 87
Links 61, 210
preferences 358
Log Console 642
XML 357
Method Execution 72, 677
value object 385
Method Invocation 72, 674
variable
Method Statistics 72, 669
change value 562
MVC 182, 296
DB2JAVA 105
Navigator 56, 59, 67, 144
extract 123
Object References 72, 684
inline 123
Outline 57, 59–60, 62, 67, 72, 119
Variables view 70, 111, 561
Package Explorer 61, 119
VBScript 13
Package Statistics 72, 667
version 696
Preview 75
control 689, 693
Profile Monitoring 662
project 731
Properties 58, 476
versioned object base 749
Sequence Diagram 680
versioning 730
Server Configuration 66, 224, 529
vertical integration 7
Servers 61, 66, 224
view 749
Sessions 370
Attributes 61
Styles 61
Bookmarks 132
Synchronize 718
Breakpoints 70, 561
Tasks 57, 67, 108, 121
Class Instance Statistics 72, 682
TCP/IP Monitor 543
Class Method Statistics 72, 668
Thumbnail 61
Colors 61
Variables 70, 111, 561
Console 105, 225
Web Browser 557
CVS Console 706
Web Structure 60, 300
CVS Repositories 73, 715
views

Index 835
overview 51 Service
Visual Composition Editor 12, 502 Explorer 455
Visual Editor 11, 469–470 service 9
code synchronization 484 client 461, 465
customize 478 create 446
event handling 502 from session bean 464
example 481 proxy 452
Java Beans view 490 scope 449
launch 472 test 459
look and feel 475 universal test client 460
palette 475 URI 448
preferences 478 XML mapping 450
-vm 24 services 443
-vmargs 24–25 clients 446
VOB 749 tools 445
create 756 services tools 15
Structure view 60, 300
Web Service Client wizard 461
W Web Service wizard 447
W3C 200, 346
Web Services Description Language 15
WAR 81, 645
Web Services Object Runtime Framework 632
class loader policy 546
web.xml 213
import 192
WEB-INF 191
watching variables 561
webservice-runtime.jar 456
Web
WebSphere
application
extension class loader 546
archive 15
WebSphere MQ 379
debug 554
WebSphere Studio
development 179
family 9
Art Designer 13
product family 4
Browser view 557
WebSphere Studio Application Developer
container 80
see Application Developer
content folder 191
WebSphere Studio Asset Analyzer 11
deployment descriptor 13, 213, 611
WHERE clause 168, 173
development tools 13
wizard
diagram 300
Application Template 88
complete 341
Create Web Pages from a JavaBean 286
components 308
Database Web Pages 249
create 307
Generate Deploy and RMIC Code 426
implemented 331
JavaBean Web Pages 237
material 810
SQL Statement 14, 165, 274
module 81
SQL to XML 14
pages from SQL queries 249
Stored Procedure 273
perspective 59
Web Service 447
project 84, 514
Web Service Client 461
create 185
XML Signature 361
dependencies 437
WORF 632
EJB reference 438
worf.jar 632
features 186
Workbench 4

836 WebSphere Studio Application Developer Version 5 Programming Guide


basics 22 -Xms 25, 547
features 6 -Xmx 24–25, 547
SCM adapter 16 XPath 348
working set 128–129 -Xquickstart 25
workload optimization 375 XSD 14
workspace 23 xsd.bean.runtime.jar 456
directory 23, 82 XSL 347
prompt 25 apply 368
World Wide Web Consortium 200 create file 362
WSAA 11 Debug perspective 68, 369
wsadmin 629–630 debugging 369
WSDL 15, 444 editor 363
files 456 source editor 11
style sheet 14
transformation 347
X tree 367
X/Open SQL 140
validator 358
Xalan 346, 369
wizards 363
Xerces 346
XSLT 14, 346–347
-Xgcpolicy 25
processor 369
XHTML 195
XMI 142
files 150 Z
XML z/OS 10
configuration file 298 ZeroAmountException 113
create file 350
editor 351
Extender 14
generators 356
Metadata Interchange 142
namespace 348
overview 346
perspective 67
processor 346
sample file 352
schema 346
create 353
editor 355
from table 354
generate 152
generate JavaBean 371
graph 155
validator 358
Signature wizard 361
tools 14, 349
tramsformation 368
validation 357
validator 358
XML4J 346

Index 837
838 WebSphere Studio Application Developer Version 5 Programming Guide
WebSphere Studio
Application Developer
Version 5 Programming Guide
(1.5” spine)
1.5”<-> 1.998”
789 <->1051 pages
Back cover ®

WebSphere Studio
Application Developer
Version 5 Programming Guide
Develop Java, Web, This IBM Redbook is a programming guide for the application
XML, database, EJB, development tool, WebSphere Studio Application Developer V5. This
INTERNATIONAL
and Web services tool is not only intended for the Java developer, but also for the Web TECHNICAL
applications designer who creates Web pages. The WebSphere Studio Application SUPPORT
Developer basic tooling and team environment is presented along with ORGANIZATION
the development and deployment of Web applications.
Test with built-in and
remote servers WebSphere Studio Application Developer provides integrated
development tools for all e-business development roles, including Web BUILDING TECHNICAL
Deploy to WebSphere developers, Java developers, business analysts, architects, and INFORMATION BASED ON
Application Server enterprise programmers. The customizable, targeted, role-based PRACTICAL EXPERIENCE
approach of WebSphere Studio Application Developer will be
characteristic of all new products built on the WebSphere Studio IBM Redbooks are developed by
Workbench. It is well integrated with WebSphere Application Server the IBM International Technical
and provides built-in server test environments that can be used for Support Organization. Experts
testing and profiling Web applications. from IBM, Customers and
Partners from around the world
create timely technical
This redbook consists of six parts: information based on realistic
򐂰 Introducing WebSphere Studio Application Developer scenarios. Specific
򐂰 Developing applications recommendations are provided
򐂰 Testing and debugging applications to help you implement IT
򐂰 Deploying and profiling applications solutions more effectively in
your environment.
򐂰 Team programming
򐂰 Appendixes and additional material

For more information:


ibm.com/redbooks

SG24-6957-00 ISBN 0738499579

También podría gustarte