RAD v7, Programming Guide
RAD v7, Programming Guide
Rational Application
Developer V7
Programming Guide
Develop Java, Web, XML, database,
EJB, Struts, JSF, SDO, EGL, Web
services, and portal applications
Deploy applications to
WebSphere Application Server
and WebSphere Portal
Ueli Wahli
Henry Cui
Craig Fleming
Maan Mehta
Marco Rohr
Pinar Ugurlu
Patrick Gan
Celso Gonzalez
Daniel M. Farrell
Andreas Heerdegen
ibm.com/redbooks
International Technical Support Organization
December 2007
SG24-7501-00
Note: Before using this information and the product it supports, read the information in
“Notices” on page xxv.
This edition applies to Version 7.0 of IBM Rational Application Developer for WebSphere
Software.
Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxvi
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxvii
The team that wrote this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxviii
Become a published author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxxi
Comments welcome. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xxxii
Chapter 1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
IBM Rational Software Delivery Platform . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Version 7 terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Application development challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Key themes of Version 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Product packaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Rational Developer supported platforms and databases . . . . . . . . . . . . . . . 9
Application Developer V7 product packaging . . . . . . . . . . . . . . . . . . . . . . . 10
Product features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Summary of new features in Version 7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Specification versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Eclipse and IBM Rational Software Delivery Platform . . . . . . . . . . . . . . . . . . 16
Eclipse Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Eclipse Software Developer Kit (SDK) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Test server environments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Installation and licensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Licensing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Updates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Uninstall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Migration and coexistence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Migration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Compatibility with previous versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Migration considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Contents v
Web perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Progress view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Contents vii
Creating a run configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Debugging a Java application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Using the Java scrapbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
Plugable Java Runtime Environment (JRE) . . . . . . . . . . . . . . . . . . . . . . . 289
Exporting Java applications to a JAR file . . . . . . . . . . . . . . . . . . . . . . . . . 290
Running Java applications external to Application Developer . . . . . . . . . 292
Importing Java resources from a JAR file into a project . . . . . . . . . . . . . . 293
Javadoc tooling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293
Generating Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Java editor and rapid application development . . . . . . . . . . . . . . . . . . . . . . 300
Navigating through the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Using the Outline view to navigate the code . . . . . . . . . . . . . . . . . . . . . . . 301
Using the Package Explorer to navigate the code . . . . . . . . . . . . . . . . . . 302
Using bookmarks to navigate the code . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Source folding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Type hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
Smart insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Marking occurrences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Smart compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Java and file search . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Working sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Quick fix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Quick assist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Content assist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Import generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Adding constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Delegate method generator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
Contents ix
Launching the visual editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Creating a visual class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
Open an existing class with the visual editor . . . . . . . . . . . . . . . . . . . . . . 409
Visual editor overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Visual editor layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
Customizing the appearance of the visual editor . . . . . . . . . . . . . . . . . . . 411
Working with the visual editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Resizing a JavaBean component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Code synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
Changing the properties of a component . . . . . . . . . . . . . . . . . . . . . . . . . 414
Adding JavaBeans to a visual class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Working with the Properties view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Testing the appearance of the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Adding event handling to GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 419
Verifying the Java GUI application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Run the sample GUI as a Java application . . . . . . . . . . . . . . . . . . . . . . . . 422
Automatically add event handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
visual editor binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Chapter 12. Develop Web applications using JSPs and servlets . . . . . . 465
Introduction to J2EE Web applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
J2EE applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
Model-view-controller (MVC) pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
Web development tooling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Web perspective and views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
Web Site Navigation Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
Web Diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 476
Page templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
CSS Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
Security Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
File creation wizards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
Summary of new features in V7.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
RedBank application design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
View layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
Controller layer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
Implementing the RedBank application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
Creating the Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Web project directory structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 491
Importing the RedBank model. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
Defining the Web site navigation and appearance . . . . . . . . . . . . . . . . . . 493
Launching the Web Site Designer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
Developing the static Web resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
Developing the dynamic Web resources. . . . . . . . . . . . . . . . . . . . . . . . . . 513
Working with JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
Testing the Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Prerequisites to run the sample Web application . . . . . . . . . . . . . . . . . . . 533
Running the sample Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
Verifying the RedBank Web application . . . . . . . . . . . . . . . . . . . . . . . . . . 534
RedBank Web application conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
Contents xi
Activating Struts development capabilities . . . . . . . . . . . . . . . . . . . . . . . . 547
ITSO Bank Struts Web application overview . . . . . . . . . . . . . . . . . . . . . . 548
Creating a dynamic Web project with Struts support . . . . . . . . . . . . . . . . 550
Developing a Web application using Struts . . . . . . . . . . . . . . . . . . . . . . . . . 553
Creating the Struts components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
Realizing the Struts components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
Modify application resources. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
Using the Struts validation framework. . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
Page Designer and the Struts tag library . . . . . . . . . . . . . . . . . . . . . . . . . 563
Completing the logon action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
Using the Struts Configuration Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Completing the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
Running the Struts Bank Web application . . . . . . . . . . . . . . . . . . . . . . . . . . 577
Developing a Struts Web application using Tiles . . . . . . . . . . . . . . . . . . . . . 580
Building the Tiles application extension . . . . . . . . . . . . . . . . . . . . . . . . . . 581
Running the Tiles application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
Importing the final sample application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
Chapter 14. Develop Web applications using JSF and SDO . . . . . . . . . . 587
Introduction to JSF, SDO, and AJAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
JavaServer Faces (JSF) overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
Service Data Objects (SDO) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
Asynchronous JavaScript and XML (AJAX) . . . . . . . . . . . . . . . . . . . . . . . 594
Preparing for the sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
Creating a dynamic Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
Setting up the sample database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
Configuring the data source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
Developing a Web application using JSF and SDO . . . . . . . . . . . . . . . . . . . 599
Creating a dynamic page template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
Views for editing page template files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
Customizing the page template. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
Create Faces JSP pages using the Web Diagram Editor . . . . . . . . . . . . . 611
Editing the Faces JSP pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
Editing the login page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
Editing the customer details page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
Editing the account details page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
Running the sample Web application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
Prerequisites to run sample Web application . . . . . . . . . . . . . . . . . . . . . . 647
Preparation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
Running the sample Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
Verifying the sample Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
Contents xiii
Implementing a detail page with update . . . . . . . . . . . . . . . . . . . . . . . . . . 715
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
Contents xv
Running the SDO Web service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
Web services security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 856
Using the WS Security wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858
Running the Web service with security . . . . . . . . . . . . . . . . . . . . . . . . . . . 862
Developing Web services with the Web Services Feature Pack . . . . . . . . . 864
Supported standards and programming model. . . . . . . . . . . . . . . . . . . . . 865
Installing the Web Services Feature Pack . . . . . . . . . . . . . . . . . . . . . . . . 866
Enabling the WebSphere Application Server v6.1 test environment with the
Feature Pack for Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . 866
Creating a Web service and a client using the JAX-WS runtime . . . . . . . 867
Securing the Web service and client with the RAMP policy set . . . . . . . . 873
Sending binary data using MTOM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879
Creating Web services using annotations . . . . . . . . . . . . . . . . . . . . . . . . . 889
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896
Contents xvii
Running the TPTP JUnit test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1027
Analyzing the test results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1028
Web application testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1031
Preparing for the sample . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1031
Recording a test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1032
Editing the test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1034
Generating an executable test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1035
Running the test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1035
Analyzing the test results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1037
Generating test reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1038
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1040
Contents xix
Preparing for the deployment of the EJB application . . . . . . . . . . . . . . . . . 1120
Reviewing the deployment scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . 1120
Installing the prerequisite software . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1121
Importing the sample application project interchange files . . . . . . . . . . . 1122
Sample database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1122
Packaging the application for deployment . . . . . . . . . . . . . . . . . . . . . . . . . 1123
Generating the EJB to RDB mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . 1123
Customizing the deployment descriptors . . . . . . . . . . . . . . . . . . . . . . . . 1125
Removing the enhanced EAR data source . . . . . . . . . . . . . . . . . . . . . . . 1126
Generating the deploy code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1126
Exporting the EAR files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1127
Manual deployment of enterprise applications . . . . . . . . . . . . . . . . . . . . . . 1128
Configuring the data source in the application server . . . . . . . . . . . . . . . 1128
Installing the enterprise applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1135
Starting the enterprise applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1138
Verifying the application after manual installation . . . . . . . . . . . . . . . . . . 1139
Uninstalling the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1141
Automated deployment using Jython based wsadmin scripting. . . . . . . . . 1141
Overview of wsadmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1142
Overview of Jython . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1142
Developing a Jython script to deploy the ITSO Bank . . . . . . . . . . . . . . . 1144
Executing the Jython script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1152
Verifying the application after automatic installation . . . . . . . . . . . . . . . . 1154
Generation Jython source code for wsadmin commands . . . . . . . . . . . . 1154
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1154
Contents xxi
Creating the Windows users and groups used by CVS . . . . . . . . . . . . . 1222
Verifying the CVSNT installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1223
Creating CVS users . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1224
CVS client configuration for Application Developer . . . . . . . . . . . . . . . . . . 1225
Configuring the CVS team capability . . . . . . . . . . . . . . . . . . . . . . . . . . . 1225
Accessing the CVS repository. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1226
Configuring CVS in Application Developer. . . . . . . . . . . . . . . . . . . . . . . . . 1227
Label decorations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1228
File content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1229
Ignored resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1230
CVS-specific settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1232
CVS keyword substitution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1233
Development scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1236
Create and share the project (step 1 - cvsuser1) . . . . . . . . . . . . . . . . . . 1237
Adding a shared project to the workspace (step 2 - cvsuser2) . . . . . . . . 1240
Modifying the servlet (step 2 - cvsuser1) . . . . . . . . . . . . . . . . . . . . . . . . 1244
Synchronizing with the repository (step 3 - cvsuser1). . . . . . . . . . . . . . . 1245
Synchronizing with the repository (step 3 - cvsuser2). . . . . . . . . . . . . . . 1247
Parallel development (step 4 - cvsuser1 and cvsuser2) . . . . . . . . . . . . . 1247
Creating a version (step 5 - cvsuser1) . . . . . . . . . . . . . . . . . . . . . . . . . . 1253
CVS resource history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1254
Comparisons in CVS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1256
Comparing a workspace file with the repository . . . . . . . . . . . . . . . . . . . 1256
Comparing two revisions in repository . . . . . . . . . . . . . . . . . . . . . . . . . . 1258
Annotations in CVS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1259
Branches in CVS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1261
Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1262
Merging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1266
Working with patches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1270
Disconnecting a project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1271
Team Synchronizing perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1272
Custom configuration of resource synchronization . . . . . . . . . . . . . . . . . 1272
Schedule synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1276
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1277
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1325
Contents xxiii
xxiv Rational Application Developer V7 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 illustrate 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.
Oracle, JD Edwards, PeopleSoft, Siebel, and TopLink are registered trademarks of Oracle Corporation
and/or its affiliates.
Snapshot, and the Network Appliance logo are trademarks or registered trademarks of Network Appliance,
Inc. in the U.S. and other countries.
AMD, the AMD Arrow logo, and combinations thereof, are trademarks of Advanced Micro Devices, Inc.
Flex, Adobe Reader, Adobe, and Portable Document Format (PDF) are either registered trademarks or
trademarks of Adobe Systems Incorporated in the United States, other countries, or both.
Enterprise JavaBeans, EJB, Java, Java Naming and Directory Interface, Javadoc, JavaBeans, JavaMail,
JavaScript, JavaServer, JavaServer Pages, JDBC, JDK, JMX, JNI, JRE, JSP, JVM, J2EE, J2SE, Sun, Sun
Java, and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other
countries, or both.
Expression, Internet Explorer, Microsoft, SQL Server, Windows NT, Windows Server, Windows Vista,
Windows, and the Windows logo are trademarks of Microsoft Corporation in the United States, other
countries, or both.
Intel, Pentium, Pentium 4, Intel logo, Intel Inside logo, and Intel Centrino logo are trademarks or registered
trademarks of Intel Corporation or its subsidiaries in the United States, other countries, or both.
UNIX is a registered trademark of The Open Group in the United States and other countries.
Linux is a trademark of Linus Torvalds in the United States, other countries, or both.
Other company, product, or service names may be trademarks or service marks of others.
Local team
Ueli
Ueli Marco
Marco Craig
Craig Pinar
Pinar Maan
Maan Patrick
Patrick Henry
Henry
Henry Cui is a Software Developer working at the IBM Toronto lab. Henry has
been in the IBM Rational Application Developer service and support team for four
years. He has helped many customers resolve design, development, and
migration issues with J2EE development. Henry was a member of the
WebFacing Eclipse project sponsored by the IBM Extreme Blue™ program at
Almaden Research Center. Before joining IBM, Henry worked as a Software
Patrick Gan is a Senior IT Specialist who works for IBM Global Services,
Application Innovation Services Center of Excellence, US. He has eight years of
experience and expertise in OOAD/Java Design best practices, J2EE
development, SOA, software development methods, and tools. In his current
Preface xxix
capacity, Patrick's primary responsibility in customer facing engagements is
solution design and delivery of custom enterprise solutions. In addition, he has
also been involved in the design and development of IBM assets and has
authored articles on developerWorks. Patrick has a Computer Science degree
from California Polytechnic State University, Pomona.
Remote team
Celso Gonzalez has thirteen years of experience in Software Engineering, four
years with IBM Rational. He is currently one of the Rational World Wide Analysis,
Design and Construction leaders. His role is to provide expertise to customers
and field engineers in domains ranging from business modeling to J2EE
development, including requirements management, architecture, and design.
Before joining the World Wide Community of Practice team, Celso was part of
the Rational Unified Process® development tea, where he contributed to areas
such as business modeling, requirements, analysis and design, and legacy
evolution. Celso holds degrees in Mathematics, Computer Science, and
Philosophy.
Your efforts will help increase product acceptance and customer satisfaction. As
a bonus, you will 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 xxxi
Comments welcome
Your comments are important to us!
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.
Part 1 Introduction to
Rational Application
Developer
In this part of the book, we introduce IBM Rational Application Developer for
WebSphere Software.
We then discuss setting up the Workbench, the perspectives, views, and editors,
and the different type of projects.
Chapter 1. Introduction
IBM Rational Application Developer for WebSphere Software V7.0 is an
integrated development environment and platform for building Java Platform
Standard Edition (Java SE) and Java Platform Enterprise Edition (Java EE)
applications with a focus on applications to be deployed to IBM WebSphere
Application Server and IBM WebSphere Portal.
The Rational product suite helps businesses and organizations manage the
entire software development process. Software modelers, architects, developers,
and testers can use the same team-unifying Rational Software Delivery Platform
tooling to be more efficient in exchanging assets, following common processes,
managing change and requirements, maintaining status, and improving quality.
The SDP provides a team-based environment with capabilities that are optimized
for the key roles of a development team including business analyst, architect,
developer, tester, and deployment manager. It enables a high degree of team
cohesion through shared access to common requirements, test results, software
assets, and workflow and process guidance. Combined, these capabilities
improve both individual and team productivity.
Figure 1-1 shows where the Application Developer product fits within the IBM
Rational Software Delivery Platform product set.
WebSphere
Business
Rational Rational
Modeler
Application Performance
Developer Tester
Rational
Manual
Tester
The following is a brief description of each of the products included in the IBM
Rational Software Delivery Platform that share common tooling based on the
IBM Eclipse SDK V3.2:
Rational Software Modeler
The Software Modeler is a UML-based visual modeling and design tool for
system analysts, software architects, and designers who need to clearly
define and communicate their architectural specifications to stakeholders.
This product was known in previous releases as Rational XDE™ Modeler and
is targeted at development shops where the business analyst has a distinct
role of architecture and design (no development).
Rational Software Architect
The Software Architect is a design and construction tool that leverages
model-driven development with UML to create well-architected applications,
including those based on service-oriented architecture (SOA). It unifies
modeling, Java structural review, Web services, Java SE, Java EE, database,
XML, Web development, and process guidance for architects and senior
developers creating applications in Java or C++.
Chapter 1. Introduction 5
This product was known in previous releases as Rational Rose® and Rational
XDE Developer Plus for Java. Software Architect includes architecture and
design capability as well as the full Java EE development functionality
provided by Application Developer. This product is targeted at architects who
are involved in architecture and design activities, as well as application
development. If architects only need the modeling functionality, they should
use the Rational Software Modeler product. Software Architect can also be
used by developers or developers leads pertaining to companies following a
model driven development approach.
Rational Application Developer
The Application Developer is a full suite of development, analysis, and
deployment tools for rapidly implementing Java EE applications, Enterprise
JavaBeans™, portlets, and Web applications. In previous releases this
product was known as Application Developer V6.0 and WebSphere Studio
Application Developer V5.x and is targeted at J2EE developers.
Workbench Workbench
Chapter 1. Introduction 7
Table 1-2 Application development challenges
Challenges Solution tooling
We provide more detail on the these new features in “Summary of new features
in Version 7” on page 12, as well as throughout the chapters of this book.
The IBM Rational Agent Controller included with Application Developer V7.0 is
supported on many platforms running WebSphere Application Server. For details
refer to the Installation Guide, IBM Rational Application Developer V7.0 product
guide (install.html) found on the Application Developer V7 Setup CD 1.
Supported databases
Application Developer V7.0 supports the following database products:
IBM Cloudscape™ V5.1
IBM DB2® Universal Database™ V7.2, V8.1, V8.2, V9.1
IBM DB2 Universal Database for iSeries® V5R2, V5.3, V5.4
IBM DB2 Universal Database for z/OS® and OS/390® V7
IBM DB2 Universal Database for z/OS V8
Apache Derby 10.0, 10.1
Generic JDBC™ 1.0
Informix Dynamic Server V9.2, V9.3, V9.4, V10.0
MySQL 4.0, V4.1
Chapter 1. Introduction 9
Microsoft SQL Server™ 2000 and Microsoft SQL Server 2005
Oracle® 8i V8.1.7, Oracle 9i, Oracle 10g
Sybase Adaptive Server Enterprise V12.x, V15
Product features
This section gives you a summary of the new features of Application Developer
V7. We provide more detailed information on the new features throughout the
chapters of this book.
Chapter 1. Introduction 11
User Control Business Enterprise
Interface Logic Logic Information
Services Connection
HTML
Servlets JavaBeans
JSP JDBC
WML Struts EJB JCA
VML JSF 4GL/EGL JMS
JSF
Portlets SDO
Not in
BPEL Business Process
Application
SOA Integration
Developer
Chapter 1. Introduction 13
For more detailed information and a programming example, refer to
Chapter 18, “Develop Web services applications” on page 811.
Model driven development:
– Support JET transformations.
– Updates to general features (such as Project Explorer, model import, and
model template).
For more detailed information and a programming example, refer to
Chapter 6, “RUP and UML” on page 173.
Rational Unified Process (RUP) integration:
– Process Browser provides search capability for RUP best practices and life
cycle for development.
– Process Advisor view displays RUP information specific to current task.
– This feature is offered in Application Developer and Rational Software
Architect.
For more detailed information and a programming example, refer to
Chapter 6, “RUP and UML” on page 173.
Debugging:
– Support for debugging WebSphere Jython administration scripts.
– Support for DB2 V9.0 Stored Procedure Debug.
Additional enhancements:
– Database tools: Many enhancements around DB2 V9.0, support for virtual
tables and support for triggers/referential constraints.
Note: The EGL tooling, which previously came as part of the Rational
Software Delivery Platform, is now an extension to the platform called Rational
Business Developer Extension (RBDe). This extension is acquired separately
from the base software install.
Specification versions
This section highlights the specification versions found in Application Developer
V7.0, which supports development for the Java Platform Enterprise Edition V1.4.
The only differences between Application Developer V6.0 and Application
Developer V7.0 are in the Java SE version (now supporting V5.0) and
JavaServer Faces (now supporting V1.1).
Web Services Feature Pack with JAX-WS 2.0, optional feature not supported
JAXB 2.0, SOAP 1.2, SAAJ 1.3
Chapter 1. Introduction 15
Table 1-5 WebSphere Application Server specification versions
Specification Application Application
Developer V7.0 Developer V6.0
Eclipse Project
The Eclipse Project is an open source software development project devoted to
creating a development platform and integrated tooling. Figure 1-4 shows the
high-level Eclipse Project architecture and shows the relationship of the following
sub projects:
Eclipse Platform
Eclipse Java Development Tools (JDT)
Eclipse Plug-in Development Environment (PDE)
Another
Eclipse Platform
Tool
Plug-in Workspace
Development Debug
Environment
(PDE)
Their
Platform Runtime Tool
Eclipse Project
Industry leaders like IBM, Borland, Merant, QNX Software Systems, RedHat,
SuSE, TogetherSoft, and WebGain formed the initial eclipse.org board of
directors of the Eclipse open source project.
Eclipse Platform
The Eclipse Platform provides a framework and services that serve as a
foundation for tools developers to integrate and extend the functionality of the
platform. The platform includes a workbench, concept of projects, user interface
libraries (JFace, SWT), built-in help engine, and support for team development
and debug. The platform can be leveraged by a variety of software development
purposes including modeling and architecture, integrated development
environment (Java, C/C++, Cobol), testing, and so forth.
Note: The Eclipse SDK does not include a Java Runtime Environment (JRE)
and must be obtained separately and installed for Eclipse to run.
Chapter 1. Introduction 17
IBM Eclipse SDK V3.2
The IBM Eclipse SDK V3.2 is an IBM branded and value added version of the
Eclipse SDK V3.2. The IBM Eclipse SDK V3.2 includes additional plug-ins and
the IBM Java Runtime Environment (JRE) V1.5 and V1.4.2.
The IBM Eclipse SDK V3.2 is highly desirable for many reasons:
It offers the ability for loose or tight integration of tooling with the platform as
well as industry standard tools and repositories.
It provides frameworks, services, and tools that enable tool builders to focus
on tool building, not on building tool infrastructure. ISVs can develop new
tools to take advantage of the infrastructure and integration points for
seamless integration between the tools and the SDK.
It provides flexibility for rapid support for new standards and technologies
(for example, Web services).
It provides a consistent way of representing and maintaining objects.
The tools have been designed to support a roles-based development model
in which the assets created in one tool are consistent for other tools
(for example, XML created in one tool and used in another).
It provides support for the full life cycle, including test, debug, and
deployment.
The following components are integrated into the IBM Eclipse SDK V3.2:
Eclipse SDK 3.2 (Platform, JDT, PDE)
Eclipse Modeling Framework (EMF)
Eclipse Hyades
C/C++ Development Tooling (CDT)
Graphical Editing Framework (GEF)
XML Schema Infoset Model (XSD)
UML 2.0 Metamodel Implementation (UML2)
IBM Java Runtime Environment (JRE) V1.5 and V1.4.2
In summary, the IBM Eclipse SDK V3.2, which provides an open, portable, and
universal tooling platform, serves as the base for the IBM Rational Software
Delivery Platform common to many Rational products, including Application
Developer V7.0.
Test servers available separately Apache Tomcat V3.2, V4.0, V4.1, V5.0, V5.5
Chapter 1. Introduction 19
Installation and licensing
This section provides a summary for licensing, installation, product updates, and
uninstallation for Application Developer V7.0. Licensing, installation, product
updates, and uninstallation are now achieved through the IBM Installation
Manager (which is installed along with Application Developer V7.0). It is
important to note that whenever using IBM Installation Manager on a previously
installed product, that particular product must not be in use when making
updates.
Installation
This section provides a summary of the new installation architecture, and the key
software and hardware requirements.
All Version 7.0 products include the Rational Software Delivery Platform and
plug-ins. If the Rational Software Delivery Platform is found during the
installation; only the plug-ins for the new product are installed. Products that
contain the functionality of an installed product as well as additional plug-ins will
upgrade the installed product. Products with less functionality than the installed
products will be blocked from installation.
Licensing
Acquiring and activating licenses in Application Developer V7.0 has changed
since the prior release.
This new way of managing licenses by importing activation kits allows you to
upgrade from a trial version to a purchased one by importing a new activation kit,
without having to uninstall the trial version.
License installation: Once you have obtained a license, invoke the IBM
Installation Manager. The detailed steps to import a license are described in
“Installing the license for Rational Application Developer” on page 1291.
Chapter 1. Introduction 21
Updates
Once Application Developer has been installed, the Installation Manager
provides and interface to update the product. This replaces the Rational Product
Updater provided in Application Developer V6.0.
Uninstall
Application Developer V7.0 can be uninstalled interactively through the IBM
Installation Manager.
Migration
Migration includes the migration of Application Developer V6.0 as well as J2EE
projects and code assets.
Metadata and project structure are not updated to the new Application Developer
format. A .compatibility file is added to projects and is used to track the
timestamps of resources.
Migration considerations
Migration information is available on specific components:
Migrating J2EE projects from J2EE 1.3 to J2EE 1.4
Migrating JavaServer Faces resources in a Web Project
Migrating JavaServer Faces resources with Faces Client Components
WDO to SDO migration
Portal Applications with and without JavaServer Faces
Considerations around using the Debugger
EGL reserved words
Chapter 1. Introduction 23
Tools
Application Developer V7.0 includes a wide array of tooling to simplify or
eliminate tedious and error-prone tasks, and provide the ability for Rapid Web
Development. We have listed the key areas of tooling included with Application
Developer:
Java development tools (JDT)
Relational database tools
XML tools
Web development tools
Struts tools
JSF development tools
SDO development tools
Enterprise Generation Language tools
EJB tools
Portal tools
Web services tools
Team collaboration tools
Debugging tools
Performance profiling and analysis tools
Server configuration tools
Testing tools
Deployment tools
Plug-in development tools
Note: Each of the chapters of this book provides a description of the tools
related to the given topic and demonstrates how to use the Application
Developer tooling.
Sample code
The chapters are written so that you can follow along and create the code from
scratch. In places where there is lots of typing involved, we have provided
snippets of code to cut and paste.
Alternatively, you can import the completed sample code from a project
interchange file. For details on the sample code (download, unpack, description,
import interchange file, create databases), refer to Appendix B, “Additional
material” on page 1307.
Much of this book was originally researched and written using Application
Developer V7.0. During the course of completing this book, we upgraded the
system to 7.0.0.2, or even 7.0.0.3 for the Web Services Feature Pack. In some
cases, our samples require at least 7.0.0.2 for the sample to run properly.
For more information, refer to the following link, which contains information on
the latest fixes available for Application Developer:
http://www-306.ibm.com/software/awdtools/developer/application/support/in
dex.html
Summary
This chapter introduced the concepts behind Application Developer and gave an
overview of the features of the various members of the Rational product suite,
and where Application Developer fits with regard to the other products. A
summary of the version numbers of the various features was given and the
Installation Manager was introduced.
Chapter 1. Introduction 25
26 Rational Application Developer V7 Programming Guide
2
When this idea is extended to include database access, some work might be
performed by another process, possibly on another machine. Although this
begins to move us into the client-server environment, the application is often only
using the database as a service—the user interface, business logic, and control
of flow are still contained within the desktop application. This contrasts with full
client-server applications in which these elements are clearly separated and
might be provided by different technologies running on different machines.
This type of application is the simplest type we will consider. Many of the
technologies and tools involved in developing desktop applications, such as the
Java editor and the XML tooling, are used widely throughout all aspects of
Application Developer.
The first scenario deals with a situation in which a bank requires an application to
allow workers in a bank call center to be able to view and update customer
account information. We will call this the Call Center Desktop.
Java 2 Platform Standard Edition (Java SE) provides all the elements necessary
to develop such applications. It includes, among other elements, a complete
object-oriented programming language specification, a wide range of useful
classes to speed development, and a runtime environment in which programs
can be executed. In this chapter, in order to be inline with the latest support of
Java EE level (1.4) in Application Developer V7.0, all discussion of Java SE will
be at version 1.4. Although, it is to be noted that Application Developer V7.0
supports Java SE V5.0.
Java language
Java is a general purpose, object-oriented language. The basic language syntax
is similar to C and C++, although there are significant differences. Java is a
For more information on the aforementioned Java SE V5.0 features, refer to the
following JSRs:
JSR 201 (http://jcp.org/en/jsr/detail?id=201): Contains four of these language
changes; enhanced for loop, enumerated types, static import and autoboxing.
Database access
It is very likely that the Call Center Desktop will have to access data residing in a
relational database, such as IBM DB2 Universal Database.
JDBC
Java SEV1.4 includes JDBC V3.0. In earlier versions of Java SE, the classes
contained in the jaxa.sql package were known as the JDBC Core API, whereas
those in the javax.sql package were known as the JDBC Standard Extension
API (or Optional Package), but now the V1.4 JDBC includes both packages as
standard. Since Java 2 Platform Enterprise Edition V1.4 (Java EE V1.4, which we
will come to shortly) is based on Java SE V1.4, all these features are available
when developing Java EE V1.4 applications as well.
Although JDBC supports a wide range of data store types, it is most commonly
used for accessing relational databases using SQL. Classes and interfaces are
provided to simplify database programming, such as:
java.sql.DriverManager and javax.sql.DataSource can be used to obtain a
connection to a database system.
java.sql.Connection represents the connection that an application has to a
database system.
java.sql.Statement, PreparedStatement, and CallableStatement represent
executable statements that can be used to update or query the database.
java.sql.ResultSet represents the values returned from a statement that has
queried the database.
Various types such as java.sql.Date and java.sql.Blob are Java
representations of SQL data types that do not have a directly equivalent
primitive type in Java.
These features would allow developers to develop test databases and work with
production databases as part of the overall development process. They could
also be used by database administrators to manage database systems, although
they might prefer to use dedicated tools provided by the vendor of their database
systems.
The AWT is implemented natively for each platform’s JVM. AWT interfaces
typically perform relatively quickly and have the same look-and-feel as the
operating system, but the range of GUI components that can be used is limited to
the lowest common denominator of operating system components, and the
look-and-feel cannot be changed.
Swing GUIs do not normally perform as quickly as AWT GUIs, but have a richer
set of controls and have a pluggable look-and-feel.
In many respects, the SWT provides the best of both worlds (AWT and Swing):
It has a rich, portable component model, like Swing.
It has the same look-and-feel as the native operating system, like the AWT.
GUIs built using the SWT perform well, like the AWT, since most of the
components simply pass through to operative system components.
A disadvantage of the SWT is that, unlike the AWT and Swing, it is not a
standard part of Java SE V1.4. Consequently, any application that uses the SWT
has to be installed along with the SWT class libraries. However, the SWT, like the
rest of the components that make up Eclipse, is open source and freely
distributable under the terms of the Common Public License.
1
In the context of windowing systems, a widget is a reusable interface component, such as a menu,
scroll bar, button, text box, or label.
An applet normally runs in a JVM with a very strict security model, by default.
The applet is not allowed to access the file system of the machine on which it is
running and can only make network connections back to the machine from which
it was originally loaded. Consequently, applets are not normally suitable for
applications that require access to databases, since this would require the
database to reside on the same machine as the Web server. If the security
restrictions are relaxed, as might be possible if the applet was being used only on
a company intranet, this problem is not encountered.
An applet is downloaded on demand from the Web site that is hosting it. This
gives an advantage in that the latest version is automatically downloaded each
time it is requested, so distributing new versions is trivial. On the other hand, it
also introduces disadvantages in that the applet will often be downloaded several
times even if it has not changed, pointlessly using bandwidth, and the developer
has little control over the environment in which the applet will run.
Application Developer V7.0 includes a visual editor for Java classes, which offers
this functionality.
For more information on XML, see the home of XML—the World Wide Web
Consortium (W3C) at:
http://www.w3c.org/XML/z
Since JAXP is a standard part of Java SE V1.4, all these features are available in
any Java code running in a JVM.
In most cases, the communication protocol used for interacting with static Web
sites is the Hypertext Transfer Protocol (HTTP).
In the context of our sample scenario, the bank might want to publish a static
Web site in order to inform customers of bank services, such as branch locations
and opening hours, and to inform potential customers of services provided by the
bank, such as account interest rates. This kind of information can safely be
provided statically, since it is the same for all visitors to the site and it changes
infrequently.
Methods
HTTP 1.1 defines several request methods: GET, HEAD, POST, PUT, DELETE,
OPTIONS, and TRACE. Of these, only GET and POST are commonly used in
Web applications:
GET requests are normally used in situations where the user has entered an
address into the address or location field of a Web browser, used a bookmark
or favorite stored by the browser, or followed a hyperlink within an HTML
document.
POST requests are normally used when the user has completed an HTML
form displayed by the browser and has submitted the form for processing.
This request type is most often used with dynamic Web applications, which
include business logic for processing the values entered into the form.
Status codes
The status code returned by the server as the first line of the HTTP response
indicates the outcome of the request. In the event of an error, this information can
be used by the client to inform the user of the problem. In some situations, such
as redirection to another URI, the browser will act on the response without any
interaction from the user. The classes of status code are:
1xx: Information—The request has been received and processing is
continuing.
2xx: Success—The request has been correctly received and processed; an
HTML page accompanies a 2xx status code as the body of the response.
3xx: Redirection—The request did not contain all the information required or
the browser needs to take the user to another URI.
4xx: Client error—The request was incorrectly formed or could not be fulfilled.
5xx: Server error—Although the request was valid, the server failed to fulfill it.
Cookies
Cookies are a general mechanism that server-side connections can use to both
store and retrieve information on the client side of the connection. Cookies can
contain any piece of textual information, within an overall size limit per cookie of 4
kilobytes. Cookies have the following attributes:
Name: The name of the cookie.
Value: The data that the server wants passed back to it when a browser
requests another page.
Domain: The address of the server that sent the cookie and that receives a
copy of this cookie when the browser requests a file from that server. The
domain can be set to equal the subdomain that contains the server so that
multiple servers in the same subdomain receive the cookie from the browser.
Path: Used to specify the subset of URLs in a domain for which the cookie is
valid.
Expires: Specifies a date string that defines the valid lifetime of that cookie.
Secure: Specifies that the cookie is only sent if HTTP communication is taking
place over a secure channel (known as HTTPS).
Non-persistent cookies are created without an expiry date—they will only last for
the duration of the user’s browser session. Persistent cookies are set once and
remain on the user’s hard drive until the expiration date of the cookie. Cookies
are widely used in dynamic Web applications, which we address later in this
chapter, for associating a user with server-side state information.
<html> Tells the browser that the following text is marked up in HTML. The closing
tag </html> is required and is the last tag in your document.
<head> Defines information for the browser that might or might not be displayed to
the user. Tags that belong in the <head> section are <title>, <meta>,
<script>, and <style>. The closing tag </head> is required.
<title> Displays the title of your Web page, and is usually displayed by the browser
at the top of the browser pane. The closing tag </title> is required.
<body> Defines the primary portion of the Web page. Attributes of the <body> tag
enables setting of the background color for the Web pages, the text color, the
link color, and the active and visited link colors. The closing tag </body> is
required.
CSS allows for separation of presentation content of documents from the content
of documents. A CSS file can be referenced by an entire Web site to provide
continuity to titles, fonts, and colors.
Below is a rule for setting the H2 elements to the color red. Rules are made up of
two parts: Selector and declaration. The selector (H2) is the link between the
HTML document and the style sheet, and all HTML element types are possible
selectors. The declaration has two parts: Property (color) and value (red):
H2 { color: red }
Since the technologies are based on Java, most of the features discussed in ,
“Desktop applications” on page 28, are relevant here as well (the GUI features
are less significant). In this section we focus on the additional features required
for developing Web applications.
In the context of our example banking application, thus far we have provided
workers in the bank’s call center with a desktop application to allow them to view
and update account information and members of the Web browsing public with
information about the bank and its services. We will now move into the Internet
banking Web application, called RedBank in this document. We want to extend
the system to allow bank customers to access their account information online,
such as balances and statements, and to perform some transactions, such as
transferring money between accounts and paying bills.
In this book we discuss Java EE V1.4, since this is the version supported by
Application Developer V7.0 and IBM WebSphere Application Server V6.0. Java
EE V1.4 requires Servlet V2.4 and JSP V2.0. Full details of Java EE V1.4 can be
found at:
http://java.sun.com/j2ee/
Servlets
A servlet is a Java class that is managed by server software known as a Web
container (sometimes referred to as a servlets container or servlets engine). The
purpose of a servlet is to read information from an HTTP request, perform some
processing, and generate some dynamic content to be returned to the client in an
HTTP response.
Within the doPost or doGet method, the servlet developer can use the wide range
of features available within Java, such as database access, messaging systems,
connectors to other systems, or Enterprise JavaBeans.
If the servlet has not already been loaded, instantiated, and initialized, the Web
container is responsible for carrying out these tasks. The initialization step is
performed by executing the method:
public void init ()
This is called when the servlet is being unloaded from the Web container.
Within the code for the doPost and doGet methods, the usual processing pattern
is:
Read information from the request. This often includes reading cookie
information and getting parameters that correspond to fields in an HTML form.
Check that the user is in the appropriate state to perform the requested
action.
Delegate processing of the request to the appropriate type of business object.
Update the user’s state information.
Dynamically generate the content to be returned to the client.
The last step could be carried out directly in the servlet code by writing HTML to
a PrintWriter object obtained from the HttpServletResponse object:
PrintWriter out = response.getWriter();
out.println("<html><head><title>Page title</title></head>");
out.println("<body>The page content:");
// etc...
This approach is not recommended, because the embedding of HTML within the
Java code means that HTML page design tools, such as those provided by
Rational Application Developer, cannot be used. It also means that development
roles cannot easily be separated—Java developers must maintain HTML code.
JSP scripting elements (some of which are shown in Table 2-2) are used to
control the page compilation process, create and access objects, define
methods, and manage the flow of control.
Directive Instructions that are processed by the JSP engine when the page is
compiled to a servlet
<%@ ... %> or <jsp:directive.page ... />
Use Bean Retrieves an object from a particular scope or creates an object and
puts it into a specified scope
<jsp:useBean ... />
Get Property Calls a getter method on a bean, converts the result to a String, and
places it in the output
<jsp:getProperty ... />
Some of the standard JSP tags are only provided in an XML-compliant version,
such as <jsp:useBean ... />. Others are available in both traditional form (for
example, <%= ... %> for JSP expressions) or XML-compliant form (for example,
<jsp:expression ... />). These XML-compliant versions have been introduced
in order to allow JSPs to be validated using XML validators.
Tag libraries
Tag libraries are a standard way of packaging tag extensions for applications
using JSPs.
Tag extensions address the problem that arises when a developer wishes to use
non-trivial processing logic within a JSP. Java code can be embedded directly in
the JSP using the standard tags described above. This mixture of HTML and
Java makes it difficult to separate development responsibilities (the HTML/JSP
designer has to maintain the Java code) and makes it hard to use appropriate
tools for the tasks in hand (a page design tool will not provide the same level of
support for Java development as a Java development tool). This is essentially the
reverse of the problem described when discussing servlets above. To address
this problem, developers have documented the View Helper design pattern, as
described in Core J2EE Patterns: Best Practices and Design Strategies by Crupi,
et al. The pattern catalog contained in this book is also available at:
http://java.sun.com/blueprints/corej2eepatterns/Patterns/
Tag extensions are the standard way of implementing View Helpers for JSPs.
Using tag extensions, a Java developer can create a class that implements some
view-related logic. This class can be associated with a particular JSP tag using a
tag library descriptor (TLD). The TLD can be included in a Web application, and
the tag extensions defined within it can then be used in JSPs. The JSP designer
can use these tags in exactly the same way as other (standard) JSP tags. The
JSP specification includes classes that can be used as a basis for tag extensions
Many convenient tags are provided in the JSP Standard Tag Library (JSTL),
which actually includes several tag libraries:
Core tags: Flow control (such as loops and conditional statements) and
various general purpose actions.
XML tags: Allow basic XML processing within a JSP.
Formatting tags: Internationalized data formatting.
SQL tags: Database access for querying and updating.
Function tags: Various string handling functions.
Tag libraries are also available from other sources, such as those from the
Jakarta Taglibs Project (http://jakarta.apache.org/taglibs/), and it is also
possible to develop tag libraries yourself.
Expression Language
Expression Language (EL) was originally developed as part of the JSTL, but it is
now a standard part of JSP (from V2.0). EL provides a standard way of writing
expressions within a JSP using implicit variables, objects available in the various
scopes within a JSP and standard operators. EL is defined within the JSP V2.0
specification.
Filters
Filters are objects that can transform a request or modify a response. They can
process the request before it reaches a servlet, and/or process the response
leaving a servlet before it is finally returned to the client. A filter can examine a
request before a servlet is called and can modify the request and response
headers and data by providing a customized version of the request or response
object that wraps the real request or response. The deployment descriptor for a
Web application is used to configure specific filters for particular servlets or
JSPs. Filters can also be linked together in chains.
Any listener interested in observing the ServletContext life cycle can implement
the ServletContextListener interface, which has two methods,
contextInitialized (called when an application is first ready to serve requests)
and contextDestroyed (called when an application is about to shut down).
Figure 2-1 shows the interaction between the Web components and a relational
database, as well as the desktop application discussed in “Desktop applications”
on page 28.
Web
JavaBean
Browser
JavaServer
Page
Java Relational
Application Database
Desktop
Application
Struts
The model-view-controller (MVC) architecture pattern is used widely in
object-oriented systems as a way of dividing applications into sections with
well-defined responsibilities:
Model: 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.
View: Implements the rendering of the model, displaying the results of
processing for the use, and manages user input.
Controller: Receives user input events, determines which action is
necessary, and delegates processing to the appropriate model objects.
In dynamic Web applications, the servlet normally fills the role of controller, the
JSP fills the role of view and various components, and JavaBeans or Enterprise
JavaBeans fill the role of model. The MVC pattern is described in more detail in
Chapter 13, “Develop Web applications using Struts” on page 541, as will Struts.
In the context of our banking scenario, this technology does not relate to any
change in functionality from the user’s point of view. The problem being
addressed here is that, although many developers might want to use the MVC
The Action object is then invoked to perform the required processing. This
Action object is provided by the developer using Struts to create a Web
application and can use any convenient technology for processing the request.
The Action object is the route into the model for the application. Once processing
has been completed, the Action object can indicate what should happen
next—the ActionServlet will use this information to select the appropriate
response agent (normally a JSP) to generate the dynamic content to be sent
back to the user. The JSP represents the view for the application.
Struts provides other features, such as form beans, to represent data entered
into HTML forms and JSP tag extensions to facilitate Struts JSP development.
Figure 2-1 on page 47 still represents the structure of a Web application using
Struts. Although Struts provides us with a framework on which we can build our
own applications, the technology is still the same as for basic Web applications.
In the RedBank Web application we want to make the user interface richer, while
still allowing us to use the MVC architecture described in “Struts” on page 47. In
addition, our developers want a simple, lightweight, object-oriented database
access system, which will remove the need for direct JDBC coding.
SDO was originally developed by IBM and BEA Systems and is now the subject
of a Java specification request (JSR 235), but has not yet been standardized
under this process.
SDOs are designed to simplify and unify the way in which applications handle
data. Using SDO, application programmers can uniformly access and manipulate
data from heterogeneous data sources, including relational databases, XML data
sources, Web services, and enterprise information systems.
More information on JSF and SDO can be found in the IBM Redbooks
publication, WebSphere Studio V5.1.2 JavaServer Faces and Service Data
Objects, SG24-6361. This book covers the use of these technologies in
WebSphere Studio rather than the Rational Software Development Platform, but
the coverage of the technologies is still very useful.
Figure 2-2 shows how JSF and SDO can be used to create a flexible, powerful
MVC-based Web application with simple database access.
JSF
Servlet
Web SDO
SDO
Browser Mediator
JSP using
JSF
Relational
Database
Figure 2-3 illustrates the overall AJAX interaction between the client browser and
the server-side application. Refer to the list below the figure for the generic
sequence of steps that get executed on a typically AJAX submission.
Client Server-side
HTTP Request
XMLHttpRequest WebSphere
send()/callback() Application Server
XML Response
JavaScript
function
invocation DOM updates
updates
Portal applications
Portal applications run on a Portal Server and consist of portal pages that are
composed of portlets. Portlets can share and exchange resources and
information to provide a seamless Web interface.
In the context of our sample scenario, we can use a portal application to enhance
the user experience. The RedBank Web application can be integrated with the
static Web content providing information about branches and bank services. If
the customer has credit cards, mortgages, personal loans, savings accounts,
shares, insurance, or other products provided by the bank or business partners,
these could also be seamlessly integrated into the same user interface, providing
the customer with a convenient single point of entry to all these services.
Within the bank, the portal can also be used to provide convenient intranet
facilities for employees. Sales staff can use a portal to receive information on the
latest products and special offers, information from human resources, leads from
colleagues, and so on.
Application Developer V7.0 includes the WebSphere Portal Toolkit and the
WebSphere Portal V5.1/V6.0 Integrated Test Environment.
Figure 2-4 shows how portal applications fit in with other technologies mentioned
in this chapter.
WebSphere Security
Portal Service
Enterprise JavaBeans
Now that the RedBank Web application is up and running, more issues arise.
Some of these relate to the services provided to customers and bank workers
and some relate to the design, configuration, and functionality of the systems that
perform the back-end processing for the application.
First, we want to provide the same business logic in a new application that will be
used by administration staff working in the bank’s offices. We would like to be
able to reuse the code that has already been generated for the RedBank Web
application without introducing the overhead of having to maintain several copies
of the same code. Integration of these business objects into a new application
should be made as simple as possible.
Finally, the bank has legacy systems, not written in Java, that we would like to be
able to update to use the new functionality provided by these business objects.
We would like to use a technology that will allow this type of interoperability
between different platforms and languages.
We can get all this functionality by using Enterprise JavaBeans (EJBs) to provide
our back-end business logic and access to data. Later, we will see how EJBs can
also allow us to integrate messaging systems and Web services clients with our
application logic.
Session EJBs
Session EJBs are task-oriented objects, which are invoked by an EJB client.
They are non-persistent and will not survive an EJB container shutdown or crash.
There are two types of session EJB: Stateless and stateful.
Session beans often act as the external face of the business logic provided by
EJBs. The session facade pattern, described in many pattern catalogs including
Core J2EE Patterns: Best Practices and Design Strategies by Crupi, et al.,
describes this idea. The client application that needs to access the business logic
provided by some EJBs sees only the session beans. The low-level details of the
persistence mechanism are hidden behind these session beans (the session
bean layer is known as the session facade). As a result of this, the session beans
that make up this layer are often closely associated with a particular application
and might not be reusable between applications.
Entity EJBs
Entity EJBs are designed to provide an object-oriented view of data. The data
itself is stored by an external persistence mechanism, such as a relational
database or other enterprise information system. Entity beans should normally
be designed to be general purpose, not designed to work with one particular
application—the application-specific logic should normally be placed in a layer of
session EJBs that use entity beans to access data when required, as described
above.
Once an entity bean has been created, it can be found using a key or using some
other search criteria. It persists until it is explicitly removed. Two main types of
entity bean exist: Container-managed or bean-managed persistence.
The methods required to traverse the relationships are generated as part of the
development and code generation mechanisms.
Only SELECT statements can be created using EJB QL. EJB QL is like a
cut-down version of SQL, using the abstract persistence schema defined by the
EJBs rather than tables and columns. The language has been extended in EJB
V2.1 compared with V2.0. A query can contain input parameters that correspond
to the arguments of the finder or select method.
Figure 2-5 shows how EJBs work with other technologies already discussed. The
provision of remote interfaces to EJBs means that the method calls made by the
JavaBean to the session EJB could take place across a network connection,
Java
Adding EJBs to the picture
Servlet
Web Session
JavaBean
Browser EJB
JavaServer
Page
Entity
EJB
Java Relational
Application Database
Security
The Java EE specification requires that the same authentication mechanisms
should be made available for Java EE Application Clients as for other types of
Java EE components. The authentication features are provided by the Java EE
Application Client container, as they are in other containers within Java EE. A
Java EE platform can allow the Java EE Application Client container to
communicate with an application server to use its authentication services;
WebSphere Application Server allows this.
Naming
The Java EE specification requires that Java EE Application Clients should have
exactly the same naming features available as are provided for Web components
and EJBs. Java EE Application Clients should be able to use the Java Naming
and Directory Interface (JNDI) to look up objects using object references as well
as real JNDI names. The reference concept allows a deployer to configure
references that can be used as JNDI names in lookup code. The references are
bound to real JNDI names at deployment time, so that if the real JNDI name is
subsequently changed, the code does not have to be modified or
recompiled—only the binding needs to be updated.
Code to look up an EJB might look like this (this is somewhat simplified):
accountHome = (AccountHome)initialContext
.lookup("java:comp/env/ejb/account");
Deployment
The Java EE specification only specified the packaging format for Java EE
Application Clients, not how these should be deployed—this is left to the Platform
provider. The packaging format is specified, based on the standard Java JAR
format, and it allows the developer to specify which class contains the main
method to be executed at run time.
Java EE application clients for the WebSphere Application Server platform run
inside the Application Client for WebSphere Application Server. This is a product
that is available for download from developerWorks, as well the WebSphere
Application Server installation CD.
Figure 2-6 shows how Java EE Application Clients fit into the picture; since these
applications can access other Java EE resources, we can now use the business
logic contained in our session EJBs from a stand-alone client application. Java
EE Application Clients run in their own JVM, normally on a different machine
from the EJBs, so they can only communicate using remote interfaces.
J2EE
Java
Application
Servlet
Client
Web Session
JavaBean
Browser EJB
JavaServer
Page
Entity
EJB
Java Relational
Application Database
So far, everything is quite self-contained. Although clients can connect from the
Web to use the Internet banking facilities, the business logic is all contained
within the bank’s systems, and even the Java application and Java EE
Application Client are expected to be within the bank’s private network.
The next step in developing our service is to enable mortgage agents, who
search many mortgage providers to find the best deal for their customers, to
access business logic provided by the bank to get the latest mortgage rates and
repayment information. While we want to enable this, we do not want to
compromise security, and we need to take into account that fact that the
mortgage brokers might not be using systems based on Java at all.
We might also want to be able to share information with other banks; for
example, we might want to exchange information on funds transfers between
banks. Standard mechanisms to perform these tasks have been provided by the
relevant government body.
These issues are all related to interoperability, which is the domain addressed by
Web services. Web services will allow us to enable all these different types of
communication between systems. We will be able to use our existing business
logic where applicable and develop new Web services easily where necessary.
A service provider creates a Web service and publishes its interface and access
information to a service registry (or service broker). A service requestor locates
entries in the service registry, then binds to the service provider in order to invoke
its Web service.
Web services use the following standards:
SOAP: A XML-based protocol that defines the messaging between objects
Web Services Description Language (WSDL): Describes Web services
interfaces and access information
Universal Description, Discovery, and Integration (UDDI): A standard
interface for service registries, which allows an application to find
organizations and services
UD
DI DI
UD AP SO
AP
SO
Web
Web
Service
Service
Client SOAP
(use (create)
)
Service
Description
(WSDL)
Web services are now included in the Java EE specification (from V1.4), so all
Java EE application servers that support Java EE V1.4 have exactly the same
basic level of support for Web services; some will also provide enhancements as
well.
The key Web services-related Java technologies that are specified in the Java
EE V1.4 specification are:
Web Services for J2EE V1.1:
http://jcp.org/en/jsr/detail?id=921
Note: The URL quoted above for the Web Services for Java EE V1.1
specification leads to a page entitled JSR 921: Implementing Enterprise
Web Services 1.1. This is the V1.1 maintenance release for Web Services
for Java EE, which was originally developed under JSR 109.
The Web services support in Java EE also relies on the underlying XML support
in the Platform, provided by JAXP and associated specifications.
Web Services for Java EE defines the programming and deployment model for
Web services in Java EE. It includes details of the client and server programming
models, handlers (a similar concept to servlets filters), deployment descriptors,
container requirements, and security.
The Java EE V1.4 specification allows for ordinary Java resources and stateless
session EJBs to be exposed as Web services. The former, known as JAX-RPC
service endpoint implementations, can be hosted within the Java EE application
server’s Web container, and the latter can be hosted within the EJB container.
The tooling should also allow skeleton Web services to be created from WSDL
files and should provide assistance in developing Web services clients, based on
information obtained from WSDL files.
Figure 2-8 shows how the Web services technologies fit into the overall
programming model we have been discussing.
Web
services Web Web
Web Web
Service Service
Service Service
Client Client
J2EE
Java
Application
Servlet
Client
Web Session
JavaBean
Browser EJB
JavaServer Entity
Page EJB
Java Relational
Application Database
Messaging systems
Although Web services offer excellent opportunities for integrating disparate
systems, they currently have some drawbacks:
Security specifications are available for Web services, but they have not been
fully implemented on all platforms at this stage.
Web services do not provide guaranteed delivery, and there is no widely
implemented, standard way of reporting the reliability of a Web service.
The bank has numerous automatic teller machines (ATMs), each of which has a
built-in computer providing user interface and communication support. The ATMs
are designed to communicate with the bank’s central computer systems using a
secure, reliable, highly scalable messaging system. We would like to integrate
the ATMs with our system so that transactions carried out at an ATM can be
processed using the business logic we have already implemented. Ideally, we
would also like to have the option of using EJBs to handle the messaging for us.
Many messaging systems exist that provide features like these. IBM’s solution in
this area is IBM WebSphere MQ, which is available on many platforms and
provides application programming interfaces in several languages. From the
point of view of our sample scenario, WebSphere MQ provides Java interfaces
that we can use in our applications—in particular, we will consider the interface
that conforms to the Java Message Service (JMS) specification. The idea of JMS
is similar to that of JDBC—a standard interface providing a layer of abstraction
for developers wishing to use messaging systems without being tied to a specific
implementation.
From a development point of view, MDBs are the simplest type of EJB, since they
do not have clients in the same sense as session and entity beans. The only way
of invoking an MDB is to send a message to the endpoint or destination that the
MDB is listening to. In EJB V2.0, MDBs only dealt with JMS messages, but in
EJB V2.1 this is extended to other messaging systems. The development of an
MDB is different depending on the messaging system being targeted, but most
MDBs are still designed to consume messages via JMS, which requires the bean
class to implement the javax.jms.MessageListener interface, as well as
javax.ejb.MessageDrivenBean.
According to this pattern, the MDB simply acts as an adapter, receiving and
parsing the message, then invoking the business logic to process the message
using the session bean layer.
Web Web
Web Web
Service Service
Service Service
Client Client
J2EE
Java
Application
Servlet
Client
Web Session
JavaBean
Browser EJB
JavaServer
Page
Entity
EJB
Message Message-
Messaging
Producer Driven
Server
Application EJB
Messaging systems
and MDBs
Java Relational
Application Database
Summary
In this chapter we reviewed the basic technologies supported by Application
Developer: Desktop applications, static Web sites, dynamic Web applications,
Enterprise JavaBeans, Web services, and messaging.
The Welcome page presents six icons, each including a description that is visible
through hover help (moving the mouse over an icon to display a description).
Table 3-1 provides a summary of each icon.
Web Resources URL links to Web pages where you can find
relevant and timely tips, articles, updates, and
references to industry standards.
The Welcome page appearance can also be customized through the preferences
page. You can click the Customize Page icon on the top right corner of the
Welcome page to open the Preferences dialog (Figure 3-2). You can use this
preference page to select one of the pre-defined themes, which affects the
overall look of the welcome. You can also select which pages will be displayed,
and the visibility, layout, and priority of the items within each page.
Users experienced with Application Developer or the concepts that the product
provides can close the Welcome page by clicking the X for the view to close it
down, or clicking the icon in the top right corner arrow. They will then be
presented with the default perspective, the J2EE perspective. Each perspective
in Application Developer contains multiple views, such as the Project Explorer
view, Outline view, and others. More information regarding perspectives and
views are provided in Chapter 4, “Perspectives, views, and editors” on page 117.
The top right of the window has a shortcut icon (Figure 3-3), which allows you to
open available perspectives, and places them in the shortcut bar next to it. Once
the icons are on the shortcut bar, you are able to navigate between perspectives
that are already open. The name of the active perspective is shown in the title of
the window, and its icon is in the shortcut bar on the right side as a pushed
button.
Workspace basics
When you start up Application Developer, you are prompted to provide a
workspace to start up. On the first startup, the path looks something like the
following sample, depending on the installation path:
c:\Documents and Settings\<user>\IBM\rationalsdp7.0\workspace
Where <user> is the Windows user ID you used to login.
The Application Developer workspace is a private work area created for the
individual developer, and it holds the following information:
Application Developer environment meta data, such as configuration
information and temporary files
Resources that are modified and saved are reflected on the local file system.
Users can have many workspaces on their local file system to contain different
projects that they are working on, or different versions. Each of these
workspaces can be configured differently, because they have their own copy of
meta data with configuration data for that workspace.
Application Developer allows you to open more than one Workbench at a time.
It opens another window into the same workspace, allowing you to work in two
differing perspectives. Changes that are made in one window are reflected to the
other windows. You are not permitted to work in more than one window at a time,
that is, you cannot switch between windows while in the process of using a
wizard in one window.
This ensures that on the next startup of Application Developer that the
workspace automatically uses the directory specified initially, and it will not
prompt for the workspace in the future.
The other way to enforce the use of a particular workspace is by using the -data
<workspace> command-line argument on Application Developer, where
<workspace> is a path name on the local machine where the workspace is
located, and should be a full path name to remove any ambiguity of location of
the workspace.
By using the -data argument, you can start a second instance of Application
Developer that uses a different workspace. For example, if your second instance
should use the MyWorkspace folder, you can launch Application Developer with
this command (assuming that the product has been installed in the default
installation directory):
c:\Program Files\IBM\SDP70\eclipse.exe -data c:\MyWorkspace
There are a number of arguments that you can add when launching Application
Developer; some useful arguments are explained in Table 3-2. More advanced
arguments can be found by searching for Running Eclipse in Help → Help
Contents.
-consolelog Mirrors the Eclipse platform's error log to the console used
to run Eclipse. Handy when combined with -debug.
-debug [optionsFile] Puts the platform in debug mode and loads the debug
options from the file at the given location, if specified. This
file indicates which debug points are available for a plug-in
and whether or not they are enabled. If a file location is not
given, the platform looks in the directory that eclipse was
started from for a file called .options. Both URLs and file
system paths are allowed as file locations.
-vm vmPath This optional option allows you to set the location of Java
Runtime Environment (JRE) to run Application Developer.
Relative paths are interpreted relative to the directory that
Eclipse was started from.
Memory considerations
Use the -vmargs argument to set limits to the memory that is used by Application
Developer. For example, with 1 GB RAM, you might be able to get better
performance by limiting the memory:
-vmargs -Xmx512M
These arguments significantly limit the memory utilization. Setting the -Xmx
argument below 512M does begin to degrade performance.
Figure 3-5 Setting the prompt dialog box for workspace selection on startup
The primary 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.
Log files
There are two main log files in the .metadata directory of the workspace folder:
CommonBaseEvents.xml: This log file is usually of interest to plug-in
developers. A new CommonBaseEvents.xml file is created every time you start
the workbench and the previous CommonBaseEvents.xml file is archived.
Archived file names have the form CommonBaseEventstimestamp.xml where
timestamp is the standard Java timestamp.
This log file can be imported into Log and Trace Analyzer for viewing,
analysis, sorting, filtering, and correlation.
Preferences
The Application Developer Workbench preferences can be modified by selecting
Window → Preferences (Figure 3-8).
In the left pane you can navigate through category of preferences. Each
preference has its own page, where you can change the initial options. The
Preferences dialog pages can be searched using the filter function.
Automatic builds
Builds, or a compilation of Java code 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 automatic build feature, then
to perform a build you have to explicitly start it. This might be 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 → General → Workspace and clear Build automatically
(Figure 3-9).
Manual builds
Although the automatic build feature might be adequate for many developers,
there are a couple of scenarios in which a developer might want to perform a
build manually. First, some developers do not want to build automatically
because it can slow down development. In this case the developer needs a
method of building at the time of their choosing. Second, there are cases when
you want to force a build of a project or all projects to resolve build errors and
dependency issues. To address these types of issues, Application Developer
provides the ability to perform a manual build, known as a clean build.
To build all resources, even those that have not changed since the last build, do
these steps:
Select the desired project in the Project Explorer.
Select Project → Clean.
In the Clean dialog select one of the following options and click OK:
– Clean all projects: This performs a build of all projects.
– Clean selected projects: <project> (The project selected in the previous
step is selected by default or you can select it from the projects list.)
Capabilities
Application Developer has the ability to enable and disable capabilities in the
tooling. The default setup does not enable some of the capabilities, such as team
support for Rational ClearCase, Web services development, or profiling and
logging.
Tip: You can display the Welcome page by selecting Help → Welcome.
The Welcome page provides an icon in the shape of a human figure in the
bottom right-hand corner used to enable roles (Figure 3-10). These assist in
setting up available capabilities for the user of the tool through the following
process.
The scenario that we will attempt is enable the team capability or role so that the
developer can save their resources in a repository.
In the Welcome page move the mouse to the bottom right corner over the
human figure. Click the icon.
Move the mouse until it is over the desired capability or role, and click the
icon. For example, move the mouse over the Team capability or role so
that it is highlighted and a matching text is shown at the top (Figure 3-10), and
click the icon; this enables the Team capability.
Figure 3-11 Setting the Team capability using Windows preferences: Part 1
This enables the Profiling and Logging capability and open the Profiling and
Logging perspective.
File associations
The File Associations preferences page 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. To open the preferences page, do
these steps:
Select Window → Preferences → General → Editors → File Associations
(Figure 3-14).
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.
Note: Optionally, you can set this program as the default program for this file
type by clicking Default.
Now you can open a .ddl file by using the context menu on the file and selecting
Open With, and selecting the appropriate program.
Local history
A local 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 edition or even restore a deleted file. You can also compare
the content of all the local editions. Each edition 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.
Table 3-3 explains the options for the local history preferences.
Days to keep files Indicates for how many days you want to maintain changes
in the local history. History states older than this value are
lost.
Maximum entries per Indicates how many history states per resource you want to
file 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 resource is over this size, no local history is kept
for that resource.
To replace a file with an edition from the local history, do these steps:
This assumes you have a Java file in your workspace. If you do not, add or
create a file.
Select the file, right-click, and select Replace With → Local History.
Select the desired file time stamp and then click Replace.
Perspectives preferences
The Perspectives preferences page enables you to manage the various
perspectives defined in the Workbench. To open the page, select Window →
Preferences → General → Perspectives (Figure 3-16).
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 from here.
The default option is to use the internal Web browser. To change, select Use
external Web browser and select a browser from the available list; otherwise
you can click New to add a new Web browser.
Internet preferences
The Internet preferences in Application Developer have three types of settings
available to be configured:
Cache
FTP
Proxy settings
Only proxy settings is covered in this section, with the other two settings you can
refer to Application Developer’s help.
Proxy settings
When using Application Developer and working within an intranet, you might
want to use a proxy server to get across a company firewall to access the
Internet.
To set the preferences for the HTTP proxy server within the Workbench to allow
Internet access from Application Developer, do these steps:
Select Window → Preferences → Internet → Proxy Settings (Figure 3-18).
Select Enable Proxy and enter the proxy host and port. There are additional
optional settings for the use of SOCKS and enabling proxy authentication.
Depending on the type of Java coding you plan to do, you might 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 want to reuse
in other projects. Once you have created a Java project, you can add any of
these variables to the project’s classpath.
Certain class path variables are set internally and cannot be changed in the
Classpath variables preferences:
JRE_LIB: The archive with the runtime JAR file for the currently used JRE.
JRE_SRC: The source archive for the currently used JRE.
JRE_SRCROOT: The root path in the source archive for the currently used JRE.
Show method return types If selected, methods displayed in views show the return
type.
Show method type If selected, methods displayed in views show their type
parameters parameters.
Show categories If selected, method, field, and type labels contain the
categories specified in their Javadoc™ comment.
Show members in Package If selected, displays the members of the class and their
Explorer scope such as private, private or protected, including
others.
Fold empty packages in If selected, folds the empty packages that do not
hierarchical layout contain resources or other child elements.
Compress package name If selected, compresses the name of the package based
segments on a pattern supplied in the dialog below the check box.
Stack views vertically in the If selected, displays the views in the Java Browsing
Java Browsing perspective perspective vertically rather than horizontally.
To specify types and packages to hide in the Open Type dialog and content
assist or quick fix proposals, do these steps:
In the Preferences dialog select Java → Appearance → Type Filters.
You can either create a new filter or add packages to the type filter list. The
default is to hide nothing.
Code style
The Java code style preferences allow you to configure naming conventions,
style rules and comment settings.
These coding conventions are used in the generation of setters and getters for
Java classes:
Whenever a prefix of m followed by a capital letter is found on an attribute, this
would ignore the prefix and generate a getter and setter without the prefix.
If the prefix is not found followed by a capitalized letter, then the setter and
getter would be generated with the first letter capitalized followed by the rest
of the name of the attribute.
The settings described in Table 3-5 specify how newly generated code should
look like. These settings are configured in the Code Style preferences page
(Figure 3-22 on page 101).
Qualify all generated field If selected, field accesses are always prefixed with
accesses with 'this.' this., regardless whether the name of the field is
unique in the scope of the field access or not.
Use 'is' prefix for getters that If selected, the names of getter methods of boolean
return boolean type are prefixed with is rather than get.
Automatically add comments If selected, newly generated methods and types are
for new methods and types automatically generated with comments where
appropriate.
Exception variable name in Specify the name of the exception variable declared in
catch blocks catch blocks.
White Space: Format where the spaces are placed in the code based on a
number of Java constructs (Figure 3-26).
Blank Lines: Specify where you want to place blank lines in the code for
readability or style guidelines, for example:
– Before and after package declaration
– Before and after import declaration
– Within a class:
• Before first declaration
• Before field declarations
• Before method declarations
• At the beginning of a method body
New Lines: Specifies the option of where you want to insert a new line, for
example:
– In empty class body
– In empty method body
– In empty annotation body
– At end of file
Line Wrapping: Provides the style rule on what should be performed with the
wrapping of code, for example:
– Maximum line width (default is 80)
– Default indentation (2)
– How declarations, constructors, function calls, and expressions are
wrapped
Comments: Determine the rules of the look of general comments and of
Javadoc that are in the Java code.
Smart caret positioning at If selected, the Home and End commands jump to the
line start and end first and last non white space character on a line.
Smart caret positioning in If selected, there are additional word boundaries inside
Java names (overrides |Camel|Case| Java names.
platform behavior)
Report problems as you If selected, the editor marks errors and warnings as you
type type, even if you do not save the editor contents. The
problems are updated after a short delay.
Light bulb for quick If selected, a light bulb shows up in the vertical ruler
assists whenever a quick assist is available.
Appearance color options The colors of various Java editor appearance features are
specified here.
Content assist
The content assist feature in Application Developer is used in assisting a
developer in writing their code rapidly and reducing the errors in what they are
writing. It is a feature that is triggered by pressing Ctrl+Spacebar, and assists
the developer in completion of a variable or method name when coding.
Folding
When enabled, a user of the Workbench can collapse a method, comments, or
class into a concise single line view.
Mark occurrences
When enabled, this highlights all occurrences of the types of entities described in
the screen (Figure 3-31). In the Java editor, by selecting an attribute (for
example), the editor displays in the far right-hand context bar all occurrences in
the resource of that attribute. This can be navigated to by selecting the highlight
bar in that context bar.
The templates can be used by typing a part of the statement you want to add;
and then by pressing Ctrl+Spacebar in the Java editor, a list of templates
matching the key will appear in the presented list. Note that the list is filtered as
you type, so typing the few first characters of a template name will reveal it.
The symbol in front of each template (Figure 3-32), in the code assist list is
colored yellow, so you can distinguish between a template and a Java statement
entry.
There are also some predefined variables available that can be added in the
template. These variables can be inserted by clicking Insert Variable. This
brings up a list and a brief description of the variable.
Templates that have been defined can be exported and later imported into
Application Developer to ensure that a common environment can be set up
among a team of developers.
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.
The compiler preferences page includes four sub-pages that allow you to set the
appropriate behavior required to ensure that you obtain the required information
from the compiler:
Building: Indicates your preferences for the Building settings, such as build
path problems, output folder, and so on.
Errors/Warnings: Defines the level the errors and warnings in several
categories such as code style, potential programming problems, unnecessary
code, annotations, and so on.
Javadoc: Provides configuration settings on how to deal with Javadoc
problems that might arise and what to display as errors.
Task Tags: Enables you to create, edit and remove Java task tags.
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 the product is used; however, to ensure that your application is
targeted for the correct platform, the same JRE or at least the same version of
the JRE should be used to compile the code. If the application is targeted for a
WebSphere Application Server V6.1, then the JRE should be set to use the JRE
associated with this environment in Application Developer.
Note: Changing the JRE used for running does not affect the way Java source
is compiled. You can adjust the build path to compile against custom libraries.
By default, the JRE used to run the Workbench will be used to build and run Java
programs. It appears selected in the list of installed JREs. If the target JRE that
the application will run under is not in the list of JREs, then this can be installed
on the machine and added onto the list. You can add, edit, or remove a JRE.
Let us assume that the application you are writing requires the latest JRE 1.6
located in the directory C:\Program Files\Java\jre1.6\. The procedure to add a
new JRE is as follows:
Click Add.
In the Add JRE dialog, enter the following items:
– JRE type: A drop-down box indicating whether a Standard VM or Standard
1.1.x VM. In most circumstances this will be set to Standard VM.
– JRE name: Any name for the JRE to identify it.
– JRE home directory: The location of the root directory of the install for the
JRE: C:\Program Files\Java\jre1.6\
– Default VM arguments: Arguments that are required to be passed to the
JRE.
Summary
In this chapter we described how to configure the Workbench preferences in
regard to logging, automatic builds, development capabilities, and Java
development.
This chapter starts with an introduction to the common structures and features
applicable to all perspectives in Application Developer and then describes its
help facility. Following this we provide a brief overview of the main features of
each perspective available in IBM Rational Application Developer V7.0. Most of
these perspectives are described in detail in the chapters within this book.
Views provide different ways of looking at the resource you are working on and
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.
Perspectives
Perspectives provide a convenient grouping of views and editors that match a
particular way of using Rational Application Developer. A different perspective
can be used to work on a given workspace depending on the role of the
developer or the task that has to be done.
For each perspective, Application Developer defines an initial set and layout of
views and editors for performing a particular set of development activities. For
example, the J2EE perspective contains views and editors applicable for EJB
development. The layout and the preferences in each perspective can be
changed and saved as a customized perspective and used again later. This is
described in “Organizing and customizing perspectives” on page 122.
A view can appear by itself or stacked with other views in a tabbed notebook
arrangement. To quickly move between views in a given perspective, you can
select Ctrl-F7 (and hold down Ctrl), which will show all the open views and let the
user move quickly to the desired view. Press F7 until the required view is
selected, then release to move to that view.
Editors
When you open a file, Rational Application Developer automatically opens the
editor that is associated with that file type. For example, the Page Designer is
opened for .html, .htm, and .jsp files, while the Java editor is opened for .java
and .jpage files.
Editors that have been associated with specific file types will open in the editor
area of the Workbench. By default, editors are stacked in a notebook
arrangement inside the editor area. If there is no associated editor for a resource,
Rational Application Developer will open the file in the default editor, which is a
text editor. It is also possible to open a resource in another editor by using the
Open With option from the context menu.
To quickly move between editors open on the workspace, you can select Ctrl-F6
(and hold down Ctrl) which will show all the open editors and let the user move
quickly to the desired one. Press F6 until the required editor is selected, then
release.
Perspective layout
Many of Rational Application Developer’s perspectives use a similar layout.
Figure 4-1 shows the general layout that is used for most default perspectives.
Toolbar
Project Explorer
Outline
Palette
Editor
Tasks
Problems
Figure 4-1 Perspective layout
Switching perspectives
There are two ways to open another perspective:
Click the Open a perspective icon ( ) in the top right corner of the
Workbench working area and select the appropriate perspective from the list.
Select Window → Open Perspective and select one from the drop-down list
shown.
In both cases there is also an Other option, which when selected displays the
Open Perspective dialog that shows the complete list of perspectives (see
Figure 4-2). Here the user can select the required perspective and click OK.
Tips:
The name of the perspective is shown in the window title area along with
the name of the file open in the editor, which is currently at the front.
To close a perspective, right-click the perspective's button on the shortcut
bar (top right) and select Close.
To display only the icons for the perspectives, right-click somewhere in the
shortcut bar and clear the Show Text option.
Each perspective requires memory, so it is good practice to close
perspectives that are not used to improve performance.
The Shortcuts tab provides the facility to specify which options are shown on the
New, Open Perspective, and Show View menu options within the current
perspective. Select the menu you want to customize from the Submenus
drop-down window and check the boxes for whichever options you want to
appear. Note that items you do not select are still accessible by clicking the
Other menu option, which is always present for these options.
The Commands tab of the dialog allows you to select command groups that will
be added to the menu bar or tool bar for Rational Application Developer in this
perspective.
Navigation
options
Search
options
In the Help window you see the available books in the left pane and the content in
the right pane. When you select a book ( ) in the left pane, the appropriate
table of contents opens up and you can select a topic ( ) within the book.
When a page ( ) is selected, the page content is displayed in the right pane.
You can navigate through the help documents by clicking Go Back and Go
Forward ( ) in the toolbar for the right pane.
Also, the left hand pane of the help window can be tabbed between the
Contents, Index, Search Results, and Bookmarks views, which provide
different methods of accessing information the help contents.
Also, at any time it is possible to display the Help contents as a view within the
workspace, by selecting Window → Show View → Other → Help → Help.
Once the search list has been saved, it can be selected as a search scope from
the main search page.
Clicking Go performs the search across the selected scope and display the
results in the Search Results view, and from there the user can click on links to
pages within the Help facility.
Available perspectives
In this section all the perspectives that are available in Rational Application
Developer are briefly described. The perspectives are covered in alphabetical
order which is how they appear in the Select Perspective dialog.
Application Developer Help has a large section on the details of using this
perspective.
Data perspective
The Data perspective (Figure 4-9) lets you access a set of relational database
tools, where you can create and manipulate the database definitions for your
projects.
More details about using the Data perspective can be found in Chapter 9,
“Develop database applications” on page 355.
The Console and Tasks views have already been discussed in earlier sections of
this chapter.
More information about the Debug perspective can be found in Chapter 22,
“Debug local and remote applications” on page 1041.
For more information about the Generic Log Adapter perspective, refer to the
Eclipse documentation at:
http://www.eclipse.org/tptp/home/documents/tutorials/gla/getting_started_gl
a.html
J2EE perspective
The p perspective (Figure 4-11) is used for working with Enterprise Application
projects and EJB projects. It contains the following views typically used when
developing J2EE applications:
Project Explorer view—This view shows information about your J2EE and
other projects in the workspace. It is similar to the Navigator view in that it
shows the files and folders that make up a project but includes extra icons
specific for a project type such as J2EE deployment descriptors and the
Security Editor (both for J2EE projects). For Web projects the Project Explorer
view includes icons for the Web deployment descriptor, the Web Navigation
view, the Web Diagram view and the Security Editor.
Snippets view—The Snippets view lets you 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. The available snippets are
arranged in drawers, such as JSP or EJB, and the drawers can be
customized by right-clicking a drawer and selecting Customize.
Properties view—This view provides a tabular view of the properties and
associated values of objects in files you have open in an editor. The format of
this view differs depending on what is selected in the editor, and by default it
shows the file properties (last modification date, file path and so on).
The Outline, Servers, Problems, Tasks, and Database Explorer views are also
relevant to the Web perspective and have already been discussed in earlier
sections of this chapter.
More details about using the J2EE perspective can be found in Chapter 16,
“Develop Web applications using EJBs” on page 719.
It consists of a main editor area and displays by default, the following views:
Package Explorer view—Shows the Java element hierarchy of all the Java
projects in your Workbench. This is a Java-specific view of the resources
shown in the Navigator view (which is not shown by default in the Java
perspective). For each project, its source folders and referenced libraries are
shown in the tree view and from here it is possible to open and browse the
contents of both internal and external JAR files.
The Outline and Problems views are also applicable to the Java perspective and
have already been discussed in earlier sections of this chapter.
The Java Browsing perspective has a larger editor area and several views to
select the programming element you want to edit:
Projects view—Lists all Java projects
Packages view—Shows the Java packages within the selected project
Types view—Shows the types defined within the selected package
Members view—Shows the members of the selected type
The Show Selected Element Only button ( ) toggles between showing all the
content of the selected type and showing only the code (and comments) for the
element selected in the Members view.
The Hierarchy view shows only an information message until you select a type:
To display the type hierarchy, select a type (for example, in the outline view or
in the editor), and select the 'Open Type Hierarchy' menu option. Alternatively,
you can drag and drop an element (for example, project, package, type) onto
this view.
Although the Hierarchy view is also present in the Java perspective and the Java
Type perspective only contains two views, it is useful as it provides a way for
developers to explore and understand complex object hierarchies without the
clutter of other information.
The perspective also includes Package Explorer, Outline, Tasks, and Problems
views, which have already been described earlier in this chapter.
This book does not cover how to develop plug-ins for Rational Application
Developer or Eclipse. To learn more about plug-in development, refer to the
IBM Redbooks publication, Eclipse Development using the Graphical Editing
Framework and the Eclipse Modeling Framework, SG24-6302, or The Java
Developer’s Guide to Eclipse-Second Edition, by D’Anjou et al (refer to
http://jdg2e.com).
In addition to this, there are several editors for viewing the results of profiling, for
example the Memory Statistics view and the Object References view. More
details about these views and the techniques required to use them can be found
in Chapter 25, “Profile applications” on page 1155.
The following link is a reference to the Eclipse project for providing the
functionality of this perspective:
http://eclipse.org/birt/phoenix/project
Resource perspective
The Resource perspective is a very simple perspective (Figure 4-17). By default
it contains only Navigator, Outline, and Tasks views and an editor area. It can
be useful when it is necessary to view the underlying files and folders present for
a project without any extra information added. All the views in this perspective
are available in other perspectives and have been described previously.
Application Developer Help has a section on writing the correlation rules, and for
an introduction to Active Correlation Technology refer to:
http://www.ibm.com/developerworks/autonomic/library/ac-acact/index.html
Figure 4-17 shows a typical layout while working in the Team Synchronizing
perspective.
Also present in the Team Synchronizing perspective is the History view to show
the revision history of a given resource file and the Tasks and Problems view.
More details about these views on this perspective and how to use them can be
found in Chapter 26, “ClearCase integration” on page 1185 and Chapter 27,
“CVS integration” on page 1213.
Test perspective
The Test perspective (Figure 4-19) provides a framework for defining and
executing test cases and test suites. Note that the focus here is on running the
tests and examining the results rather than building the code contained in JUnit
tests. Building JUnit tests involves writing sometimes complex Java code and is
best done in the Java perspective.
More information about Component Testing is located in Chapter 21, “Test using
JUnit” on page 1001.
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 web.xml. Figure 4-20 shows a typical layout while
developing in this perspective.
More information about developing JSPs and other Web application components
in the Web persecutive can be found in Chapter 12, “Develop Web applications
using JSPs and servlets” on page 465.
Progress view
The Progress view is not part of any perspective by default, but is a very useful
tool when using Rational Application Developer. When Rational Application
Developer is carrying out a task that takes a substantial amount of time, a prompt
might appear with two options available (Figure 4-22).
The user can either watch the dialog until the operation completes, or the user
can click Run in Background and the task continues in the background. If the
second option is selected, Rational Application Developer runs more slowly, but
the developer can carry out other tasks while waiting. Examples of tasks that
might be worth running in the background would be publishing and running an
enterprise application, checking a large project into CVS, or rebuilding a complex
set of projects.
If Run in Background is clicked, then the Progress view can be shown again to
review the status of the running task by clicking the icon in the bottom right of
the workspace. Note that this icon only shows if there are processes running in
the background.
Some processes do not prompt the user with a dialog and run in the background
when they are initiated. In these cases, the Progress view can be accessed in the
same way.
For example, when a Web application is published to the test server and the
server has to be started, this process might take some time. By default this
condition shows as a flashing status bar in the bottom left of the workspace and
the icon to show the Progress view appears (Figure 4-23).
Summary
In this chapter, the perspectives available within Application Developer and the
main views associated were described. Parts 2, 3, 4, and 5 of this book
demonstrate in detail the use of these perspectives for various development
scenarios.
Chapter 5. Projects
This chapter provides a high level summary of the types projects within
Application Developer and their main features, in particular, those used for
building J2EE applications. We start with a review of the basic features of the
J2EE framework and then describe the fundamental structures and mechanisms
used by Application Developer for handling projects and the many types of
projects available.
The J2EE specification, along with many other resources relating to J2EE, is
available at http://java.sun.com/j2ee/. This specification includes a
description of the component model for developing J2EE applications and the
runtime architecture. A high level view of a J2EE enterprise application structure
is shown in Figure 5-1.
contains
contains contains 0 or more
0 or more 0 or more
Standard Java Archive
(JAR File)
Includes:
contains -*.class files
Resource Adapter Archive 0 or more
(RAR File)
Includes:
-ra.xml (deployment descriptor)
EJB Resource
-*.class files (JAR File)
- other application resources as applies to Includes:
what is being adpated -ejb-jar.xml (deployment descriptor)
-*.class files (including the EJBs any other Java utility class)
WAR files
Web archive (WAR) files contain all the components of a Web application which
can be deployed to a J2EE compliant application server. These components
often include:
HyperText Markup Language (HTML) files
Cascading style sheets (CSS) files
JavaServer Pages (JSP) files
Compiled Java servlet classes
Other compiled Java classes
Image files
Portlets (portal applications)
WAR files also include a deployment descriptor (web.xml), which describes how
to deploy the various components packaged within the Web module and to map
incoming Web requests to the correct resources.
RAR files
A resource adapter archive (RAR) file is used to package J2EE resource
adapters. These provide access to back-end resources using services provided
by an application server to manage the lookup of the resource and to manage
connections. Resource adapters are often provided by vendors of enterprise
information systems to facilitate access from J2EE applications to resources
such as mainframe systems or non-Java applications.
The resource adapter can be installed as a stand-alone module within the server,
allowing it to be shared among several applications, or as part of an enterprise
application, in which case it is available only to the associated application and
modules contained within it. The RAR file includes the Java classes, providing
the Java-side of the resource adapter, and platform-specific code, providing the
back-end connection functionality. The deployment descriptor is called ra.xml.
Project basics
Within any Rational Application Developer work-space all resources are
organized into projects which contain the files, folders, and properties required
for the application under construction. In a workspace you can create different
kinds of projects with different structures as required for different applications.
The full set of available projects is listed in “Rational Application Developer
projects” on page 156.
Closing projects
It is also possible to close projects on the workspace, which means their contents
are locked and cannot be edited, and other projects cannot reference any of the
resources inside them. This can be done using either the Close Project or Close
Unrelated Projects from the Project Explorer context menu. Closed projects
remain in the Project Explorer view, but they cannot be expanded.
Each wizard will create an empty project of the specified type with the structures,
files, folders, supporting libraries, and references to support such a project. Once
created, it is still possible to change aspects of the project through the project
properties.
The packaging rules, described above in “J2EE architecture” on page 152, are
only applied by Rational Application Developer when a J2EE application or
module is exported.
While these applications and modules are being worked on within Rational
Application Developer, they are stored as projects within the workspace. The
relationship between the enterprise application projects, and the modules they
contain, is managed by Rational Application Developer and applied on export to
produce a properly packaged .ear file.
Java Project
Project
Connector Project Reference Standard Java Archive
(JAR File)
Resource Adapter Archive
(RAR File)
EJB Project
EJB Resource
(JAR File)
When building a dynamic Web project, the user is prompted for which facets are
to be used by the new project, and then the wizard automatically adds the
supporting libraries and configuration files to the new project. By selecting the
appropriate facets, it is possible to create a project which uses Struts or
JavaServer Faces as a framework for building a Web application.
For more information on developing Web applications, see Chapter 12, “Develop
Web applications using JSPs and servlets” on page 465.
For more information on developing Web applications, see Chapter 12, “Develop
Web applications using JSPs and servlets” on page 465.
EJB project
EJB projects contain the resources for EJB applications. This includes the
classes and interfaces that make up the EJBs, the deployment descriptor for the
EJB module, IBM extensions, and bindings files, and files describing the
mapping between entity beans in the project and relational database resources.
For more information on developing EJBs, see Chapter 16, “Develop Web
applications using EJBs” on page 719.
Connector project
A connector project contains the resources required for a J2EE resource adapter.
The wizard allows a set of facets (including the J2EE Connector Architecture
(JCA) version) and containing EAR file to be specified.
Java project
A Java project contains Java packages and Java code as .java files and .class
files. They have an associated Java builder that incrementally compiles Java
source files as they are changed and can be exported as JAR files or into a
directory structure.
Java projects are used for stand-alone applications or to build utility JAR files for
an enterprise application.
For more information on building Java projects, see Chapter 7, “Develop Java
applications” on page 227.
The final page (Figure 5-5) gives the user the opportunity to select any
projects that are part of the enterprise application. This dialog includes select
boxes for all the Java, EJB, Web and Application Client projects in the current
workspace, which, if selected, will be in the project references for the new
project.
If the project you have created is associated with a particular perspective (as in
this case, with the J2EE perspective), Rational Application Developer offers to
switch over to the relevant perspective (Figure 5-8), and from there development
can commence.
In the Properties dialog you can edit most project attributes, and different types of
projects have different options available.
Samples gallery
The samples gallery lists all the samples available in Rational Application
Developer. At the time of writing, this included 26 samples applications within
Application Developer and 46 links to tutorial topics within IBM developer works.
The samples can be selected from a hierarchical list in the left-hand pane
(Figure 5-10).
For example, the Auction Web application is one of the Web application
Showcase samples. The front page for this sample (Figure 5-11) provides an
introduction and links to setting up the sample, getting the sample code, running
the sample, and references for further information.
Click Finish to import the sample projects (in this case eight projects) and build
them. From here the user can run, modify, and experiment with the imported
code as required.
For example, these example projects show model solutions for application
logging and XML processing. Running the wizard adds the example project to
the workspace and also displays an entry from Application Developer help
describing the sample.
Summary
In this chapter we discussed the main types of project within Application
Developer, in particular, those used in the development of J2EE applications.
We also presented the basic features for handling projects within the Application
Developer workspace, and provided an introduction to the samples gallery that is
supplied with Application Developer.
All development activities within Application Developer are based on this project
structure, which comes from the Eclipse framework. In the remaining chapters of
this book we discuss different types of projects in Application Developer and the
specific features available in each project type for building different types of
applications.
Part 2 Develop
applications
In this part of the book, we describe the tooling and technologies provided by
Application Developer to develop applications using Java, databases, XML,
JSPs, servlets, Struts, JavaServer Faces, Service Data Objects, Enterpise
Genration Language (EGL), Enterprise JavaBeans (EJB), Web services, and
Portal Server.
Note: The sample code for all the applications developed in this part is
available for download at:
ftp://www.redbooks.ibm.com/redbooks/SG247501
As shown in Figure 6-1, the Rational Unified Process can be described along two
dimensions that reflect the dynamic and static structure of the process:
The horizontal axis represents the dynamic structure and shows the life cycle
aspects of a process as time goes by. It is described in terms of phases and
iterations.
The vertical axis represents the static structure and content respectively. It
shows the individual disciplines, which logically group the process content.
RUP divides the life cycle of a project in one or more individual cycles that focus
on the generation of successive releases of a system (for example, version 1.0
and version 1.1). Each cycle consists of four successive phases: Inception,
Elaboration, Construction, and Transition. Each of these phases has a special
meaning and concludes with a well defined project milestone. A phase itself is
further broken down in several individual iterations, each of them producing some
kind of working software.
The Rational Unified Process is not only a process framework that can be used
to organize and structure a software development process. Beside a complete
description of the process itself, it provides:
Guidelines for all team members, and all portions of the software life cycle.
Guidance is provided for both the high-level thought process, as well as for
more tedious day to day activities. The guidance is published in HTML form
for easy platform independent access on your desktop.
Tool mentors, which provide additional guidance when working with any of the
software development tools offered by IBM Rational Software, such as
Rational Application Developer for software development and Rational
ClearCase for configuration management.
Templates and examples for all major process artifacts.
Rational Application Developer facilitates the use of the Rational Unified Process
by the Process Advisor feature. This feature provides a seamless integration of a
development process within a development tool. It enabled the development
team to work with a common development process that is configured for a
practitioner’s specific environment. This feature enables the practitioner to obtain
context sensitive guidance, to use process elements such as templates and tool
mentors, to browse and manage process views, and to manage process
preferences without leaving his or her development environment.
If you want to use the Process Advisor feature, either you must select it during
the normal product installation, or you must update the installed package using
the IBM Installation Manager.
The Process Views topic contains several individual process views, each
represented by its own tabbed pane. A process view is the hierarchical set of
process elements represented in and displayed by the process content tree in
the view pane, and associated with a particular role or major category. Process
views are used to group and customize the various elements of the installed
process configuration including templates, guidelines and examples.
If you want to adapt this configuration to your own requirements, you can create
one or more new process views and customize them by using the toolbar buttons
at the top of the window. Select a view you want to start with and select Save
Tree As to create your own copy. This view can then be modified by adding
nodes or selecting the desired information for displaying. The Tutorials Gallery
contains the tutorial Customize a process view that provides a more detailed
description of this task.
Process Advisor
The Process Advisor provides real time dynamic process guidance on selected
UML diagram elements directly from within Rational Application Developer.
Unlike the Process Browser it is a view that runs inside the development tool.
After you select a certain context in the tool, for example, a class in an UML class
diagram, the Process Advisor view is populated automatically with the process
elements that are related to that context (Figure 6-3).
Figure 6-3 Process Advisor displaying method content for a selected context
Another important tool to search the current process configuration for more
information is Process Search (Figure 6-4). It provides search capabilities with
advanced filtering and a tight integration with the Eclipse search. You can access
this tool either by clicking Process Search in the Process Advisor toolbar or
directly from the top menu in Rational Application Developer (select Search →
Search. Then select the Process Search tab).
Process Search allows you to customize the search results. By selecting the
appropriate check boxes you can specify the relevant topics you want to include
in the results.
Process preferences
The Process Advisor feature allows you to select different process configurations
or to set content filtering options for dynamic searches displayed in the Process
Advisor through the Process page of the Preferences window (see Figure 6-5).
The Process preferences page is accessible from within Rational Application
Developer by selecting Window → Preferences.
In addition to this default process configuration, you can use specific process
configurations that you create and publish by using the IBM Rational Method
Composer, and then point to these process configurations with the process
advisor. You can do this in the preferences page shown in Figure 6-5. Therefore
you can simply publish a process configuration in Rational Method Composer
and use the Browse button to point the Process Advisor to the published process
configuration.
Another essential part of the Process Advisor feature is the ability to select filters
to determine what context based content will appear in the Process Advisor view.
On the process preferences page you can select the roles and topics you are
interested in by selecting the appropriate check boxes.
Visual editing offers developers the ability to build code without explicitly typing
the code in a text editor. A palette is used to drag and drop different components
such as Java classes onto a diagram. They can then further be edited visually
such as adding methods and attributes or defining relations between them.
Rational Application Developer offers the following types of UML visual diagrams:
Class diagrams show some or all of the components or elements in an
application. You can use class diagrams to visually represent and develop the
structures and relationships for Java classes and interfaces. You can create
your own context to understand, collaborate, and develop an application by
using a subset of its classes. You can also develop Java elements directly
from class diagrams.
Browse diagrams are temporary diagrams in which you can explore the
details of an application and its underlying elements and relationships. A
browse diagram provides a view of a context element that you specify and is
similar in functionality to a Web browser. You cannot add or modify the
individual diagram elements or save a browse diagram in an application.
However, you can convert a browse diagram to a UML class diagram or save
it in an image file that captures the inheritance hierarchy, which you can send
in an e-mail message or publish on a Web site.
All of these diagrams help developers analyze and document code. To provide
further documentation you can generate Javadoc HTML documentation that
contains UML diagram images to provide more information about the source
code.
The visualization tool is applicable not only for Java classes but also for other
types of artifacts, such as Web services or Enterprise JavaBeans. Rational
Application Developer also supports data visualization using Unified Modeling
Language or Information Engineering notation.
Figure 6-6 provides an overview of a workspace that you might see when using
the UML visualization capabilities:
The center area is the UML editor. This editor is used to display and modify
the different elements of the model.
Built into the editor is a palette that is used to drag and drop artifacts into the
editor work area. The items that appear in the palette are specific to the type
of project that is being visualized. The palette is only available when the
diagram is editable.
The Outline view enables you to see the area of the diagram that you are
zoomed into the editor area. You can switch this view to show the different
elements that build up the current model.
The Properties view enables you to review or change any property that is
related to a selected diagram or a contained element.
Finally, you can drag and drop project artifacts from the Project Explorer or
Package Explorer view directly into the editor to add these items to the
diagram.
Relationships
There are five kinds of relationships in the UML that describe how one element is
related to another:
Dependency is a semantic relationship between two things, where a change
to one class might affect another class. For example, a Bank class depends on
an Account class because it is used as parameter for an operation.
An association is a structural relationship that describes a connection
between objects so that you can navigate between them. Such a relationship
maps to the declaration of class members in a class. For example, a Customer
class might have a single association to an Account class, which indicates
that each Account instance is owned by one Customer instance.
The extends relationship describes the case when one thing is a
specialization or concretion of another more general thing. Such a
relationship maps to the extends keyword in Java. For example, a
SavingsAccount class that extends an Account class provides a more specific
behavior than its parent.
The implements relationship maps to the implements keyword in Java. Such
a relationship represents a class that realizes operations (behavior) that is
defined by an interface.
The owned element association represents classes that are owned by a
package. This construct is primarily used for implementation reasons and for
hiding information
The individual diagrams can be categorized into three groups, each of them
representing a different view of an application.
Structural diagrams show the building blocks of an application,
characteristics that do not change over time. For this purpose they use
objects, attributes, operations, and relationships. Examples are component
diagrams, class diagrams and deployment diagrams.
Dynamic behavior diagrams emphasizes how an application responds to
requests or otherwise evolves over time by showing collaborations among
objects and changes to the internal states of objects. Examples are use case
diagrams and activity diagrams.
Interaction diagrams are a subset of behavior diagrams that focus on the
exchange of messages within a collaboration (that is, a group of cooperating
objects) to accomplish a goal. Examples are sequence diagrams.
The content of a class diagram is stored in a file with a .dnx extension. The
corresponding diagram editor consists of a panel displaying the different
elements and a tool palette that contains individual tools that can be used to
create new UML elements and add them to the current diagram.
Once the wizard is started, enter the name of the file that should contain the
content of this diagram and specify the folder where this file should be stored.
Then click Finish. The new class diagram is created and opened for editing with
an associated palette on the right side (Figure 6-7).
Alternatively, you can create a UML class diagram of existing source elements,
including packages, classes, interfaces, Enterprise JavaBeans, and data types.
In the Project Explorer select the desired source element(s) and then select
Visualize → Add to New Diagram File → Class Diagram from the context
menu.
Of course it is possible to create more than one class diagram within a folder,
each of them depicting different aspects of an application.
To create a new element, select the desired tool in the tool palette and place it on
an empty space inside the class diagram. This launches the appropriate wizard
that guides you to create the selected element, both in the diagram and under
the project. Alternatively, you can create these elements directly and place them
afterwards into the diagram.
Action bar
Modeling assistant
Figure 6-8 Action bar and modeling assistant for Java elements
The upper compartment (name compartment) contains the class name and a
stereotype. A stereotype is a string, surrounded by guillemets or angle quotes
(<<sterotypestring>>), that describes the UML type of the class.
The middle compartment (attribute compartment) contains the attributes.
The lower compartment (operation compartment) contains the operations.
You can show or hide individual compartments so that only the compartments
you are interested in appear in the shape. Right-click on the shape and select
Filters → Show/Hide Compartment, and a submenu offers you the available
options.
When you hover over a Java element that has been visualized on a class
diagram, the action bar and the modeling assistant are displayed:
The action bar is an icon-based context menu that provides a quick access to
commands that allow you to edit the selected element. Using the buttons on
the action bar, you can edit the Java element by adding fields or methods to it.
These actions are also available through the Add Java submenu in the
element's context menu.
You can create incoming relationships in the same way by using the incoming
arrow. Alternatively, you can select the desired relationship in the tool palette and
place it on the individual elements.
The modeling assistant also allows you to view related elements that are based
on a specific relationship. Double-click the small box at the end of the outgoing or
incoming arrow and select the desired relationship from the resulting context
menu (Figure 6-10). This is equivalent to selecting Filter → Show Related
Elements from the element's context menu, then selecting a single relationship
and restricting it to a single level for either incoming or outgoing relationships.
Figure 6-10 Viewing related Java elements using the Modeling Assistant
For a class diagram of the ITSO Bank application, refer to Figure 7-12 on
page 238.
To use these capabilities, a class diagram must be created within the context of
an EJB project. Then you can use the tool palette in the same way as described
in the previous section to create and edit EJBs, to develop the relationships
between them, and to define a mapping to an underlying relational database
table. Alternatively, you can create these elements directly and place them
afterwards on the diagram.
Figure 6-13 shows the graphical representation of an EJB and the corresponding
EJB module (to visualize an EJB module select its deployment descriptor from
the Project Explorer and drop it into the diagram). Because they are more
complex than a Java class, EJBs are mapped to UML components, a subtype of
On the top you can see the Attribute compartment that displays the persistent
attributes of that bean. If you want to show or hide any compartment, select
Filters → Show/Hide compartments from the context menu.
After selecting an EJB the Show Related Elements feature (Filters → Show
Related Elements) searches and displays related elements based on selection
criteria. This feature provides a set of predefined custom queries that can be
quickly used to view the related elements (Figure 6-15).
From the context menu there are several other options available to edit a
selected EJB or to change its appearance. Most of these features have been
described previously so the following focuses on topics that are specific to EJBs.
Some of these features are exposed as wizards that are also available through
the action bar, the tool palette, or the deployment descriptor.
You can use UML class diagrams to manage EJB security visually. This
comprises creating and modifying security roles, security role references, run-as
security identities, method permissions, and excludes lists.
Security roles
Developing security roles for an Enterprise JavaBean comprises the following
tasks: Create security roles, add references to security roles, and link security
role references to security roles:
A security role is created with the help of the Add Security Role wizard. To
launch this wizard, right-click an EJB JAR artifact and select Add EJB →
Security Role. Once the wizard is started, enter the name and description for
the security role and click Finish. As shown in Figure 6-16, the newly created
security role is visualized in the diagram as an actor notation of stereotype
<<Role Name>>, with a dependency of stereotype <<Security Role>> to the
EJB JAR artifact.
The next step is to create references to security roles defined for an EJB JAR.
In the diagram editor, right-click the desired Enterprise JavaBean, and select
Add EJB → Security Role Reference. In the dialog provide a name for the
If not already done in the previous step, you must link a security role to a
security role reference. In the class diagram, right-click on the actor
representing the security role reference, and select Link to Security Role. In
the following dialog you can add or change the desired role.
Method permissions
Another aspect of security management that can be visually created and
manipulated are method permissions. Once the security roles for an EJB are
defined, you can specify the methods of the home and component interface that
each security role is allowed to invoke:
You can add method permissions with the help of the Add Method Permission
wizard. Right-click a session or entity bean and select Add EJB → Method
Permission. In the first step, you must specify the permission for the
methods. You have the option to select from an existing security role or to
allow the methods to be invoked without being checked for authorization
(Figure 6-19).
In the next step, select the methods from the home and component interfaces
that each selected security role is allowed to invoke. Then click Finish
(Figure 6-20).
Figure 6-21 shows the new method permission being linked to the EJB
through a dependency of stereotype <<Method>>. If you want to edit a method
permission, right-click the desired method permission and select Edit → Edit,
then follow the instructions in the Add Method Permission wizard.
Exclude lists
Finally, you can specify methods that you want to mark as not callable. In the
diagram editor, right-click an EJB session or entity bean and select Add EJB →
Exclude List. In the dialog select the methods to be excluded, and click Finish
(Figure 6-22). To edit an exclude list, right-click and select Edit → Edit and follow
the instructions in the Exclude List wizard.
For examples of EJB class diagrams refer to Chapter 16, “Develop Web
applications using EJBs” on page 719.
To use this feature, the Web Service Modeling capability must be enabled
beforehand. In the preferences dialog (Window → Preferences) expand
General → Capabilities. In the Capabilities page select Modeling and click
Advanced. In the dialog expand Web Service Developer and select Web
Service Development.
The result of this task is shown in Figure 6-25. Like an EJB, a WSDL service is
mapped to an UML component with stereotype <<WSDL Service>>. The port is
depicted as a small square on the right side of the component. Note that the
external view of the component is shown. To switch to the compressed view,
open the context menu and clear Show External View from the Filter submenu.
To add a port to a WSDL service, right-click the service and select Add WSDL →
Port. This launches the Port wizard shown in Figure 6-26. Enter the name of the
port. Optionally you can specify a binding and a protocol. Then click Finish.
After you have created a port, you can use the Properties view to review or
change any property. Right-click the square representing the desired port and
select Show Properties View. Then select General on the left side of the
Properties view. On this page, you can enter a new name and address and you
can select a binding and protocol (Figure 6-27).
You can create a new port type together with an operation with the help of the
New WSDL Port Type wizard (Figure 6-28). You can launch this wizard either by
placing the WSDL Port Type tool from the tool palette in the diagram or by
right-clicking in the diagram and selecting Add WSDL → Port Type.
The result is shown in Figure 6-29. A port type is visualized in the diagram using
the interface notation with a stereotype <<WSDL Port Type>>. You can add further
operations by selecting Add WSDL → Operation from the context menu.
Note that you did not create a connection between this port type and the port so
far. You will do this in the last task.
First, you must specify the WSDL file that should contain the message. Like
WSDL services or port types, messages are top-level objects that can be defined
in a separate WSDL file. As described previously you can either browse to select
an existing file or create a new one. Finally, enter the message name and part
name and click Finish.
The result is shown in Figure 6-31. The newly created message is displayed
using a UML class notation with stereotype <<WSDL Message>>. If you want to add
any further part to this massage, right-click the shape and select Add WSDL →
Add Part.
You can add new elements to a complex type. In the diagram editor, right-click
the complex type and select Add XSD → Add New Element. This creates a new
element within the selected complex type with type string. You can further set or
change the type of an existing XSD element. In the diagram editor, right-click an
XSD element or an element within a complex type and select Add XSD → Set
XSD Type. The dialog that opens provides a list of available types that you can
select.
Note that once you have created an XSD element, you just can delete it from the
diagram. If you want to delete it permanently from the underlying WSDL file, you
must edit the file directly.
To review or change the type associated with a part, select the corresponding
diagram element to bring up its properties in the Properties view. Then select the
General tab. As shown in Figure 6-32, you can select the desired type in the
drop-down combo box.
To proceed with the scenario, create two complex types, Account and Customer,
and add the attributes amount, name, and firstName (Figure 6-33).
To add a message to an operation, you can use one of the following tools offered
by the tool palette: WSDL Input Message, WSDL Output Message, or WSDL
Fault Message. Select the desired tool, click the port type, and drag the cursor to
a message you want to add. In the dialog select the desired operation and click
Finish (Figure 6-35). Alternatively, you can use the modeling assistant to do this.
To proceed with the example scenario, create a WSDL input message from the
createAccount operation to the CreateAccount message. Then create a WSDL
output message from the same operation to the CreateAccountResponse
message. (Figure 6-36).
Figure 6-37 Class diagram showing a binding between a port and its port type
The last step is to generate the content for this binding. Select the dependency
representing the binding and open the Properties view. On the General page
click Generate Binding Content and complete the wizard (Figure 6-38).
After you have created the entire Web service, you can directly create an
implementation of this Web Service within the diagram editor. Right-click a
WSDL service component and select Implement Web Service. This will start
the Web Service wizard that guides you through the process. You can also use
the diagram editor to create a Web Service client for a given Web Service.
Right-click a WSDL service component and select Consume Web Service.
Before you create a new UML class diagram, you can set the default global
preferences for attributes and operations, such as visibility styles, showing or
hiding attributes and operations, showing or hiding operation signatures, and
showing or hiding parent names of classifiers.
UML diagram settings—Using the Diagrams page and the pages beneath
users can specify several preferences regarding to the style, fonts and colors
that are displayed in UML diagrams when they are created. Users can change
the default settings for showing or hiding attributes, operations, operation
signatures, or parent names of classifiers. They can also specify which
compartments are shown by default when a new UML element is created.
Java development settings—This category allows users to specify if the
corresponding wizards should be used when new fields or methods are
created within a class diagram. They can further specify the default values
that should be applied to these wizards. The Show Related Elements Filters
page provides the option to filter out binary Java types when the Show
Related Elements action is executed. Binary Java types are types that are not
defined in the workspace, but instead are available to the workspace through
referenced libraries (jars).
Browse diagrams
A browse diagram is a structural diagram which provides a view of a context
element such as a class, a package, or an EJB. It is a temporary and non
editable diagram that provides the capability to explore the given context
element. You can view the element details, including attributes, methods, and
relationships to other elements, and you are able to navigate to these elements.
Browse diagrams can be applied to various elements including Java and
Enterprise JavaBeans artifacts, but excluded are all artifacts related to Web
services.
You can create a browse diagram from any source element or its representation
within a class diagram. Right-click the desired element and select Visualize →
Explore in Browse Diagram. A browse diagram is created and shown in the
corresponding diagram editor. The diagram editor consists of a panel displaying
the selected element along with its relationships and a tool bar. Because a
browse diagram is not editable, the tool palette and the modeling assistant are
not available. Depending on the elements shown, the diagram is displayed either
using the radial or generalization tree layout type. The radial layout type shows
the selected element in the center of the diagram, whereas the generalization
tree layout type organizes the general classes at the top of the diagram and the
subclasses at the bottom.
Figure 6-39 shows a sample browse diagram with the Java class Account as
context element. You can see all attributes and methods declared by this class,
and because all filter buttons are highlighted all the related elements are shown
as well. You can see that Account is directly referenced by Customer and that it
has two subclasses. Further, the diagram shows that somewhere in the
implementation code the class Account is used by the Bank class.
The browse diagram retains the history of elements you have viewed so far. You
can use the two arrow buttons provided in the tool bar to navigate backward or
forward to browse previously viewed elements.
In Figure 6-39 the Home icon and the two arrow icons are disabled, so the
current element is the first element in the browse diagram history.
If you want to explore the details of a diagram element, double-click it. This
element becomes the new context element. When you right-click a diagram
element, the Navigate submenu provides several options to navigate to the Java
source of a diagram element.
Topic diagrams
Topic diagrams provide another way to create structural diagrams from the code
in your application. They are used to quickly create a query based view of
relationships between existing elements in your application. These queries are
called topics and represent commonly needed views of your code, such as
showing the super type or sub types of a given class. Topic diagrams are
applicable to various elements, such as Java and EJB artifacts, or WSDL files.
Like browse diagrams these diagrams are not editable, but they can be saved as
editable UML diagrams and shared with other team members.
The Topics page (Figure 6-41) provides a list of standard topics Rational
Application Developer can create. Select a predefined query and click Finish.
This creates a new topic diagram based on default values associated with the
selected topic.
If you want to review or change these values click Next instead. The Related
Elements page shown in Figure 6-42 appears.
This page shows the details of the previous selected topic and allows you to
change these values. You can select different types of relationship that should be
included in the query along with the expansion direction:
If you select Incoming, all elements are shown that are related to the context
element.
On the other side, if you want to see all elements that have a relationship to
the context element, select Outgoing.
You can further specify the number of levels of relationships to query and the
layout type for the diagram. The possible values are Default and Radial.
These values map to the generalization and radial tree layout type described
previously.
Once a topic diagram is created, you are able to review or change the underlying
query. Right-click an empty space inside the diagram and select Customize
Query.
Like browse diagrams, topic diagrams are not editable, so the tool palette and the
modeling assistant are not available. You can add more elements to the diagram
by right-clicking and selecting Visualize → Add to Current Diagram.
You are also able to save a topic diagram as editable diagram or as an image.
Right-click an empty space and select either File → Save as Diagram or File →
Save as Image.
The main focus of Rational Application Developer is to model and visualize the
dynamic behavior of a system rather than developing code. The tool enables
developers to create, edit, and delete the various elements of a sequence
diagram such as lifelines, messages and combined fragments in a visual manner.
In contrast to a class diagram, the elements of a sequence diagram are not
related to existing elements, such as classes or interfaces. So changes made in
a sequence diagram do not affect any code.
You can also create a new sequence diagram of an existing class or interface. In
the Project Explorer select the desired source element and select Visualize →
Add to New Diagram File → Sequence Diagram. Once the wizard is started,
provide a name for the file that will be created to contain the content of the
diagram, and specify the parent folder where this file should be stored. Then click
Finish.
Creating lifelines
A lifeline represents the existence of an object involved in an interaction over a
period of time. A lifeline is depicted as a rectangle containing the object's name,
type and stereotype. A vertical dashed line beneath the object icon indicates the
progress of time. Figure 6-44 shows several examples of possible lifelines:
The first lifeline represents an instance of the Customer Java class named
customer.
The second lifeline represents an anonymous instance of the Customer Java
class
The last lifeline represents an object named customer whose type is not
specified.
To add a lifeline from an existing Java element to a sequence diagram, select the
desired element in the Project Explorer view and drag it on an empty place in the
diagram. This creates a new lifeline and places it on top the diagram aligned
vertically with the other lifelines.
You can also use the tool palette to create a new lifeline. Select the Lifeline
element and drop it on an empty space inside the diagram. Note, that this
creates a lifeline representing an object whose type is not specified. Once a
lifeline is created, you can change the name and type of the object it represents.
If you want to change the name, select the lifeline's shape and enter the new
name. If you want to change the type, select the desired element in the Project
Explorer view and drag it on the lifeline's shape. You can also use the Properties
view to review or change any property of a given lifeline.
Per default, a lifeline is shown as a rectangle containing the lifeline's name, type,
and stereotype. If you right-click a lifeline, the Filters submenu provides several
options to change the lifeline's appearance.
Creating messages
A message describes the kind of communication that occurs between two
lifelines. A message is sent from a source to a target lifeline to initiate some kind
of action or behavior such as invoking an operation, creating, or destroying a
lifeline. The target lifeline can respond with a further message to indicate that it
has finished processing.
Per default, only the operation's name is shown. If you want to see the full
operation signature, right-click the arrow representing the message and
select Filters → Show Signature.
An Asynchronous Message allows the source lifeline to invoke an operation
provided by the target lifeline. It continuous with the next step immediately
without waiting for the target lifeline to finish processing the message. An
Asynchronous Message is drawn similar as a synchronous message, but the
line is drawn with an open arrowhead, and the response is omitted. You can
further use the Asynchronous Message to model a signal, a special form of a
message that is not associated with a particular operation.
guard condition
To create a combined fragment, you must first select the desired tool in the tool
palette. Click the solid triangle right next to the Combined Fragment category
and select the desired tool from the available options. Then place the cursor
within an empty place in the diagram and drag the combined fragment across the
lifelines that you want to include in it. When you drop the cursor, the Add Covered
Lifelines dialog opens that allows you to select the individual lifelines to be
covered by the combined fragment. Each lifeline is represented by a check box,
and each of them is selected by default. When you click OK a new combined
fragment along with one or two interaction operands is created.
Figure 6-49 shows a newly created alternative combined fragment with two
empty interaction operands (the lifelines are omitted in this diagram). If you want
to specify a guard condition for an interaction operand, select the corresponding
brackets and enter the text. You can create messages between the individual
lifelines covered by the combined fragment in the same way as described
previously. Note how the sequence numbers of the individual messages change
within an interaction operand. You can also nest other combined fragments within
an existing combined fragment.
Note: Note, that at the time of writing it was not possible to truly reference
another diagram. Instead it was only possible to provide a simple name.
When you right-click an empty space inside the diagram, the File submenu
provides you the options to either save this diagram as an image (Save as Image
File), to convert this diagram to an editable UML sequence diagram (Save as
Diagram File) or to print the entire diagram (Print).
A static sequence diagram for a Java method has to be created only once. Like
other topic diagrams, the query and context that have been specified when
creating the diagram are stored in the diagram itself. So each time a sequence
diagram is opened, Rational Application Developer queries the underlying
elements and populates the diagram with the latest updates. If you want to
refresh the contents of a static sequence diagram to reflect the latest changes in
the source code, right-click an empty space inside the diagram and select
Refresh.
For example, you can specify if return messages should be created automatically
or a message numbering is shown.
Those perspectives and their main views were briefly introduced in Chapter 4,
“Perspectives, views, and editors” on page 117. In this section we go deeper into
the details and describe some more useful views. The highlighted areas in
Figure 7-1 indicate all perspectives and views we discuss.
Java perspective
We use the Java perspective to develop Java SE applications or utility Java
projects (utility JAR files) containing code that is shared across multiple modules
within an enterprise application.
To view the hierarchy of a class type, select the class in the Package Explorer,
and press F4 or right-click the class and select Open Type Hierarchy. The
hierarchy of the selected class is displayed, as shown in Figure 7-3.
Outline view
The Outline view is very useful and is the recommended way to navigate through
a type that is currently opened in the Java editor. It lists all elements including
package, import declarations, type, fields, and methods. The developer can sort
and filter the elements that are displayed by using the icons highlighted in
Figure 7-4.
Problems view
While editing resource files, various builders can automatically log problems,
errors, or warnings in the Problems view. For example, when you save a Java
source file that contains syntax errors, those will be logged as errors, as shown in
Figure 7-5. When you double-click the icon for a problem , error , or
warning , the editor for the associated resource automatically opens to the
relevant line of code.
Application Developer provides a quick fix for some problems. How to process a
quick fix is described in “Quick fix” on page 310.
Note: Java builder is responsible for all Java resource files. However, in an
enterprise application project, other builders can be used. Builders can be
enabled and disabled for each project. Right-click the project in the Package
Explorer and select first Properties and then Builders.
Declaration view
This view displays the declaration and definition of the currently selected type or
element, as shown in Figure 7-7. It is most useful to see the source code of a
referenced type within your code. For example, if you reference a customer within
your code and you want to see the implementation of the Customer class, just
select the referenced type Customer, and the source code of the Customer class is
displayed in this view. Clicking directly opens the source file of the selected
type in the Java editor.
The highlighted link in Figure 7-8 directs you to the line in the source code where
the exception has been thrown.
Packaging structure
The ITSO Bank application contains several packages. Table 7-1 lists the
packages and describes theirs purposes.
Class diagram
A UML class diagram helps to overview the interfaces and classes and their
relationships. In the class diagram in Figure 7-12, we added the packages as
well to get a complete picture of the ITSO Bank application.
We will create this diagram by using Application Developer’s UML modeling tool
in “Creating a UML class diagram” on page 242.
Note: Projects are not defined in the Java SE specification. They are used in
Application Developer as the lowest unit to organize the workspace.
Application Developer must be started at that time, and we recommend that you
work with the Java perspective. The way to change a perspective is described in
“Switching perspectives” on page 121.
Note: By default, the project files are stored in a folder created under
Application Developer workspace directory. Select Create project from
existing source to change the directory of the project.
In the Package Explorer view, you cannot see the generated .class
files. If you want to see the folder structure and the files as they are in
the file system, you have to open the Navigator view. Select Window →
Show View → Navigator. Now you can see the sources in the src
directory and the bytecode files in the bin directory.
Note: By default, Use project folder as root for source and class
files is selected. If you select Create separate source and output
folders, you can optionally change the directories to something other
than src and bin by clicking Configure default.
– Click Next.
In the New Java Project - Java Settings dialog (Figure 7-14, right) we accept
the default settings for each of the tabs by just clicking Finish.
This dialog allows you to change the build path settings for a Java project. The
build class path is a list of paths visible to the compiler when building the
project.
– Source tab—This tab allows you to add and remove source folders from
the Java project. The compiler translates all .java files found in the source
folders to .class files and stores them to the output folder. The output
folder is defined per project except if a source folder specifies an own
output folder. Each source folder can define an exclusion filter to specify
which resources inside the folder are not visible to the compiler.
– Projects tab—This tab allows you to add another project within the
workspace to the build path for this new project (project dependencies).
– Libraries tab—This tab allows you to add libraries to the build path. There
are five options:
• Workspace-managed (internal) JAR files:
Add JARs—Allows you to navigate the workspace hierarchy and
select JAR files to add to the build path.
Figure 7-15 Visualizer Class Diagram editor with Java Drawer in the Palette
The interfaces and classes are described in “Interfaces and classes overview” on
page 236.
– Interfaces: java.io.Serializable
To add an interface, click Add and type the interface name in the Choose
interfaces field. All matching types are listed. Select the required interface
and click Add. If you have added all required interfaces, click OK to leave
the dialog (Figure 7-20).
Note: Add all required Java classes according to Table 7-2 on page 246.
Method and field declarations are added later. Alternatively you can wait and
import the finished classes later.
Table 7-3 lists the fields of the interfaces, and Table 7-4 lists the attributes and
getter and setter methods of the classes which must be created.
Table 7-4 Attributes and getter and setter methods of the classes
Class Attribute Type Initial value Visibility, Methods
name Modifiers
lastName
accounts *) ArrayList<Account>
amount BigDecimal
transactionId int 0
account Account
*
These attributes are in fact the implementations of UML class associations.
So you can also create them by following the steps described in “Creating
relationships between Java types” on page 264.
In the Create Java Field dialog, enter the following data (Figure 7-21).
– Name: timeStamp
– Type: java.sql.Timestamp
Note: To change the type, click , to change the type to any primitive
type or to any reference type of the java.lang.* package, or click
Browse and type the interface or class name in the Pick a class or
interface field. All matching types are listed and you select the required
class and click OK to leave the dialog.
All required import statements are also added to the source code.
Note: If the required attribute has a multiplicity higher than 1, select this
field. If selected, the wizard allows you to select the required Java
collection class. If you select any kind of Map class, you can select the
type of the key in the Java collection key type field. Finally, you can
create parameterized types by selecting the use generic collection
checkbox. More information about generic types can be found here:
http://java.sun.com/developer/technicalArticles/J2SE/generics/
Note: There are two reasons why you might not see the attributes in the
class diagram:
Class diagram attribute compartment is collapsed—Select the interface
or class and click the little blue arrow in the compartment in the middle.
That expands the attribute compartment.
Class diagram attribute compartment is filtered out—Right-click the
interface or class and select Filters → Show/Hide Compartment →
Attribute Compartment.
To generate getter and setter methods for a Java attribute using the refactor
feature, do these steps:
Right-click the attribute in the diagram editor or in the Outline view and select
Refactor → Encapsulate Field.
In the Encapsulate Field dialog, enter the following data (Figure 7-22):
– Getter name: getTimeStamp (default)
– Setter name: setTimeStamp (default)
– Insert new methods after: As first method (default)
– Access modifier: select public
You can later change the access modifier of the setter method to private
in the source code.
– Field access in declaring type: use getter and setter (default)
It is good programming style when you use the getter and setter method
also internally in the class to access member variables.
– Generate method comments: clear (default)
Note: If the source code is open in the Java editor, you can just right-click
somewhere in the Java editor and select Source → Generate Getters and
Setters, or you can select Source → Generate Getters and Setters in the
menu bar.
Note: It does not matter in which way you are creating the getter and setter
methods. As soon as you save the changes, they are visible in the class
diagram as well as in the source code.
getCustomers Map<String,
Customer>
There are two ways to add a method declaration to an interface. You can write
the method declaration directly into the interface body in the Java editor, or you
can add it in the Visualizer Class Diagram editor. The Visualizer Class Diagram
editor calls the Create Java Method wizard to complete the work.
Note: The Create Java Method wizard only gets called through the Visualizer
Class Diagram editor. It is not possible to call it by yourself (for example, by
clicking an icon in the toolbar).
– Name: searchCustomerBySsn
– Visibility: public (default)
– Modifiers: clear all (default)
Note: To add an exception, click Add and type the exception class
name in the Pick one or more exception types to throw field. All
matching types are listed in the Matching types field. Select the
required exceptions and click OK.
Note: To add a parameter, click Add. Enter the name, select the type
and dimensions in the Create Parameter dialog, and click OK to add the
parameter. In the example, we do not pass any array parameters, and
dimensions are always 0 (default).
Note: There are two reasons why you might not see the methods in the
class diagram:
Class diagram method compartment is collapsed—Select the interface
or class and click the little blue arrow in the compartment in the bottom.
That expands the method compartment.
Class diagram method compartment is filtered out—Right-click the
interface or class and select Filters → Show/Hide Compartment →
Method Compartment.
Table 7-6 Constructors and methods of the classes of the ITSO Bank application
Method name Modi- Type Parameters Exceptions
fiers
ITSOBank
ITSOBank private -
construc
tor
Account
Account public - String accountNumber,
construc BigDecimal balance
tor
toString String
Customer
Customer public - String ssn,
construc String title,
tor String firstName,
String lastName
toString String
Transaction
Transaction public - BigDecimal amount
construc
tor
Credit
Credit public - BigDecimal amount
construc
tor
toString String
Debit
Debit public - BigDecimal amount
construc
tor
toString String
BankClient
main public void String[] args
static
The Java editor of the Application Developer provides a set of useful features to
develop the code. These features are explained in “Additional features used for
Java applications” on page 282 and “Java editor and rapid application
development” on page 300.
You can add all the classes to the diagram manually, or import the diagram
into the diagram folder from:
C:\7501code\java\diagram\ITSOBank-Diagram.dnx
To change the appearance of the diagram, right-click in the diagram and
select Filters → Show/Hide Connector Labels → All or No connector
Labels, or Filters → Show/Hide Relationships and select the relationships
to be displayed or hidden. For example, you can hide the many <<use>>
relationships.
There are already extends relationships in the class diagram: The Transaction
class is specified as the superclass of the Credit and Debit classes. Extends
relationships are displayed using a solid line with a triangular arrow pointing to
the superclass.
Implements relationship
To create an implements relationship between an existing class and an interface
select in the Java Drawer and drag the mouse with the left mouse
button down from any point in the implementation class to the interface.
Association relationship
The classes in the ITSO Bank application have the following relationships:
ITSOBank remembers the customers and accounts.
A customer knows his or her accounts.
An account logs all the transactions for logging and querying purposes.
Note: The following step-by-step guide explains how to create the association
between Customer class and the Account class. The associations are listed in
Table 7-4 on page 250.
Note: We do not show the generated getter and setter methods because they
are trivial.
Customer class
Example 7-1 shows the Java source code of the Customer class.
import itso.rad7.bank.exception.AccountAlreadyExistException;
import itso.rad7.bank.exception.InvalidAccountException;
import java.io.Serializable;
import java.util.ArrayList;
Account class
Example 7-2 shows the Java source code of the Account class.
import itso.rad7.bank.exception.InvalidTransactionException;
import itso.rad7.bank.ifc.TransactionType;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
if (TransactionType.CREDIT.equals(transactionType)) {
transaction = new Credit(amount);
} else if (TransactionType.DEBIT.equals(transactionType)) {
transaction = new Debit(amount);
} else {
throw new InvalidTransactionException(
"Invalid transaction type: Please use Debit or Credit. "
+ "No other transactions are currently supported.");
}
newBalance = transaction.process(this.getBalance());
if (newBalance.doubleValue() < 0) {
throw new InvalidTransactionException(this, transactionType, amount);
} else {
this.setBalance(newBalance);
this.getTransactions().add(transaction);
}
}
import itso.rad7.bank.exception.InvalidTransactionException;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Timestamp;
Credit class
Example 7-4 shows the Java source code of the Credit class.
import itso.rad7.bank.exception.InvalidTransactionException;
import itso.rad7.bank.ifc.TransactionType;
import java.math.BigDecimal;
ITSOBank class
Example 7-5 shows the Java source code of the ITSOBank class.
import itso.rad7.bank.exception.AccountAlreadyExistException;
import itso.rad7.bank.exception.CustomerAlreadyExistException;
import itso.rad7.bank.exception.ITSOBankException;
import itso.rad7.bank.exception.InvalidAccountException;
import itso.rad7.bank.exception.InvalidCustomerException;
import itso.rad7.bank.exception.InvalidTransactionException;
import itso.rad7.bank.ifc.Bank;
import itso.rad7.bank.ifc.TransactionType;
import itso.rad7.bank.model.Account;
import itso.rad7.bank.model.Customer;
import itso.rad7.bank.model.Transaction;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
private ITSOBank() {
this.setCustomers(new HashMap<String, Customer>());
this.setAccounts(new HashMap<String, Account>());
this.setCustomerAccounts(new HashMap<String, ArrayList<Account>>());
this.initializeBank();
}
if (this.getCustomers().get(customerSsn) != null) {
if (this.getAccounts().get(accountNumber) == null) {
this.getAccounts().put(account.getAccountNumber(), account);
this.getCustomerAccounts().get(customerSsn).add(account);
customer.addAccount(account);
} else {
throw new AccountAlreadyExistException(accountNumber);
}
} else {
throw new InvalidCustomerException(customerSsn);
}
}
if (this.getCustomers().get(customerSsn) != null) {
if (this.getAccounts().get(accountNumber) != null) {
this.getAccounts().remove(accountNumber);
this.getCustomerAccounts().get(customerSsn).remove(
accountNumber);
customer.removeAccount(account);
} else {
throw new InvalidAccountException(accountNumber);
}
} else {
throw new InvalidCustomerException(customerSsn);
}
}
ITSOBankException class
Example 7-6 shows the Java source code of the ITSOBankException class.
InvalidTransactionException class
Example 7-7 shows the Java source code of the InvalidTransactionException
class.
import itso.rad7.bank.model.Account;
import java.math.BigDecimal;
AccountAlreadyExistException class
Example 7-8 shows the Java source code of the AccountAlreadyExistException
class. The other exceptions have similar code and are not listed.
BankClient class
Example 7-9 shows the Java source code of the BankClient class.
import itso.rad7.bank.exception.ITSOBankException;
You can see the output in the Console view, similar to Figure 7-28.
Figure 7-28 Console view with output of the ITSO Bank application
Type a name for the analysis configuration in the Name field and set the
scope of your analysis:
– Analyze entire workspace: The rules that you select on the Rules tab are
applied to all the resources in your workspace.
– Analyze a resource working set: The rules that you select on the Rules tab
are applied to a specific set of projects, folders, or files in your workspace.
– Analyze selected projects: The rules that you select on the Rules tab are
applied to the resources in the project you select.
Select the Rules tab to specify the rule categories, rules, or rule sets to apply
during the analysis:
– Analysis Domains and Rules: Expand the tree and select providers, rule
categories, and rules. For example, select Code review for Java.
– Rule Sets: Select a defined rule set and click Set to configure the
providers, rule categories, and rules. For example, select Java Quick
Code Review.
Note that setting a rule set selects a subset of domains and rules.
Click Apply.
While the analysis runs, the Analysis Results view opens and, if your source
code does not conform to the rules in the analysis configuration, the view
populates with results. The results are listed in chronological order and are
grouped into the same categories that you specified in the analysis configuration.
If you run the analysis for the RAD7Java project, no problems are reported. If
running the analysis for the RAD7GUI project developed in Chapter 10, “Develop
GUI applications” on page 403, then many problems are reported (Figure 7-30).
A result is not necessarily a problem, mistake, or bug, but you have to evaluate
each result in the list to determine what action, if any, you have to take. If the
result is a problem that has a trivial solution, the author of the rule might have
provided a quick fix that automatically corrects the resource. How to process a
quick fix is described in “Quick fix” on page 310.
To locate a problem, right-click an entry in the Analysis Results view and select
View Result. This action opens the Java source file with the problem code
highlighted.
Note: You do not have to specify a project, but doing so allows a default
classpath, source lookup path, and JRE to be chosen.
The Arguments tab defines the arguments to be passed to the application and
to the virtual machine. To add a program argument, do these steps:
– Click Variables below the Program arguments field.
– Select one of the predefined variables or create your own variable by
clicking Edit Variables and then New.
• Enter the name and the value for the variable and click OK to add it.
• Click OK again to return to the Select a variable dialog. The new
variable is now available in the list. Select it and click OK to return to
the Arguments tab.
– In the same way, you can also add VM arguments.
– You can also specify the working directory to be used by the launched
application.
The JRE tab defines the JRE used to run or debug the application. You can
select a JRE from the already defined JREs, or define a new JRE.
The Classpath tab defines the location of class files used when running or
debugging an application. By default, the user and bootstrap class locations
are derived from the associated project's build path. You can override these
settings here.
The Source tab defines the location of source files used to display source
when debugging a Java application. By default, these settings are derived
from the associated project's build path. You can override these settings here.
The Environment tab defines the environment variable values to use when
running or debugging a Java application. By default, the environment is
inherited from the Eclipse runtime. You can override or append to the
inherited environment.
A scrapbook page can be added to any project and package. The extension of a
scrapbook page is .jpage, to distinguish it from normal Java source file.
bank.searchCustomerBySsn("xxx-xx-xxxx");
Important: All classes that are not from the java.lang package must be
fully qualified, or you have to set import statements:
Right-click anywhere in the scrapbook page editor and select Set
Imports.
For the example, add the following types and packages:
itso.rad7.bank.model.*
itso.rad7.bank.ifc
itso.rad7.bank.impl.ITSOBank
java.math.BigDecimal
To export the ITSO Bank application code to a JAR file, do these steps:
Right-click the RAD7Java project and select Export.
In the Export dialog, select Java → JAR file and click Next.
In the JAR Export dialog, enter the following data (Figure 7-33):
Note: Ensure that the JRE is set in the Windows environment variable called
PATH. You can add the JRE to the path with the following command in the
Windows Command Prompt:
set path=%path%;{JREInstallDirectory}\bin
set path=%path%;C:\Program Files\IBM\SDP70\jdk\jre\bin
To test the imported Java project, select and run the BankClient class from the
Package Explorer.
Javadoc tooling
Javadoc is a very useful tool in the Java Development Kit used to document Java
code. It generates a Web-based (html files) documentation of the packages,
interfaces, classes, methods and fields.
Generating Javadoc
This section explains how to generate Javadoc from an existing Java project.
Application Developer supports the following types of Javadoc generation:
Generate Javadoc
Generate Javadoc with diagrams from existing tags
Generate Javadoc with diagrams automatically
Generate Javadoc from an Ant script
Generate Javadoc
To generate Javadoc from an existing Java project, do these steps:
Right-click the RAD7JavaImport project in the Package Explorer and select
Export → Java → Javadoc, or select Project → Generate Javadoc.
In the Javadoc Generation dialog, enter the following data (Figure 7-36):
– The Javadoc command is predefined.
– Select Public for Create Javadoc for members with visibility (default).
– Select Use Standard Doclet. Alternatively, you can specify a custom
doclet with the name of the doclet and the classpath to the doclet
implementation.
– Destination: {workspaceDirectory}\RAD7Java\doc (default)
Generates Javadoc in the doc directory of current project
In the Configure Javadoc arguments for standard doclets dialog accept the
default settings and click Next.
In the Configure Javadoc arguments dialog, enter the following data:
– Select 1.5 for JRE source compatibility because we use generic types in
the project, which are only supported from JDK version 1.5 (5.0) or higher.
– Select Save the settings for this Javadoc export as an Ant script and
accept the destination:
{workspaceDirectory}\RAD7JavaImport\javadoc.xml
Click Finish to generate the Javadoc.
When prompted to update the Javadoc location, click Yes to all.
When prompted that the Ant file will be created, click OK.
Open the Javadoc in a browser and explore the generated Javadoc for the
RAD7JavaImport project (Figure 7-37).
– Expand RAD7JavaImport → doc in the Package Explorer.
– Double-click index.html to display the Javadoc contents for the project.
Note that the ITSOBank-Diagram.dnx file must be in the same package as the
class. Copy the diagram from the diagram folder to the itso.rad7.bank.client
package.
You have to place your diagrams along with the Java source code. For Web
applications, this has the side effect of the class diagrams being packaged
into the WAR file with the compiled Java code.
This remaining error can be resolved with an additional input in the Extra
Javadoc options field of the Javadoc Generation - Configure Javadoc
arguments dialog:
-tagletpath "C:\IBM\SDP70Shared\plugins\
com.ibm.xtools.viz.j2se.ui.javadoc_7.0.100.v20061213_1732.jar"
The path above is the default installation path. You might have to verify
what the actual location is as well as the version number of the above
plug-in on your installation.
In the Choose diagram image generation options dialog, accept the default
settings and click Finish.
When prompted to update the Javadoc location, click Yes to all.
Open the Javadoc in a browser and verify that a diagram has been added to
the generated Javadoc for the BankClient class.
– Expand RAD7JavaImport → doc in the Package Explorer.
– Double-click index.html to display the Javadoc contents.
– Select BankClient class in the All Classes pane and verify that the
diagram has been imported.
Click Finish to generate the Javadoc, then open the Javadoc and browse the
classes with the generated diagrams.
For example, in a Java source file, the structural elements are package name,
import declarations, class, fields, and methods. We use the RAD7Java project to
demonstrate the use of the Outline view to navigate through the code:
Select and expand the RAD7Java → src → itso.rad7.bank.model from the
Package Explorer.
Double-click Account.java to open the file in the Java editor.
By selecting elements in the Outline view, you can navigate to the
corresponding point in your code. This allows you to easily find method and
field definitions without scrolling through the Java editor, as shown in
Figure 7-39.
Note: If you have a source file with many fields and methods, you can use the
Show Source of Selected Element Only feature. Select the open source file
in the Java editor, and click in the toolbar to limit the edit view to the
element that is currently selected in the Outline view.
Show bookmarks
To show the Bookmarks view select Window → Show View → General →
Bookmarks.
View bookmark
Bookmarks are indicated by the symbol in the gray sidebar (Figure 7-40), and
are listed in the Bookmarks view (Figure 7-41). Double-clicking the bookmark
entry in the Bookmarks view opens the file and navigates to the line where the
bookmark has been set.
Delete bookmarks
A bookmark can be removed by right-clicking on the bookmark symbol in the
gray sidebar and selecting Remove Bookmark or right-click the bookmark in the
Bookmarks view and select Delete, or click in the Bookmark view toolbar.
Note: Bookmarks can also be given for a file. It allows you to open it quickly
from the Bookmarks view later. Select the file in the Project Explorer and
select Edit → Add Bookmark.
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.
Type hierarchy
The Java editor allows the quick viewing of type hierarchy of a selected type.
Select a type with the cursor and press Ctrl+T to displays the hierarchy
(Figure 7-43).
Smart insert
To toggle the editor between smart insert and insert modes, press
Ctrl+Shift+Insert. When the editor is in smart insert mode, the editor provides
extra features specific to Java. For example, in smart insert mode when you cut
and paste code from a Java source to another Java source, all the needed
imports are automatically added to the target Java file.
Marking occurrences
When enabled, the editor highlights all occurrences of types, methods,
constants, non-constant fields, local variables, expressions throwing a declared
exception, method exits, methods implementing an interface, and targets of
break and continue statements, depending on the current cursor position in the
source code (Figure 7-44). For better orientation in large files, all occurrences
are marked with a white line on the right side of the code.
Smart compilation
The Java builder in the Application Developer workbench incrementally compiles
the Java code in the background as it is changed and displays any compilation
errors automatically, unless you disable the automatic build feature. Refer to
Chapter 4, “Perspectives, views, and editors” on page 117 for information on
enabling and disabling automatic builds and running workbench tasks in the
background.
In the Search dialog, you can perform file, text, or Java searches:
Java searches operate on the structure of the code.
File searches operate on the files by name and/or text content.
Text searches allow you to find matches inside comments and strings.
Java searches are faster, because there is an underlying indexing structure for
the code.
Click Search. While searching, you can click Cancel at any time to stop the
search. Partial results will be shown. The Search view shows the search
results.
Click or in the toolbar of the Search view to navigate to the next or
previous match. If the file in which the match was found is not currently open,
it is opened in the Java editor at the position of the match. Search matches
are tagged with a symbol on the left side of the source code line.
Right-click the resource you are looking for in the view or editor and select
References → Workspace, or press Ctrl+Shift+G.
Click Search. While searching, you can click Cancel at any time to stop the
search. Partial results will be shown. The Search view shows the search
results.
Note: To find all files of a given file name pattern, leave the Containing text
field empty.
Working sets
Working sets are used to filter resources by only including the specified
resources. They are selected and defined using the view's filter selection dialog.
We use an example to demonstrate the creation and use of a working set as
follows:
Click in the toolbar, or select Search → Java, or press Ctrl+H to open the
Java Search Dialog.
Enter itso.rad7.bank.model.Credit in the Search string field, select
Working set under Scope, and then click Choose.
In the Select Working Set dialog click New to create a new working set.
Select the new EntityPackage working set in the Select Working Sets dialog,
and click OK.
We have now created a working set named EntityPackage containing Java
resources comprised of all the Java files in the itso.rad7.bank.model
package.
Click Search to start the search process.
Quick fix
Application Developer offers a quick fix for some kind of problems, which were
detected during the code compilation or static code analysis. The developer can
process the quick fix to correct his code.
To process the quick fix, click on the symbol. All suggestions to correct the
problem are displayed in an overlaid window. As soon a suggestion is selected, a
code preview is shown, so that the developer can see, what will be changed
(Figure 7-49). Double-click one of the suggestion to process the quick fix.
Note: The problem symbol is grayed out but still visible. Save the source and
the problem symbol disappears.
Content assist
This feature displays possible code completions that are valid with the current
context.
The content assist provides the all possible code completions that are valid for
the current context in a overlaid window (Figure 7-51). Double-click the desired
completion, or use the arrow keys to select it, and press Enter.
Tip: If there are still too many possible completions, just continue to write the
code yourself and the amount of suggestions becomes smaller.
Import generation
The Java editor simplifies the task of finding the correct import statements to use
in the Java code.
Simply right-click the unknown type in the code and select Source → Add
Import, or select the type and press Ctrl+Shift+M. If the type is unambiguous,
the import statement is directly added. If the type exists in more than one
package, a window with all the types is displayed and you can select the correct
type for the import statement.
You can also add the required import statements for the whole compilation unit.
Right-click a project, package, or Java type in the Package Explorer and select
Source → Organize Imports, or select the project, package, or Java type and
press Ctrl+Shift+O. The code in the compilation unit is analyzed and the
appropriate import statements are added.
Adding constructors
This feature allows you to automatically add constructors to the open type. The
following constructors can be added:
Constructors from superclass
Constructor using fields
Figure 7-55 Simple car example class diagram (before method delegation)
Example 7-13 shows how the poor driver has to start his car.
// Engine class
package itso.rad7.example;
public class Engine {
public void start() {
// code to start the engine
}
}
// PoorDriver class
package itso.rad7.example;
import itso.rad7.example.Car;
public class PoorDriver {
public static void main(String[] args) {
Car myCar = new Car(null);
/* How can I start my car?
* Do I really have to touch the engine?
* - Yes, there is no other way at the moment.
*/
myCar.getCarEngine().start();
}
}
To make the driver happy, we delegate the start method from the Engine class to
the Car class. To delegate a method, do these steps:
Right-click the carEngine field in the Car class and select Source →
Generate Delegate Methods.
In the Generate Delegate Methods dialog, select only the start method and
click OK (Figure 7-56).
This action adds the start method to the Car class, and code is added in the
body of the method to delegate the method call to the Engine class through
the carEngine attribute.
Figure 7-57 and Example 7-14 shows how the HappyDriver can start the car.
Figure 7-57 Simple car example class diagram (after method delegation
// HappyDriver class
package itso.rad7.example;
public class HappyDriver {
public static void main(String[] args) {
Car myAdvancedCar = new Car(null);
// Start the car - I don't care about technical details
myAdvancedCar.start();
}
}
Refactoring
During the development of a Java application, it might be necessary to perform
tasks, such as renaming classes, moving classes between packages, and
breaking out code into separate methods. 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 a
list of refactor actions to automate the this process.
Rename Starts the Rename Compilation Unit wizard. Renames the selected
element and (if enabled) corrects all references to the elements (also in
other files). It 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 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.
Change Starts the Change Method Signature wizard. You can change the
Method visibility of the method, change parameter names, parameter order,
Signature parameter types, add parameters, and change return types. The wizard
updates all references to the changed method.
Extract Starts the Extract Interface wizard. You can create an interface from a
Interface set of methods and make the selected class implements the newly
created interface.
Push Down Starts the Push Down wizard. Moves a field or method to its subclasses.
Can be applied to one or more methods from the same type or on a text
selection resolving to a field or method.
Right-click the type and select Refactor → Push Down, or select the
element and select Refactor → Push Down from the menu bar.
Pull Up Starts the Pull Up wizard. Moves a field or method to its superclass. 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.
Right-click the type and select Refactor → Push Up, or select the
element and select Refactor → Push Up from the menu bar.
Extract Starts the Extract Method wizard. Creates a new method containing the
Method statements or expressions currently selected, and replaces the
selection with a reference to the new method.
Extract Starts the Extract Local Variable wizard. Creates a new variable
Local assigned to the expression currently selected and replaces the selection
Variable with a reference to the new variable.
Extract Starts the Extract Constant wizard. Creates a static final field from the
Constant selected expression and substitutes a field reference, and optionally
replaces all other places where the same expression occurs.
Inline Starts the Inline Method wizard. Inlines local variables, non abstract
methods, or static final fields.
Encapsulate Starts the Encapsulate Field wizard. Replaces all references to a field
Field with getter and setter methods. Is applicable to a selected field or a text
selection resolving to a field.
Note: If there are any files with unsaved changes in the workspace and
you have not indicated in the preferences that the save has to be done
automatically, you are prompted to save these files before continuing the
refactor operation.
The following URLs provide further information about Eclipse and Java
technology:
Sun Java™ SE Technology Home page—Contains links to specifications,
API Javadoc, and articles about Java SE:
http://java.sun.com/javase/index.jsp
IBM Developerworks Java Technology—Java news, downloads and CDs,
and learning resources:
http://www.ibm.com/developerworks/java/
Eclipse Open Source Community—Official home page of the eclipse open
source community:
http://www.eclipse.org/
The focus of the chapter is to demonstrate by example how to use the Rational
Application Developer patterns tooling to develop and use patterns.
The idea of pattern implementation came from the desire to go further than just
using the pattern specification as a blueprint—to try to automate as much as
possible the application of the pattern. The result is to codify the pattern
specification into a pattern implementation, allowing you to automatically apply it
into a given environment.
The core idea behind pattern implementation is that as we have codified and
automated best practices, applying them is now faster than doing it manually, and
more consistent, because it involves less manual modifications.
JET allow you to customize the output artifacts into an XML input file and a set of
templates. The structure of this input file, as well as how it impacts the different
artifacts, is based on what you are doing when creating your transformation using
the Application Developer Exemplar Authoring tools. Because the tools produce
JET, exemplar authoring transformations are also sometimes referred as JET
transformations.
Exemplar authoring is not only a set of tools, but more importantly, it is a process
to create pattern based into exemplars.
At a high level, these are the steps we follow as part of exemplar analysis:
1. Identify artifact roles. When examining the exemplar, we often find that
there are multiple elements that are based on the same abstraction. For
instance, in the case of JavaBeans we often see that there is a pair of
elements: An interface and a class that adheres to the interface. Our
exemplar might contain multiple JavaBeans, but if the intent of our pattern is
to generate JavaBeans, we just have to pick out the most representative pair
and can ignore the other repeating cases. In this case, although the exemplar
contains multiple beans, we have just a single role for the class and one for
the interface. An important aspect of this identification is that a JET template
is associated with each role.
2. Create role groups. Using the exemplar authoring tooling, we then have to
group the roles based on their cardinality. One time roles appear at the
highest level, and then we create subgroups for roles that repeat. Many
subgroups can exist with all elements within a subgroup sharing the same
cardinality. For instance, an Eclipse project can contain a number of artifacts
such as a .project file and a .classpath file, which occur only once per
project. However, we might have multiple JavaBeans within a project. As such
After importing the ITSO Bank sample, verify that it runs properly in the Java
perspective (BankClient). For more information refer to “Running the ITSO Bank
application” on page 281.
Note: The example we will be walking you through in the rest of the chapter is
probably not the best representation of a pattern implementation as its scope
of application is small (we will generate bank test clients). We selected this
example because it was providing enough variability to allow you to
understand how the exemplar authoring works, but not too much to not
overwhelm you by language and command details.
Click Finish and the EMF JET Transformation project is created. The
Exemplar Authoring editor now displays the RAD7JavaClient exemplar and
an empty model (Figure 8-3). The underlying file of this transformation is
called transform.tma (in case you have to reopen the transformation).
Exemplar Model
Figure 8-3 Exemplar Authoring editor
Figure 8-4 Artifacts added to the transformation model under the client type
Note: As you can see in Figure 8-4, each time you drag an artifact from the
exemplar to the model:
A create action (create project or create file) is created into the model.
The corresponding artifact into the exemplar is marked by a blue check
mark.
Each of the create actions will create the corresponding Eclipse resource.
Below are the names and paths of the associated exemplar artifacts:
– RAD7PatternsClient
– RAD7PatternsClient/.classpath
– RAD7PatternsClient/.project
– RAD7PatternsClient/src/itso/rad7/bank/client/BankClient.java
Some of the components of the names and paths that are likely to vary from
one test client to another:
– RAD7PatternsClient (project name)
– itso/rad7/bank/client (client directory corresponding to the client
package)
According to JET transformation best practices, these variable names have to
be stored in attributes and derived attributes.
In the Select Model Reference dialog, select the name attribute of the client
type and click OK.
Note that a query expression for the name attribute as been inserted as
{$client/@name}RAD7PatternsClient. Change the expression to
{$client/@name}Client to define the calculation correctly (Figure 8-7). Click
OK to get back to Replace with Model References dialog.
Note: The syntax used for the calculation is related to the fact that access
to the variable content is done by navigating an XML Domain Object Model
(DOM) using XPath.
Using the same approach to replace the path parameter of the .classpath
and .project elements. Select RAD7PatternsClient and replace the text with
a model reference to the projectName attribute (Figure 8-9):
{$client/$projectName}/.classpath
{$client/$projectName}/.project
Select the Create File: BankClient.java action and in the Properties view
replace RAD7PatternsClient with a model reference to the projectName
attribute:
{$client/$projectName}/src/itso/rad7/bank/client/BankClient.java
We defined package as a variable, therefore we want to replace
itso/rad7/bank/client by a new derived attribute. This derived attribute is
called clientDirectory (Figure 8-10).
Note: Be careful to click on the client type before adding the new derived
attribute. Consider the expression on the Calculation box:
{translate($client/@package,'.','/')}
Select the Create File: BankClient.java action and in the Properties view
replace the package directory with a reference to the clientDirectory
attribute (Figure 8-11):
{$client/$projectName}/src/{$client/$clientDirectory}/BankClient.java
Let us generate the templates and insert variables into the content of these
templates:
Right-click in the model transformation pane (for example near root) and
select Update Project. New Templates are generated into the project
(Figure 8-13).
Note: There is a blue underscore under the name element, indicating that
the underscored string matches the exemplar strings of one of the
attributes. This indicates that the string should probably be replaced by a
variable expression referencing this attribute.
Select the underscored text, right-click, and select Find/Replace with JET
Model Reference (Figure 8-14)
Figure 8-15 Replacing the project names with the projectName attribute
import itso.rad7.bank.exception.ITSOBankException;
import itso.rad7.bank.ifc.Bank;
In the Find/Replace with JET Model Reference dialog, select customer and
click New to create a new derived attribute. Call the new derived attribute
varName and type customer{$customer/@id} into the Calculation box
(Figure 8-19). Click OK to go back to the previous dialog.
Note: We also updated the output line before </c:iterate> to replace it with
only one account reference.
Notes:
Because we iterate to create different amounts, the declaration of the
amount variable (BigDecimal amount;) must be before the first
<c:iterate> tag.
As the debit code is applied to account12, the easiest way to reuse the
lines of code is to replace account12 by $account/@varName, so it
could be applied to any account we create.
The account iteration closing tag (</c:iterate>) has been moved after
the transaction iteration closing tag because a transaction is a subtype
of the account type.
Example 8-1 Template code containing the account and transaction parametrization
BigDecimal amount = 0; // top of method
<c:iterate select="$customer/account" var="account">
Account <c:get select="$account/@varName" /> = new Account
("<c:get select="$account/@id" />",
new BigDecimal(<c:get select="$account/@amount" />));
bank.openAccountForCustomer(<c:get select="$customer/@varName" />,
<c:get select="$account/@varName" />);
System.out.println("Account "
+ <c:get select="$account/@varName" />.getAccountNumber()
+ " has been successfully opened for "
+ <c:get select="$customer/@varName" /> + ".\n");
System.out.println("System is listing all account information of "
+ <c:get select="$customer/@varName" /> + "...");
System.out.println(bank.getAccountsForCustomer
(<c:get select="$customer/@varName" />.getSsn()));
We said previously that eventually we would like to create more than one
customer. To do so, we create a <c:iterate> tag. We also remove the
remaining transactions and the account close command, as we do not expect
our clients program to close any accounts. Example 8-2 shows the final
BankClient.java.jet with all the tags.
import itso.rad7.bank.exception.ITSOBankException;
import itso.rad7.bank.ifc.Bank;
import itso.rad7.bank.impl.ITSOBank;
import itso.rad7.bank.model.Account;
import itso.rad7.bank.model.Customer;
import java.math.BigDecimal;
Run Update Project before running the sample to make the model modifications
available for use in the JET templates. Save all the files.
Note: You can verify that both accounts have been created, that all
transactions were performed, and that the balance is the same between the
generated project and the exemplar project.
To run the transform, right-click sample2.xml and select Run As → Input for
Jet Transformation. Because the containing project is not a JET
transformation project, the Edit launch configuration properties dialog is
displayed. In this dialog, select RAD7PatternsTransform as transformation
id from the drop-down list (Figure 8-25).
Note: After doing this initial configuration, the JET transformation can be
rerun just by right-clicking sample2.xml and selecting Run As → Input for
Jet Transformation.
Facade pattern
In this section we describe a second example transformation, which generates
the facade (interface and implementation) for the sample banking application.
Facade transformation
Open the transform.tma file in RAD7PatternsFacadeTransform. The
transformation defines:
Attributes: name (of the interface), package (base package), systemProjName
(underlying project with the model)
Derived attributes: facadeDirectory (folders from package), facadeVarname
(variable for the interface), ifcPackage (package of interface), implClass
(implementation class name), implPackage (package of implementation), and
projectName (generated project)
Elements: entity (to define model objects), and operation (to define the
methods of the interface)
Creates: Project, .classpath, .project, Bank.java (interface), ITSOBank.java
(implementation)
Depending on your goals, this chapter is written for three types of users:
If you want to access databases and discover information about them, you
can use the database explorer to create a connection to those databases.
After you have set up connection information for a database, you can connect,
refresh a connection, and browse the objects that are contained in the
database.
If you want to develop database related activities such as SQL queries and
stored procedures, you have to create a data development project. The data
development project stores your routines and other data development objects.
Application developer also provides tooling to assist you to develop SQLJ
applications, and offers a DB beans package to access database information
without directly using the JDBC interface.
If you want to design your database model, you have to create a data design
project to store your objects. The modeling tool assists you to build a data
model, analyze the model, perform the impact analysis, and so forth.
All examples in this chapter are demonstrated against the open source
embedded Derby database server. The embedded version of Derby is bundled
inside Rational Application Developer, so its availability is guaranteed. These
examples can be easily applied to DB2 databases.
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 a Java
application or Java applet.
In JDBC 1.x 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.
Data source
In the JDBC 2.x Standard API, you can use a data source to access the
database. By using data source objects you have access to a pool of connections
through the data source. Using connection pooling gives you the following
advantages:
Improves performance—Creating connections is expensive; a data source
object creates a pool of connections as soon as it is instantiated.
Simplifies resource allocation—Resources are only allocated from the data
source objects, and not at arbitrary places in the code.
Connecting to databases
Application Developer enables you to create a connection to the following
databases:
Cloudscape 5.1
DB2 UDB v7.2, v8.1, 8.2, 9.1
DB2 UDB iSeries V5R2, V5R3, V5R4
DB2 UDB zSeries® V7, V8 New Function Mode and Compatibility Mode, V9
New Function Mode and Compatibility Mode
Derby 10.0, 10.1
Informix 9.2, 9.3, 9.4, 10.0
MySQL 4.0, 4.1
Oracle 8, 9, 10
SQL Server 2000, 2005
Sybase 12x, 15
You can use filters to exclude data objects (such as tables, schemas, stored
procedures, and user-defined functions) from the view. Only the data objects
that match the filter condition are shown. We only want to see the objects in
schema ITSO (Figure 9-2):
– Clear Disable filter.
– Select Selection.
– Select Include selected items.
In the Database Explorer view right-click the Customer table and select
Data → Sample Contents. The action opens the Data Output view
(Figure 9-5).
In this section, we create and run an SQL query to retrieve a customer name
based on the social security number, and the total amount of money involved in
each transaction type (credit, debit). The SQL select statement includes table
aliases, table joins, a query condition, a column alias, a sort type, a database
function expression and a grouping clause.
A data development project is used to store routines and queries. You can store
and develop the following types of objects in a database development project:
SQL scripts
DB2 and Derby stored procedures
DB2 user-defined functions
You can also test, debug, export, and deploy these objects from a data
development project. The wizards that are available in a data development
project use the connection information that is specified for the project to help you
develop objects that are targeted for that specific database.
Click Finish. The data development project is displayed in the Data Project
Explorer view.
Note: Stop the WebSphere Application Server v6.1 if it is running and has
accessed the ITSOBANK database for other chapters.
SQL
Source
Tables
Design
Joining tables
A join operation lets you retrieve data from two or more tables based on matching
column values. Three joins are needed for this query:
Drag the cursor from column SSN column in the C (CUSTOMER) table to column
CUSTOMERS_SSN in AC (ACCOUNTS_CUSTOMERS) table.
Drag the cursor from ACCOUNTS_ID in the AC (ACCOUNTS_CUSTOMERS) table
to ID in the A (ACCOUNT) table.
Drag the cursor from ID in the A (ACCOUNT) table to ACCOUNTS_ID in the T
(TRANSACTIONS) table.
Relationship lines are drawn between the selected columns (Figure 9-9).
The query is now complete. Save the select statement. The SQL statement is
listed in Example 9-1.
To improve application performance, you can create stored procedures that run
on a database server. A client application can then simply call the stored
procedures to obtain results of the SQL statements that are contained in the
procedure. Because the stored procedure runs the SQL statements on the
server for you, database performance is improved.
– Select the Conditions tab. In the first row double-click the cell under
Column and select CUSTOMER.LASTNAME. In the same row select
LIKE as the Operator and type :PARTIALNAME as the Value
(Figure 9-19).
– Click Next.
In the Change the SQL Statement page, review the generated SQL statement
and click Finish to close the New SQL Statement wizard.
Back in the New Stored Procedure wizard, select One for the Result set and
click Next.
In the Parameters page, leave the settings as default and click Next.
In the Deploy Options page of the wizard, clear Deploy. We will deploy the
stored procedure in later steps. Click Next.
In the Code Fragments page of the wizard, click Next.
Review your selections on the Summary page of the wizard and click Finish.
The generated file is opened and is shown in Example 9-2.
We will give $100 credit to the selected accounts. Add the following code
under the rs1[0] = stmt.getResultSet() statement (Example 9-3):
You can see a success build status in the Data Output view.
In the Data Explorer view you can see that ADDCREDIT has been added
under ITSOBANK → Schemas → ITSO → Stored Procedures.
Save AddCreditBean.java.
We have to add the Derby JDBC driver library to the project build path:
Right-click project RAD7DataDevelopment → Properties → Libraries
tab → click Add External JARs → select derby.jar, which is in
<RAD_HOME>\runtimes\base_v61\derby\lib. Click OK.
The SQLJ translator translates an SQLJ source file into a standard Java source
file plus an SQLJ serialized profile that encapsulates information about static
SQL in the SQLJ source. The translator converts SQLJ clauses to standard Java
statements by replacing the embedded SQL statements with calls to the SQLJ
runtime library. An SQLJ customization script binds the SQLJ profile to the
database, producing one or more database packages. The Java file is compiled
and run (with the packages) on the database. The SQLJ runtime environment
consists of an SQLJ runtime library that is implemented in pure Java. The SQLJ
runtime library calls the JDBC driver for the target database.
SQLJ provides better performance by using static SQL. SQLJ generally requires
fewer lines of code than JDBC to perform the same tasks. The SQLJ translator
checks the syntax of SQL statements during translation. SQLJ uses database
connections to type-check static SQL code. With SQLJ, you can embed Java
variables in SQL statements. SQLJ provides strong typing of query output and
return parameters and allows type-checking on calls. SQLJ provides static
package-level security with compile-time encapsulation of database
authorization.
Using the SQLJ wizard shipped with Application Developer, you can do the
following actions:
Name an SQLJ file and specify its package and source folder.
Specify advanced project properties, such as additional JAR files, to add to
the project classpath, translation options, and whether to use long package
names.
Select an existing SQL SELECT statement, or construct and test a new one.
Specify information for connecting to the database at run time.
In this section, we will create an SQLJ application to retrieve the customer and
the associated account information.
– Select the Joins tab. Drag the cursor from CUSTOMER.SSN to CUSTOMERS_SSN
and from ACCOUNT.ID to ACCOUNTS_ID (refer to Figure 9-18 on page 374).
– Select the Conditions tab. In the first row double-click the cell in the
Column and select ACCOUNT.BALANCE. In the same row select >= as
the Operator and type :BALANCE as the Value.
– Select the Order tab. Select ACCOUNT.BALANCE and click >. For Sort
order select DESC. The results will be listed with the highest balance first.
– Click Next.
In the Change the SQL Statement page, review the generated SQL statement
and click Next.
In the Specify Runtime Database Connection Information page, select Use
DriverManager Connection (Figure 9-26). Note that the URL takes values
previous dialogs. Single back slash (\) create errors when generated. Change
the URL to use forward slashes:
jdbc:derby:C:/7501code/database/derby/ITSOBANK;create=true
Click Finish. The SQLJ file is generated. If you see an error in the Problems
view, then you probably did not change the URL to use forward slashes.
Correct the SQLJ source file.
The next method moves to the next row of the result set if one exists.
We have to add the Derby JDBC driver library to the project build path:
Right-click project RAD7SQLJ → Properties → Libraries tab → click Add
External JARs → select derby.jar, which is in
<RAD_HOME>\runtimes\base_v61\derby\lib. Click OK.
This means that the Derby database is locked by another connection. Check
the Database Explorer if the ITSOBANK connection is still active. Disconnect the
connection, or restart the workbench.
Data modeling
Application Developer provides tools to create, modify, and generate DDL for
data models. At any time when you are building a data model, you can analyze
the model to verify that it is compliant with the defined constraints. If you make
changes to the data model, Application Developer provides tooling to compare
the changed data model with the original data model.You can also perform an
impact analysis to determine how the changes might affect other objects.
In the Workbench, you can create and modify data models by using the Data
Project Explorer, the Properties view, or a diagram of the model. You can also
analyze models and generate DDL.
A data design project is primarily used to store modeling objects. You can store
the following types of objects in a data design project:
Logical data models
Physical data models
Domain models
Glossary models
SQL scripts, including DDL scripts
The data design project is displayed in the Data Project Explorer view
(Figure 9-27).
Using the data tooling, you can create a physical data model in several ways:
Create a blank physical model by using a wizard.
Create a physical model from a template by using a wizard.
Reverse engineer a physical model from a database or a DDL file by using a
wizard or by dragging data objects from the Database Explorer.
Import a physical data model file from the file system.
In this section, we show you two ways to create the physical data model. First we
create a physical data model by reversing the model from an existing database
ITSOBANK. Then we create a new physical data model from a template and deploy
this new model to the database.
Figure 9-28 New Physical Data Model: Create from reverse engineering
The physical model is created and added to the Data Models folder. The
overview diagram is added to the Data Diagrams folder (Figure 9-30).
Figure 9-30 Data Design Project with physical model and diagram
Initial diagram
Diagram with
Show key and
Show non-key
Select a table in the diagram, then look at the Properties view to see the
columns and relationships.
Select a relationship (line) in the diagram and look at the Properties view to
see the cardinality (Details tab). The cardinality is also displayed visually in
the diagram.
Close the model.
The physical model is created and displayed in the Data Models folder. The data
diagram for the schema opens in the diagram editor.
In this section, we create a schema named RAD7Bank in the physical data model.
Under this schema, we create two tables: ACCOUNT and TRANSACTIONS.
In the Data Project Explorer select RAD7DataDesign → Data Models →
Bank_model.dbm → New Database → Schema, and in the Properties view
change the schema name from Schema to RAD7Bank.
To add a table, do these steps:
– Select the Data drawer in the palette and select Table in the Data drawer.
– Click the empty area in the data diagram. A new table is added to the
diagram.
– Overtype the table name with ACCOUNT.
Hover the mouse over the ACCOUNT table in the diagram and you see four
icons appearing outside of the table (Figure 9-32). Click the Add Key icon.
Overtype the name with ID (or change the name in the Properties view,
General tab).
Select the ID column, and in the Properties view, Type tab, change the Data
type to VARCHAR. Set the Length to 16 (Figure 9-33).
Note: The key ID must be uppercase. If you use lowercase, you might get the
following error message when you run DDL on server in later section:
SQL Exception: 'ID' is not a column in table or VTI 'ACCOUNT'..
Hover the mouse over the ACCOUNT table and click the Add Column icon.
In the Properties view change the Name to BALANCE, the data type to
INTEGER, and select Not Null.
Follow the same procedure to create the TRANSACTIONS table:
– Key:
ID VARCHAR(250) NOT NULL
– Columns:
TRANSTYPE VARCHAR(32) NOT NULL
TRANSTIME TIMESTAMP NOT NULL
AMOUNT INTEGER NOT NULL
ACCOUNTS_ID VARCHAR(16)
The data diagram is shown in Figure 9-34.
Quoted identifiers
are required if the
names contains
blanks.
Tip: You cannot see the RAD7BANK schema! Remember that your schemas are
filtered. Right-click Schemas → Filters and select Disable filters, then click
Finish. The RAD7BANK schema with two tables is now visible.
In the Migrate Key Option dialog, select Use the existing child
attribute/column, and click OK (Figure 9-38).
We use an
existing column
(ACCOUNTS_ID) as
foreign key
Select the foreign key relationship you just created. In the Properties view,
select the Details page.
Save the diagram. Notice the relationship verbs in the diagram (Figure 9-40).
Save the diagram and rerun Analyze Model. The error in the problems view
is gone.
We can see the following differences between the modified data model
modified and the model in the Derby database:
– We added a foreign key in the modified physical data model.
– When you export the database model to the Derby server, the Derby
database automatically creates an index on the primary key (one in each
table on the right-hand side).
We want to find the impact when adding the foreign key relationship to the data
model in the database. First we add the relationship in the compare editor,
analyze the impact, and then perform the change.
Tip: If the Generate Right DDL button is not active, close the compare editor
and run the comparison again (right-click the RAD7Bank schema and select
Compare With → Another Data Object). Then copy the <Foreign Key>
TRANS_ACCOUNT_FK from left to right, and the button is active.
In the Save and Run DDL page, examine the DDL in the Preview DDL
section. Specify the following settings (Figure 9-45) and click Next:
– Select the design project as the Folder.
– Type rad7bankDelta.sql as the File name.
– Review the DDL, which adds the foreign key constraint to the
TRANSACTIONS table.
– Select Run DDL on server.
More information
More information on JDBC can be found at:
http://java.sun.com/j2se/1.4.2/docs/guide/jdbc/
http://java.sun.com/javase/technologies/database/
http://developers.sun.com/product/jdbc/drivers
In this chapter we introduce the visual editor and develop a sample GUI, which
interacts with back-end business logic. This GUI is runnable as a JavaBean and
as a Java application.
The visual editor allows you to design GUIs 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—the visual
editor uses a process known as round-tripping to synchronize the two views.
To set up your development environment for the GUI sample application, you
have to create the database that the GUI uses and import some database
access classes.
Note: Creating a variable is a good practice for this kind of situation. The
alternative is to select Add External JARs which adds the full path to the JAR
file into the project build settings. A variable can be shared among all the
projects in the workspace, saving time for JAR files that are likely to be used
elsewhere.
The instructions for creating the ITSOBANK database are in “Setting up the
ITSOBANK database” on page 1312.
Imported code
The imported model classes in the itso.rad7.model.entity package are:
Account—JavaBean with two properties: id, balance.
Customer—JavaBean with four properties: ssn, firstName, lastName, title.
AccountFactory—Retrieve accounts from the database by id and customer.
CustomerFactory—Retrieve customer from the database by ssn.
DatabaseManager—Create a JDBC connection to the database.
The BankDesktop GUI class opens in the visual editor. this can take a while,
because Application Developer has to start a new JVM to display the GUI
visually in the Display view.
Figure 10-3 shows the new class BankDesktop in the Visual Editor.
Editor that
was used the
last time
When the visual editor is opened, two additional views open automatically:
The Java Beans view, in the bottom-left corner of the workspace, displays the
structure of the JavaBeans used in your GUI in a tree view.
The Properties view, at the bottom-right, lets you view and modify attribute
settings.
maximize/minimize
Click the up arrow, located in the center-left of the separator between the Design
and Source views (Figure 10-5), to maximize the Source view or the down arrow,
located to the right of the up arrow, to maximize the Design view.
The Palette automatically hides when not in use, but the appearance of the
Palette can be modified:
Click on a drawer to open or close the drawer.
Drawers can be fixed open within the Palette by clicking the pin icon next to
the drawer name.
To modify the preferences for the visual editor as a whole, select Window →
Preferences and select Java → Visual Editor.
Use this approach to resize the JFrame. Notice that the generated initialize
method is modified as a result of this change, so it now looks something like
Example 10-1 (the numbers in the setSize method call are probably different).
This code generates automatically when the visual and code views of your GUI
are synchronized (by default this takes place every second).
Code synchronization
We have seen that changes made in the Design view cause changes to the code.
The reverse is also true. Change the setSize method call in the initialize
method to setSize(440, 300), as seen in Example 10-2.
After you overtype the first number (the width), replacing it with 440, wait for
about a second and you see the visual representation of the GUI update even
without saving the code changes. During the short interval before the views are
synchronized, the status bar displays Out of synch instead of the usual
In synch.
You can also disable synchronization by clicking the Pause icon in the
toolbar. This is a good idea when you want to make a number of large changes to
the source without incurring the overhead of the round-tripping for synchronizing
the code and visual representations.
Tip: Once the content pane is selected, if you accidentally press Delete,
the content pane is deleted. To add it back, right-click the frame and select
Create Content Pane.
Select the Properties view and scroll down until you can see the layout
property with a value of BorderLayout.
Click the value to select it, then click it again to display a list of the available
values.
Select GridBagLayout from the list. Press Enter.
Select the JFrame title bar. Change the title of the JFrame by clicking the title
value (JFrame) and change it to Bank Desktop.
Save the work.
Click in the content pane, click OK to accept the default name, and the JLabel
appears in the center of the pane.
Select JTextField from the Palette and drop it to the right of the JLabel.
When the mouse pointer is in the correct position, the coordinates should be
(1,0)—indicating column 1, row 0.
The GUI works up to a point—you should be able to type into the text fields and
click Lookup—but we have not yet coded any event handling behavior.
Add the appropriate import statements. Right-click in the source and select
Source → Organize Imports or press Ctrl+Shift+O.
Save the file.
Enter xxx-xx-xxxx
as Search SSN where
x is any number
Try entering an invalid value. In the Console view, you see an error message
for the invalid value entered as well as an exception stack trace:
SQL Exception: Invalid cursor state - no current row.
at org.apache.derby.impl.jdbc.Util.newEmbedSQLException(Unknown Source)
...... at
itso.rad7.model.entity.CustomerFactory.getCustomer(CustomerFactory.java:14)
at itso.rad7.gui.BankDesktop.actionPerformed(BankDesktop.java:52) ......
In the visual editor, Swing visual components (such as text fields, tables, and
buttons) can be bound using the provided generic classes and interfaces.
To get a better feel, we will try this binding in the following example:
Select the customerName text field.
Click Bind above the field (Figure 10-14).
In the Find Data Bindings dialog, click New Data Source Data Object.
In the New Data Source Data Object dialog (Figure 10-15), enter the following
data:
– Name: customerDataObject
– Source type: Select Java Bean Factory.
– Data source: Click New next to Data source.
– Enter CustomerFactory into the search text field, and click OK.
– Source service: Select getCustomer.
– Argument: Select searchSSN (the text field).
– Property: Select text.
– Click OK.
Select fullName from the Data object properties list (Figure 10-16) and click
OK.
The main change is highlighted in bold. The code required to set the text of the
name and social security fields is no longer required—it is essentially replaced by
the call to getCustomerDataObject().refresh(), which handles the
synchronization for us.
Summary
In this chapter we demonstrated how to build a GUI application using the visual
editor of Application Developer. We used a number of features, such as graphical
layout, event handling generation, and data binding.
More information
For more detailed information on GUI development, refer to the following sites:
Java Swing V1.4.2 API:
http://java.sun.com/j2se/1.4.2/docs/guide/swing/
Java AWT V1.4.2 API:
http://java.sun.com/j2se/1.4.2/docs/guide/awt/
Eclipse homepage:
http://www.eclipse.org/platform/
XML is a key part of the software infrastructure. It provides a simple and flexible
means of defining, creating, and storing data. XML is used for a variety of
purposes ranging from configuration to messaging to data storage.
By allowing the user to define the structure of the XML document, the rules that
define the structure can also be used to validate a document to ensure they
conform.
XML documents follow strict syntax rules. To create, read, and update XML
documents, you require an XML processor or parser. At the heart of an XML
application is an XML processor that parses an XML document, so that the
document elements can be retrieved and transformed into a format understood
by the target client. The other responsibility of the parser is to check the syntax
and structure of the XML document.
An 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. 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
With XML schemas being extensible, they can be re-used in other schemas.
Multiple schemas can be referenced from the same document. In addition, they
have the ability to create new data types from standard data types.
XSL uses an XML notation and works on two principles—pattern matching and
templates. XSL 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 other structures can be added.
The result tree can be completely different from the source tree.
If both entities (a person and a book) have to be defined in the same document
(for example, in a library entry that associates a book with its author), we require
a 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 that
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.
Tip: Alternatively, you can change the element name in the Properties view,
General tab, Name field. The Properties view gives you lots of options to
modify the properties of an XML schema.
Right-click the Account complex type again, and select Add Element.
Now you are switched to the detailed view for complex type Account. Change
the element name to AccountId (Figure 11-2).
In our bank, the account ID is 6 to 8 digits long and takes in numbers 0-9:
– Click the element AccountId. In the Properties view, select the
Constraints tab.
– In Specific constraint values section, select Patterns. Click Add.
– In the Regular Expression wizard (Figure 11-3):
• In the Current regular expression field enter [0-9]{6,8}.
• Click Next.
• In the Sample text area, enter 123456.
• Note after you enter a 6-digit number, the warning in the dialog box is
gone.
• Click Finish.
In the Design view, right-click the sequence icon and select Add Element.
Change its name to AccountType. The bank account has three account
types: Savings, Loan, and Fixed:
– In the Properties view, select the Constraints tab. In the Specific
constraint values section, select Enumerations.
– Click Add and enter Savings.
To create an instance document from this XML schema, the XML schema
must have a global element. We add a global element named Accounts as
follows:
– Click the icon at the top left corner.
– In the Design view of the schema, right-click the Elements category and
select Add Element.
– Change the name to Accounts.
– In the Properties view, General tab, select the drop-down menu for Type,
select New..., then select complex type and Create as local anonymous
type, and click OK.
– Double-click Accounts and you are switched to the detailed view for
Accounts element. Right-click (AccountsType) and select Add Element.
– Change the name to Account.
– Right-click Account and select Set Type → Browse → Account.
– In the Design view, make sure Account is selected. In the Properties view,
General tab, set the Minimum Occurrence to 1 and Maximum
Occurrence to unbounded.
– Select Source → Format → Document to format the XSD file.
– Save and close the file.
<complexType name="Account">
<sequence>
<element name="AccountId">
<simpleType>
<restriction base="string">
<pattern value="[0-9]{6,8}"></pattern>
</restriction>
</simpleType>
</element>
<element name="AccountType">
<simpleType>
<restriction base="string">
<enumeration value="Savings"></enumeration>
<enumeration value="Loan"></enumeration>
<enumeration value="Fixed"></enumeration>
</restriction>
</simpleType>
</element>
<element name="Balance" type="decimal"></element>
<element name="Interest">
<simpleType>
<restriction base="decimal">
<minExclusive value="0"></minExclusive>
<maxExclusive value="100"></maxExclusive>
</restriction>
</simpleType>
</element>
<element name="CustomerInfo">
<complexType>
<sequence>
<element name="FirstName" type="string"></element>
<element name="LastName" type="string"></element>
<element name="PhoneNumber">
<simpleType>
<restriction base="string">
<pattern
value="\([0-9]{3}\) [0-9]{3}-[0-9]{4}">
</pattern>
</restriction>
<element name="Accounts">
<complexType>
<sequence>
<element name="Account" type="itso:Account"
minOccurs="1" maxOccurs="unbounded">
</element>
</sequence>
</complexType>
</element>
</schema>
In some cases, when you build the large J2EE projects, the XSD validation
process takes some time. You can disable the validator either at the project level,
or, at the global level:
To disable the validator at the project level, select the project and
Properties → Validation, then select Override validation preferences and
clear the XML Schema Validator.
To disable the validator at the global level, use the Window → Preferences
dialog (Figure 11-7) and clear the XML Schema Validator.
To see an error, for example, change a type from decimal to deximal, and run the
validation. Note after correcting the error you have to run validation again to
remove the error.
The HTML files are created in the location you specified. The generated
index.html file is opened in a Web browser inside Application Developer.
Explore the generated documentation by selecting the Account type and its
elements.
Double-click Default HTML header. This adds the default HTML header
information into the XSL file.
Position the cursor after the end tag </xsl:template>.
In the XSL drawer double-click HTML table in XSL.
In the XSL Table wizard (Figure 11-10):
XML mapping
The XML Mapping editor is a visual data mapping tool that is designed to
transform any combination of XML schema, DTD, or XML documents and
produce a deployable transformation document. You can map XML-based
documents graphically by connecting elements from a source document to
elements of a target document. You can extend built-in transformation functions
using custom XPath expressions and XSLT templates. The mapping tool
automates XSL code generation and produces a transformation document based
on the mapping information you provide.
You can select one of the following options to transform between the nodes
(Table 11-1).
Concat This type creates a string concatenation that allows you to retrieve data
from two or more entities to link them into a single result.
Inline map This type enables the map to call out to other maps, but other maps
cannot call it. It can only be used within the current map. If the inputs
and outputs are arrays, the inline map is implicitly iterated over the
inputs.
Submap This type references another map. It calls or invokes a map from this
or another map file. Choosing this transform type is most effective for
reuse purposes.
Substring This type extracts information as required. For example, the substring
lastname, firstname with a "," delimiter and a substring index of 0
returns the value lastname. If the substring index was changed to 1
the output would now be firstname.
Group This type takes an array or collection of data and groups them into a
collection of a collection. Essentially, it is an array containing an array.
Grouping is done at the field level, meaning that it is done by selecting
a field of the input collection such as “department.”
Normalize This type normalizes the input string. For example, it can be used to
remove multiple occurrences of white space (such as space, tab, or
return).
Custom This type allows you to enter custom code or call reference code to be
used in the transform. You can extend built-in transformation functions
using custom XPath expressions and XSLT templates.
In this section, we show you an example on mapping two XML schemas using
move, concat, inline map, substring. and custom options.
Sections
expanded
Resulting
XML
Properties
view
Edit
Figure 11-15 Inline map
Click Generate XSLT script. See Figure 11-15 to find this icon. You
immediately notice that the Accounts-out.xml is changed.
Note: Alternatively, you can simply save the mapping file and the changes are
automatically reflected in the resulting xml file.
Inline mapping
Click Edit at the top right corner of the Inline map. See Figure 11-15 to find
the Edit icon.
In the Inline map details view, perform the following mapping transforms:
– Map the AccountId, AccountType, Balance, and Interest by dragging
the elements from the left to the corresponding elements on the right. Note
that we map the element AccountId to the attribute AccountId.
– Click Generate XSLT script and verify how the account information is
generated in the XML output.
– Map the CustomerInfo element from left to right. This creates an inline
map. The current mapping is shown in Figure 11-16.
Click Generate XSLT script to see the change in the output XMl file.
Concatenation mapping
We want to concatenate last name and firstname into one element:
Click Edit at the top right corner of the CustomerInfo Inline map and add
these transformations:
– Select the FirstName element and drag it to the Name element on the
right.
– Select the LastName element and drag it to the Move transform box
between the Firstname and Name. When you drag a second element to
the transform type box, the transform type automatically changes to
Concat (Figure 11-17).
Substring mapping
The phone number is stored as a single data type in the source document and
we want to separate it into the sub-elements of area code and local number in
the target document.
Do the following steps to extract substrings:
– Select the PhoneNumber element on the left and drag it to the AreaCode
element on the right.
– Click the drop-down arrow in the transformation and select Substring
from the list.
– Right-click the transformation and select Show in Properties.
– In the Properties view, select the General tab. In the Delimiter field put a
space. Because the phone number format is (xxx) xxx-xxxx, the space
should be the delimiter between area code and local number.
– In the Substring index field, type 0.
– Select the PhoneNumber element and drag it to the LocalNumber
element.
– Change the transform type to Substring.
– In the Properties view in the Delimiter field, type a space.
– In the Substring index field, type 1. The current mapping is shown in
Figure 11-18.
To return to the main map, click the Up a level icon at the top right of the
inline map details page. Do it twice to return to the main map.
Calculation
We want to calculate the sum of the balance from all accounts and put it in the
BalanceSum attribute of the output document. We use an XPath expression to
calculate the total.
In the Properties view, General tab, select XPath as the Code and type
sum(./*/in:Balance) as the XPath expression (Figure 11-20).
Save the mapping file and click Generate XSLT script to see the final output
XML file. Notice the BalanceSum attribute in the <Accounts> tag and the formatting
of an account:
<out:Accounts xmlns:out="http://itso.rad7.xml.com" BalanceSum="70000">
<out:Account AccountId="123456" AccountType="Savings">
<out:Balance>20000</out:Balance>
<out:Interest>1.0</out:Interest>
<out:CustomerInfo>
<out:Name>Cui, Henry</out:Name>
<out:PhoneNumber>
<out:AreaCode>(123)</out:AreaCode>
<out:LocalNumber>456-7890</out:LocalNumber>
import java.math.BigDecimal;
import com.xml.rad7.itso.*;
import com.xml.rad7.itso.util.ItsoResourceUtil;
ItsoResourceUtil.getInstance().save(documentRoot, System.out);
ItsoResourceUtil.getInstance().save(documentRoot, "accounts.xml");
}
}
The core concepts in the SDO architecture are the data object and data graph:
A data object holds a set of named properties, each of which contains either a
primitive-type value or a reference to another data object. The data object API
provides a dynamic data API for manipulating these properties.
The data graph provides an envelope for data objects, and is the normal unit
of transport between components. Data graphs also have the responsibility to
track changes made to the graph of data objects, including inserts, deletes,
and modification to data object properties.
Data graphs are typically constructed from data sources, such as XML files,
EJBs, XML databases, relational databases, or from services, such as Web
services, JCA Resource Adapters, JMS messages, and so forth.
Components that can populate data graphs from data sources and commit
changes to data graphs back to the data source are called data mediator
services (DMS). DMS architecture and APIs are outside the scope of the
SDO specification.
This jar is used by our application code. If you do not add this JAR to the
project build path, you will get java.lang.NoClassDefFoundError :
org/eclipse/emf/ecore/change/ChangeDescription.
Add the sample code shown in Example 11-5 to the Java main method:
Figure 11-22 shows the accounts data graph of the XML file.
AccountsType
Account1 Account2
Add the code shown in Example 11-6 after the sample code in Example 11-5:
account2.delete();
More information
For more information on XML schemas, refer to:
http://www.w3.org/XML/Schema
In the first section, we describe the main tools available in Application Developer
to Web developers and introduce the new features provided with V7.0. Next we
present the design of the ITSO RedBank application, then we build and test the
application using the various tools available within Application Developer. In the
final section, we list sources of further information on J2EE Web components
and the Web tools within Application Developer.
Typically, in a large project, the JSPs and servlets are part of the presentation
layer of the application and include logic to invoke the higher level business
methods. The core business functions are usually separated out into a clearly
defined set of interfaces, so that these components can be used and changed
independently of the presentation layer (or layers, when there is more than one
interface).
Enterprise JavaBeans (EJBs) are also a key feature included in the J2EE
framework and are one popular option to implement the business logic of an
application. These are described in detail in Chapter 16, “Develop Web
applications using EJBs” on page 719. The separation of the presentation logic,
business logic, and the logic to combine them is referred to as the
model-view-controller pattern and is described later.
Technologies such as Struts, JavaServer Faces (JSF), various JSP tag libraries
and numerous others have been developed to extend the JSP and servlets
framework in different ways to improve aspects of J2EE Web development (for
example, JSF facilitates the construction of reusable UI components which can
be added to JSP pages). Some of these are described in detail in other chapters
of this book, however, it is important to note that the underlying technologies of
these tools are extensions to Java servlets and JSPs.
Struts
JavaServer Faces
(JSF)
Our focus in this chapter is on developing Web applications using JSPs, servlets,
and static pages using HTML with the tools included with Application Developer.
Once these concepts are mastered, it should be easier to understand the other
technologies available.
J2EE applications
At the highest level, the J2EE specification describes the construction of two
application types that can be deployed on any J2EE compliant application server.
These are Web applications represented by a Web Application Archive (WAR)
file or an enterprise application represented by an Enterprise Application Archive
(EAR) file. Both files are constructed in zip file format, with a defined directory
and file structure. Web applications generally contain the Web components
required to build the information presented to the end user and some lower level
logic, while the enterprise application contains an entire application including the
presentation logic and logic implementing its interactions with an underlying
database or other back-end system.
Also note that an EAR file can include one or more WAR files where the logic
within the Web applications (WARs) usually invokes the application logic in the
EAR.
Chapter 12. Develop Web applications using JSPs and servlets 467
Enterprise applications
An enterprise application project contains the hierarchy of resources that are
required to deploy an enterprise (J2EE) application to WebSphere Application
Server. It can contain a combination of Web applications (WAR files), EJB
modules, Java libraries, and application client modules (all stored in JAR format).
They also must include a deployment descriptor (applicaton.xml within the
META-INF directory), which contains meta information to guide the installation and
execution of the application.
The JAR files within an enterprise application can be used by the other contained
modules. This allows sharing of code at the application level by multiple Web or
EJB modules.
On deployment, the EAR file is unwrapped by the application server and the
individual components (EJB modules, WAR files, and associated JAR files) are
deployed individually, however, some aspects are configured across the
enterprise application as a whole including, for example, shared JAR files.
Web applications
A Web application server publishes the contents of a WAR file under a defined
URL root (called a context root) and then directs Web requests to the right
resources and returns the appropriate Web response to the requestor. Some
requests can be simply mapped to a simple static resource (such as HTML files
and images) while others are mapped to a specific JSP or servlet class, which
are referred to as dynamic resources. It is through these requests that the Java
logic for a Web application is initiated and calls to the main business logic are
processed.
When a Web request is received, the application server looks at the context root
of the URL to identify which WAR the request is intended for, then the server
looks at the contents after the root to identify which resource to send the request
to. This might be a static resource (html file), the contents of which are simply
returned, or a dynamic resource (servlet or JSP), where the processing of the
request is handed over to JSP or servlet code.
The structure of these elements within the WAR file is standardized and
compatible between different Web application servers. The J2EE specification
defines the hierarchical structure for the contents of a Web application that can
be used for deployment and packaging purposes. All J2EE compliant servlet
containers, including the test Web environment provided by Rational Application
Developer, support this structure.
The structure of a WAR file (and an EAR file) is shown in Figure 12-2.
Chapter 12. Develop Web applications using JSPs and servlets 469
J2EE Web APIs
The main classes used within the J2EE frame work and the interactions between
then are shown in Figure 12-3. The class ApplicationServlet is the only class
outside of the J2EE framework, and would contain the application logic.
Servlet
void init(..)
calls service(..) for
Application Server each web request
void service(ServletRequest, ServletResponse)
void destroy(..)
...
ServletRequest
String getParameter(String p)
HttpServlet
void set Attribute(String s,
Object o) doGet(..) JSPServlet
Object getAttribute(String s) doPost(..) _jspService(..)
ServletInputStream getInputStream() doPut(..)
... ...
ServletResponse
String getParameter(String p) HttpServletRequest
get request
void setAttribute(String s, Object o) String getParameter(String p)
properties
Object getAttribute(String s) void setAttribute(String s, Object o)
ServletInputStream getInputStream() Object getAttribute(String s) Application Servlet
... ...
HttpServletResponse
String getParameter(String p) RequestDispatcher HttpSession
void setAttribute(String s, Object o) void forward(..) void setAttribute(String s, Object o)
Object getAttribute(String s) void include(..) Object getAttribute(String s)
... ... ..
JSPs
It is possible to include any valid fragment of Java code in a JSP and mix it with
HTML. In the JSP code, the Java tags are marked by <% and %> and on
deployment (or sometimes the first page request, depending on configuration)
the JSP is compiled into a servlet class. This process combines the HTML and
the scriptlets in the JSP file in the _jspService method that populates the
HttpResponse variable. Combining a lot of complex Java code with HTML can
result in a very complicated JSP file, and except for very simple examples, this
practice should be avoided.
One way around this is to use custom JSP tag libraries, which are tags defined
by developers that initiate calls to a Java class. These classes implement the Tag,
BodyTag or IterationTag interfaces from the javax.servlet.jsp.tagext
package which is part of the J2EE framework. Each tag library is defined by a
.tld file which includes the location and content of the taglib class file. A
reference to this file has to be included in the deployment descriptor.
The most widely available tag library is the JavaServer Pages Standard Template
Library (JSTL), which provides some simple tags to handle simple operations
required in most JSP programming tasks, including looping, internationalization,
XML manipulation, and even processing of SQL result sets.
The RedBank application presented later uses JSTL tags to display tables and
add URLs to a page, and the final section of this chapter contains references on
what is possible with JSPs and tag libraries.
Following the MVC concept, a software application or module should separate its
business logic (model) from its presentation logic (view). This is desirable
because it is likely that the view will change over time and it should not be
necessary to change the business logic each time. Also, many applications might
have different views of the same business model, and if the view is not
separated, then adding an additional view causes considerable disruptions and
increase the component's complexity.
Chapter 12. Develop Web applications using JSPs and servlets 471
This separation can be achieved through the layering of the component into a
model layer (responsible for implementing the business logic) and a view layer
(responsible for rendering the user interface to a specific client type). In addition
the controller layer sits between the two, intercepting the a requests from the
view (or presentation) layer and mapping them to calls on the business model
and then returning the response based on a response page selected by the
controller layer. The key advantage provided by the controller layer is that the
presentation can focus just on the presentation aspects of the application and
leave the flow control and mapping to controller layer.
There are several ways to achieve this separation in J2EE applications and
various technologies, such as JavaServer Faces (JSF) and Struts, focus on
different ways of applying the MVC pattern. The focus of this chapter is on JSPs
and servlets that fit into the view and controller layers of the MVC pattern. If only
servlets and JSPs are used in an application, then the details of how to
implement the controller layer is left to whatever mechanism the development
team decides is appropriate, and which they can create using Java classes.
In one example presented later in this chapter, a Command pattern (see Design
Patterns, Elements of Reusable Object-Oriented Software in the bibliography) is
applied to encompass the request to the business logic and interactions made
with the business logic through a facade class, while in the other interactions the
request is sent directly to a servlet that makes method calls through the facade.
Some of these tools are illustrated further in the RedBank Web application
example built later in this chapter.
Chapter 12. Develop Web applications using JSPs and servlets 473
In the Web perspective, there are many views accessible (by selecting
Window → Show View), several of which are already open in the Web
perspective default setting.
Note: For more information on the Web perspective and views, refer to “Web
perspective” on page 146.
The flow of an application can be visually laid out and then the elements (JSPs,
HTML pages) rearranged until it fits the requirements. Once the flow is arranged,
a developer can begin creating pages based on this design.
When the structure of a site changes, (for example when a new page is added)
the navigation links are automatically regenerated to reflect the new Web site
structure.
To launch the Web Site Designer, double-click Web Site Navigation found in the
root of the Web project folder.
Note: For a detailed example of using the Web Site Designer, refer to
“Launching the Web Site Designer” on page 502.
Chapter 12. Develop Web applications using JSPs and servlets 475
Web Diagram
The Web Diagram (Figure 12-5) is another view of the Web application, which
shows the pages, the links between pages, and the page variables available on
each page. In addition, if Struts of JavaServer Faces technologies are being used
in the application, this view can include extra information to link the pages and
data together as appropriate for the selected technology.
In the RedBank example, the Web Diagram is not used to build the application.
Instead, the Web Site Navigation Designer is the tool with which pages are built
and relationships between pages are shown. Chapter 14, “Develop Web
applications using JSF and SDO” on page 587 and Chapter 13, “Develop Web
applications using Struts” on page 541 both provide examples of how to apply
the Web Diagram.
Page Designer
Page Designer is the primary editor within Application Developer for building
HTML, XHTML, JSPs, and JSF source code. It provides three representations of
a page: Design, Source, and Preview:
The Design tab provides a WYSIWYG environment to visually design the
contents of the page.
A good development technique is to work within the Design tab of Page Designer
and build up the HTML contents by clicking and dragging items from the Palette
view onto the page and arranging them with the mouse or editing properties
directly from the Properties view. The Outline view is also very helpful to navigate
quickly to another tag that is related (for example, an ancestor) to the tag being
edited. The Source tab can be used to change details not immediately obvious in
the Design tab, and the Preview tab can be used throughout the process to verify
the look of the final result.
Often it is the case that HTML content is provided to a development team and
created from tools other than Application Developer. These files can be imported
simply using the context menu on the target directory and selecting File →
Import → General → File System and browsing to the new file and clicking
Import. When an imported file is opened in Page Designer, all the standard
editing features are available.
Note: For a detailed example of using the Page Designer, refer to “Developing
the static Web resources” on page 508 and “Working with JSPs” on page 521.
Page templates
A page template contains common areas that you want to appear on all pages,
and content areas which are intended to be unique on each page. They are used
to provide a common look and feel for a Web project.
The Page Template File creation wizard is used to create these files. Once
created the file can be modified in Page Designer. The page templates are stored
as *.htpl files for HTML pages and *.jtpl files for JSP pages. Changes to the
page template are reflected in pages that use that template. Templates can be
applied to individual pages, groups of pages, or applied to an entire Web project.
Areas can be marked as read-only meaning that Page Designer will not allow the
user to modify those areas.
When creating a new page template, the user is prompted if the template is to be
a dynamic page template or a design time template:
Dynamic page templates are a new feature in Application Developer V7.0,
which make it possible to apply changes dynamically on a deployed
application and use Struts-Tiles technology.
Chapter 12. Develop Web applications using JSPs and servlets 477
Design time templates allow changes to be made and applied to the template
at design or build time, but once an application is deployed and running, the
page template cannot be changed. Design time templates do not rely on any
technologies other than the standard J2EE/servlet libraries.
CSS Designer
Cascading style sheets (CSS) are a tool used with HTML pages to ensure that
an application has consistent colors, fonts, and sizes across all pages. It is
possible to create a default style sheet when creating a new project and there are
several samples included with Application Developer. Usually, a good idea is to
decide on the overall theme (color, fonts) for your Web application in the
beginning and create the style sheet at the start of the development effort. Then,
as you create the HTML and JSP files, you can select that style sheet to ensure
that the look of the Web pages are consistent. Style sheets are commonly kept in
the WebContent/theme folder.
The CSS Designer is used to modify cascading style sheet *.css files. It provides
two panels, the right hand side showing all the text types and their respective
fonts, sizes, and colors which are all editable. On the left hand side, a sample of
how the various settings will look. Any changes made are immediately applied to
the design in Page Designer if the HTML file is linked to the CSS file.
Security Editor
The Security Editor is a new enhancement with Application Developer V7.0. It
provides a wizard to specify security groups within a Web application and the
URLs that group has access to. The J2EE specification allows for security groups
and levels of access to defined sets of URLs to be defined in the deployment
descriptor and the Security Editor provides a nice interface for this information
(Figure 12-6).
Selecting an entry in the Security Roles pane shows the resources members of
that role in the Resources pane, and the Constraint rules that are applicable for
the role and resource (if one is selected). Each entry in the Constraints window
has a list of resource collections, which specify the resources available to it and
which HTTP methods can be used to access these resources. Using context
menus it is possible to create new roles, security constraints, and add resource
collections to these restraints.
Note that J2EE security specification defines the mechanism for declaring
groups and the URL sets that each group can access, but it is up to the Web
Container to map this information to an external security system. WebSphere’s
administrative console provides the mechanism to configure an external LDAP
directory. Refer to the IBM Redbooks publication, Experience J2EE! Using
WebSphere Application Server V6.1, SG24-7297.
Chapter 12. Develop Web applications using JSPs and servlets 479
The wizards available in the Web perspective are as follows:
CSS—The CSS file wizard is used to create a new cascading style sheet
(CSS) in a specified folder.
Dynamic Web Project—Steps the user through the creation of a new Web
project, including which features the project use and any page templates
present.
Filter—Constructs a skeleton Java class for a J2EE filter, which provides a
mechanism for performing processing on a Web request before it reaches a
servlet. The wizard also updates the web.xml file with the filter details.
Filter Mapping—Steps the user though the creation of a set of URLs to map
a J2EE filter with, The result of this wizard is stored in the deployment
descriptor.
Javascript—Used to create a new Javascript file in a specified folder.
Life-cycle Listener—The J2EE specification allows for classes to be
configured to receive pertinent events from the Web container. For example
the classes which implement the HttpSessionListener interface and are
declared in the deployment descriptor, receive notification every time a
HttpSession is created or destroyed. This wizard guides the user through the
creation of such a listener and automatically adds a reference to it to the
deployment descriptor.
Security Constraint—Used to populate the <security-constraint> in the
deployment descriptor which contains a set of URLs and a set of http
methods which members of particular security role might (or might not) be
entitled to access.
Security Role—Adds a <security-role> element to the deployment
descriptor.
Servlet—Used to create a skeleton servlet class and add the servlet to the
deployment descriptor.
Servlet Mapping—Steps the user through the creation of new URL to servlet
mapping and adds it to the deployment descriptor.
Static Web Project—Steps the user through building a new Web project
containing only static pages.
Web Diagram—It is possible to create a Web Diagram for a Web project
which already has a large number of pages. This wizard creates an empty
Web Diagram onto which the user can place existing pages and show existing
page relationships.
Web Page—The Web Page wizard allows you to create an HTML or JSP file
in a specified folder, with the option to create from a large number of page
templates.
Note that there are also a number of wizards specifically for Struts and JSF,
which are discussed in other chapters.
Chapter 12. Develop Web applications using JSPs and servlets 481
Page Designer—The following changes have been made to the Page
Designer:
– HTML/JSP code folding (structured source editting.pdf)—These now
have support in HTML and JSP editing for code folding, that is, expanding
and shrinking HTML elements (also CSS, XML, HTML and JSP).
– Struts tiles support—Projects can now be created using Struts tiles. JSP
pages using Struts tiles now visualize these components in the Design
tab.
– Page Data view usability—The items and menus on the Page Data view
are categorized for better usability.
– Preview page support for Linux—Formerly this was only available for
Windows users, but it is now also available on Linux.
– HTML validation—The HTML editor now features as-you-type validation
as well as validation when building.
– Web site navigation improvements— New menu style navigation tabs
(Tabbed menu, Vertical menu and Tabbed menu) are available. Pages
which are shared in multiple locations in the Web structure can now be
included in Navigation bars. Also, navigation on unmapped pages (that is
pages not shown in the Web Site Navigation view) is now possible and the
usual navigation elements are available for adding to the page.
– Visualization for third Party JSF components —Now third party
providers of JSF components can provide visualization of the components,
which is displayed in the Design tab.
Model
The model for the RedBank project is implemented using a simple Java project,
exposed to other components through a facade interface (called ITSOBank). The
main ITSOBank object is a singleton object, accessible by a single static public
method called getBank.
The ITSOBank object is composed of the other business objects which make up
the application, including Customer, Account, and Transaction. The facade into
Stores HashMap of
Credit Debit
The underlying technology to store data used by the ITSOBank application are
Java HashMaps. These are populated at startup in the constructor and obviously
the data is lost every time the application is restarted. In a real world example
this would be stored in a database, but for the purposes of this example
HashMaps are fine. In Chapter 16, “Develop Web applications using EJBs” on
page 719 the ITSOBank model is modified to run as EJBs and the application data
is stored in a database.
View layer
The view layer of the RedBank application is composed of four HTML files and
four JSP files. The application home page is the index.html containing a link to
three HTML pages (rates.html, insurance.html, and redbank.html).
rates.html, index.html, and insurance.html are simple static HTML pages
showing information, but no forms or entry fields.
redbank.html contains a single form which allows a user to type in the
customer ID to access the customer services such as accessing balance, and
performing transactions. Note that although the account number is verified,
security issues (logon and password) are not covered in this example.
Chapter 12. Develop Web applications using JSPs and servlets 483
From redbank.html the user is shown the lisAccounts.jsp page, which
shows the customer’s details, a list of accounts, and a button to logout.
Selecting an account brings up the accountDetails.jsp, which also shows
the balance for the selected account and a form through which a transaction
can be performed. This 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, depending on the option
selected. One of the transaction options on AccountDetails.jsp is List
Transactions, which invokes the listTransactions.jsp.
If anything goes wrong in the regular flow of events, the exception page
(showException.jsp) is shown to inform the user of the error.
These four JSP pages (listAccounts.jsp, accountDetails.jsp,
listTransactions.jsp, and showException.jsp) make up the dynamic pages
of the RedBank application.
Refer to Figure 12-21 on page 507 for a diagram showing the planned structure
of pages within the RedBank application. The diagram was created using the
Web Site Designer tool.
Controller layer
The controller layer was implemented using two different strategies: One
straightforward; and the other more complex, but more applicable to a real world
situation.
The first three servlets use a simple function call from the servlet to the model
classes to implement their controller logic and then use the RequestDispatcher
to forward control onto another JSP or HTML resource. The pattern used is
shown in the sequence diagram in Figure 12-8.
calls doPost()
searchCustomerBySsn()
getAccountsForCustomer()
forwardRequest()
(through the RequestDispatcher)
Returns page
showing list of
accounts
Chapter 12. Develop Web applications using JSPs and servlets 485
User's Web
PerformTransaction
Application ListTransactionsCommand ITSOBank listTransactions.jsp
browser Server Servlet
HttpPost to
ListAccounts
servlet.
calls doPost() with
transaction=list
calls execute()
searchAccountByAccountNumber()
getTransactionsForAccount()
getForwardView()
forwardRequest()
(through the RequestDispatcher)
Returns page
showing list of
accounts
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.
Note that the completed application has already been developed and is available
to explore if required by importing the project interchange file:
c:\7501code\zInterchangeFiles\webapps\RAD7BankBasicWeb.zip
At the end of this section, the RedBank application should be ready for testing.
Note: Before this, it might be a good idea to check that Web capabilities are
enabled. Select Windows → Preferences and expand General →
Capabilities make sure that Web Developer options (including basic, typical
and advanced) are selected.
There are two types of Web projects available in Application Developer, namely,
static and dynamic. Static Web projects contain static HTML resources and no
Java code, and thus are comparatively simple. In order to demonstrate as many
features of Application Developer as possible, and because the RedBank
application contains both static and dynamic content, a dynamic Web project is
used for this example.
Chapter 12. Develop Web applications using JSPs and servlets 487
– Target Runtime: Select WebSphere Application Server v6.1 (default).
This option will display the supported test environments that have been
installed. Use WebSphere Application Server V6.1 Test Environment.
– Under Configurations select <custom> (default). This option allows a user
to make use of some pre-defined project configurations to speed up
creating new projects.
– Select Add module to an EAR project (default).
Dynamic Web Projects, such as the one we are creating, run exclusively
within an enterprise application. For this reason, you have to either create
a new EAR project or select an existing project.
– EAR Project Name: RAD7BankBasicEAR (overtype the default). Because we
selected Add module to an EAR project, the wizard will create a new
EAR project.
In the Project Facets dialog, select the features for Default Style Sheet,
Design-Time Page Template support, JSTL, Web Site Navigation
WebSphere Web (Co-existence) and WebSphere Web (Extended)
as seen in Figure 12-11.
Note: The options shown with a “..” next to the Version allow you to alter
the underlying version of this feature being selected. By default, the latest
version available is always chosen.
From this dialog, it is also possible to save the configuration for future
projects. To do this, just click Save and enter a configuration name and a
description, as shown in Figure 12-12. The new configuration is available as a
configuration option for subsequent projects and shown in the Configurations
drop-down list (see Figure 12-10).
Chapter 12. Develop Web applications using JSPs and servlets 489
Figure 12-12 Save new Dynamic Web Page Facts Configuration
In the Web Module pag, accept the default options (refer to Figure 12-13).
Click Finish and the Dynamic Web Project is created. The Web Diagram is
opened automatically; this can be closed, as the work for building this
application is done in the Web Site Navigation tool.
Chapter 12. Develop Web applications using JSPs and servlets 491
Structured view into
EAR deployment
descriptor
The main folders shown under the Web project are as follows:
Deployment Descriptor—This shows an abstracted view of the contents of
the projects web.xml. It includes sub folders for the main pieces which make
up a Web project configuration, including Servlets and Servlet Mappings,
Filters and Filter Mappings, Listeners, Security and References.
Web Site Navigation wizard—Clicking on this starts up the tool for editing
the page navigation structure.
Java Resources: src—This folder contains the Java source code for regular
classes, JavaBeans, and servlets. When resources are added to a Web
project, they are automatically compiled, and the generated class files are
added to the WebContent\WEB-INF\classes folder.
WebContent—This folder holds the contents of the WAR file that is deployed
to the server. It contains all the Web resources, including compiled Java
Important: Files that are not under WebContent are not deployed when
the Web project is published. Typically this would include Java source and
SQL files. Make sure that you place everything that should be published
under the WebContent folder.
To verify that the model is running, it is possible to run the main method of the
class itso.rad7.bank.client.BankClient class. This will invoke the bank
facade classes directly, make some simple transactions directly and print out the
results to System.out.
Chapter 12. Develop Web applications using JSPs and servlets 493
Create new page templates
Page templates provide an efficient method of creating a common layout for Web
pages. They can be created from an existing sample page template or be
user-defined and can be shared across many (or even all) pages in a Web
application. If changes are required to one of the common sections of a template,
it needs to be updated only in one place.
In this example, design-time page templates are applied for the JSPs, which
means that the pages are built from the template in the design/build phase.
Dynamic templates are the other option that would allow the page template data
to be updated while the application is running.
We recommend that you create a page template prior to creating the pages in
the Web Site Designer so that the page template can be specified at the time
each page is created.
Note: The Page Template wizard works in such a way that if a new page
template is created from a sample, then all page elements of the new
template are read-only, except for the content area. This is not the desired
behavior for our example because we want to be able to make changes to
all aspects of the template. To get around this feature, we rename the
sample template to our new template file name.
Chapter 12. Develop Web applications using JSPs and servlets 495
The underlying mechanism within Application Developer for applying a template
to a JSP is very different from that used for an HTML template. Therefore,
although the two templates have the same headers, footers, and icons two
separate templates are required.
Note: As with the HTML case, we want to be able to change all aspects of
the original template, and so we copy the sample template over our new
template.
The RedBank JSP template now exists in the itso_jsp_template.jtpl file under
WebContent/theme.
Chapter 12. Develop Web applications using JSPs and servlets 497
Customize the links on the navigation bar
A navigation bar is a set of links to other Web pages, displayed as a horizontal or
vertical bar on a Web page. When these links are applied consistently to all
pages in an application, users can easily find their way around a new site. For the
RedBank application, it is desirable to have a list of the children of the top page
shown across the top and a list of ancestor pages, from the currently page shown
up to the root, shown at the bottom.
Application Developer has a feature to make the addition of these navigation bars
very easy. In the Pallet view under the Web Site Navigation drawer are a series of
elements which can be dragged onto pages to provide this navigation.
In our example, the sample template already included a navigation bar to the top
and bottom of the Web pages. These do however require some changes.
Perform the following steps to customize the links on the navigation bar:
Open itso_html_template.htpl and move to the Design tab.
Click on the top grey bar, which has the text Children of top page written on
it.
In the Properties view (which should be showing a Bar tab selected), click on
the Link Destination tab immediately below the Bar tab.
Select Children of Top Page (should be already selected), which is what is
required. This means that links to the rates, insurance, and bank pages are
shown across the top bar on all pages that use this template.
Click on the bottom grey bar which has the text Sibling Pages displayed on it.
In the Properties view click on the Link Destination tab immediately below
the Bar tab.
Clear Sibling pages and select Ancestor pages Figure 12-16). Originally
this page was configured to show the siblings of the current page at the
bottom, this has to be changed to show an ancestor tree back to the main
index page.
Note: The tools available for Web site navigation have been enhanced in
V7.0. Among other features, there are now Vertical Menu and Tabbed
Menu elements in the Palette view in the Web Site Navigation drawer,
which allow the addition of drop-down menu style navigation bars.
clear
The page template for the HTML pages is now finished (Figure 12-17) and it is
possible to generate a series of HTML pages from it for the RedBank application.
Chapter 12. Develop Web applications using JSPs and servlets 499
Figure 12-17 Completed HTML template (compressed)
The page template for the JSP pages should now be created and it is possible to
generate a series of JSP pages from it for the RedBank application.
To fix this problem, copy the c.gif file from WebContent\theme to WebContent.
In the RedBank example a style sheet named gray.css was created as part of
the process of creating the page templates from the samples. Both the HTML
(itso_html_template.htpl) and the JSP (itso_jsp_template.jhtpl) templates
reference the gray.css style sheet for them to have a common appearance of
fonts and colors for the pages.
In the following example, we customize the colors used on the navigation bar
links, and supporting variations such as hover links. By default the link text in the
navigation bar is orange (cc6600). We will customize this to be red (FF0000). To
find the hexadecimal code for a particular color a resource is supplied in the
references section at the end of this chapter.
Chapter 12. Develop Web applications using JSPs and servlets 501
Figure 12-18 CSS Designer: gray.css
Change the Hex HTML color code for all nav-h-highlighted entries from
color: #cc6600; (orange) to color: #FF0000; (red).
Customize the footer highlighted link text. Locate the .nav-f-highlighted
style and change the color from #ff6600 (orange) to #ff0000 (red).
Save the file.
Now when a page is navigated to, the header and footer tabs will show the
current the currently viewed page in red rather than orange.
Obviously any number of changes can be applied to the style sheets to change
the look, feel, and color of the application.
Palette View
for new pages
and groups
Navigation or
Detail tab of
Site Designer
Chapter 12. Develop Web applications using JSPs and servlets 503
Create the Web site navigation and pages
In this section, we use the Web Site Designer to construct the page navigation
and page skeletons for the RedBank Web site. At the end we will have a working
skeleton of the application, where we can navigate from page to page using the
tabs below the page header and the ancestor tabs. The pages will not have any
actual content but this is added later.
We will create the navigation pages and corresponding HTML or JSP page for
each of the following pages:
itsohome index.html
rates rates.html
insurance insurance.html
redbank redbank.html
listaccounts listAccounts.jsp
accountdetails accountDetails,jsp
listtransactions listTransactions.jsp
showexception showException.jsp
To define the site navigation and create the HTML and JSP page skeletons,
perform the following steps in the Web Site Designer:
Launch the Web Site Designer from the Project Explorer.
Create the root static navigation page (index.html):
– Select New Page from the Palette and click on the Navigation page to add
the first page.
– After the new page is added, the navigation label can be entered in the
Navigation page or in the Properties view under Navigation label. Enter
itsohome. Save the Navigation page.
– Double-click the itsohome navigation page to create the HTML file
associated with the index page.
– In the New Web Page dialog, enter the following items (Figure 12-20).
• File name: index.html
By default, a Web Server will look for index.html (or index.htm) when
a Web project is run. Although this behavior can be changed, we
recommend that you use index.html as the top level page name.
Chapter 12. Develop Web applications using JSPs and servlets 505
Page groups are used to logically build or organize pages into a movable
block of related pages. In the RedBank example the JSPs under
redbank.html are grouped together.
– Select the redbank page, right-click, and select Add New Group → As
Child. A Group box appears below the redbank page.
– Select the group and in the Properties view, Group tab, type RedBank as
the group name.
– Save the Navigation page.
Create the dynamic pages (JSPs) listaccounts, accountdetails,
listtransactions, and showexception.
– From the context menu of the RedBank group, select Add → New Page →
Into Group.
– After the New Page is added, notice you can type the navigation label in
the Navigation page or in the Properties view as Navigation label. For the
first page, enter listaccounts.
– Double-click the listaccounts box to create the JSP file associated with
the navigation label.
– In the New Web Page dialog, enter the following items and then click Next:
• File name: listAccounts.jsp
• Template: Select My Templates → theme/itso_jsp_template.jtpl
• Make sure Link Page to template is selected.
Note that when creating JSPs the Options button is active. This provides
options to specify the Document Markup properties, to have the wizard
automatically generate servlet stubs methods and to add extra fields to the
web.xml file. For this example, the default options are fine.
– Click Finish to create the page.
Repeat the steps to add the accountdetails (accountDetails.jsp),
listtransactions (listTransactions.jsp), and showexception
(showException.jsp) pages. Note that the spelling and capitalization of the
JSP file names must be perfect.
The showexception page only appears when there is a problem and is not
part of the standard navigation. Therefore, select the showexception page,
right-click, and select Set Navigation → Show in Navigation (this clears the
option).
Change the <title> tag through the Navigation editor, Detail tab, in the Page
Title column of each JSP to List Accounts, Account Detail, List Transactions,
and Show Exception. This action changes the <title> tag in the source code
of each JSP.
When done adding the navigation, HTML, and JSP pages, the Navigation page
should look like Figure 12-21.
Chapter 12. Develop Web applications using JSPs and servlets 507
Figure 12-22 ITSO RedBank Web site
To verify the JSPs, type this URL directly into the browser:
http://localhost:9080/RAD7BankBasicWeb/listAccounts.jsp
The list accounts page is shown. Note that the Ancestor trail at the bottom of
the page shows itsohome and redbank, which is the correct ancestor tree for
this page. The same test can be performed for the other JSPs.
To remove the project from the test server, in the Servers view right-click
WebSphere Application Server v6.1, select Add Remove Projects, and
remove RAD7BankBasicEAR.
Alternatively, expand WebSphere Application Server v6.1, right-click the
RAD7BankBasicEAR project and select Remove.
Chapter 12. Develop Web applications using JSPs and servlets 509
Figure 12-23 Preview of index.html
Note: Additional table rows and columns can be added and deleted with
the Table menu option.
Chapter 12. Develop Web applications using JSPs and servlets 511
Figure 12-25 Preview of Insurance.html
The static HTML pages for the RedBank application are now complete.
The wizards not only support the creation of servlets and JSPs, they also
compile the Java code and store the class files in the correct folders for
publishing to your application servers. Finally, as the wizards generate project
resources, the deployment descriptor file (web.xml) is updated automatically with
the appropriate configuration information for the servlets that are created.
In the previous section we described how to create each of the static Web pages.
In this section we demonstrate the process of creating and working with servlets.
The example servlets are first built using the wizards, then the code contents are
imported from the sample solution. In the next section “Working with JSPs” on
page 521, the JSP pages are created which invoke the logic in these servlets.
Chapter 12. Develop Web applications using JSPs and servlets 513
Adding RAD7Java as a Web Library project
Before the implementation of the servlet classes can proceed, we must add a
reference from the RAD7BankBasicWeb project to the RAD7Java project,
because the servlets call the methods from classes in this project.
This uses a facility within Application Developer known as Web Library projects,
where a Java project can be associated with a Web project so that the Java
resources in the Web project can call those in the Java project. Also, when the
WAR file is built, a JAR file representing the Java project is automatically added
to the WEB-INF/lib directory.
Tip: The Create Servlet wizard can also be accessed by right-clicking the
project and selecting New → Servlet.
The first page of the Create Servlet wizard opens. Enter ListAccounts as the
class name and itso.rad7.webapps.servlet as the package (Figure 12-28).
Click Next.
The second page (Figure 12-29) provides space for the name and description
of the new servlet.
The page also allows the addition of servlet initialization parameters, which
are used to parameterize a servlet. Servlet initialization parameters can be
changed at runtime from within the WebSphere Application Server
administrative console.
The wizard will automatically generate the URL mapping /ListAccounts for
the new servlet. If a different, or additional URL mappings are required, these
can be added here.
Chapter 12. Develop Web applications using JSPs and servlets 515
In our sample, we do not require additional URL mappings or initialization
parameters. Click Next.
The third and final page gives the option to have the wizard create stubs
methods for methods available from the HttpServlet interface. The init
method is called at start-up and destroy is called at shutdown. The doPost,
doGet, doPut, and doDelete methods are called when a http request is
received for this servlet. All of the do methods have two parameters, namely a
HttpServletRequest and a HttpServletResponse. It is the job of these
methods is to extract the pertinent details from the request and populate the
response object.
For the ListAccounts servlet, only doGet and doPost should be selected.
Usually, HTTP gets are used with direct links, when no information has to be
sent to the server. HTTP posts are typically used when information in a form
has to be sent to the server.
There is no initialization required for our new servlet and so the init method
is not selected.
Ensure that the options are selected as shown in Figure 12-30, and click
Finish.
The servlet is generated and added to the project. The source code can be found
in the Java Resources folder of the project, while the configuration for the servlet
is found in Servlets tab of the Web deployment descriptor.
Chapter 12. Develop Web applications using JSPs and servlets 517
The performTask method does the following tasks:
– First the method deals with the HTTP request parameters supplied in the
request. This servlet expects to either receive a parameter called
customerNumber 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.
– Next the method implements the control logic. Access to the Bank facade
is obtained through the ITSOBank.getBank() method and it is used to get
the customer object and the array of accounts for that customer.
– The third section adds the customer and account variables to the
HttpRequest object so that the presentation renderer (listAccounts.jsp)
gets the parameters it requires to perform its job. The control of processing
the request is then passed through to listAccounts.jsp using the
RequestDispatcher.forward method, which builds the response to be
shown on the browser.
– The final part of the method is the error handler. If an exception is thrown
in the previous code, the catch block will ensure that control is passed to
the showException.jsp page.
See Figure 12-8 on page 485 for a sequence diagram of the design of this
class.
The ListAccounts servlet is now complete. The changes should be saved
and the source editor closed.
The servlet requires that the SSN of the customer that is to be updated is already
placed on the session (as should be done in the ListAccounts servlet). It extracts
the title, firstName and lastName parameters from the HttpRequest object, calls
the bank.getCustomer(String customerNumber) method and then uses the
simple setters on the Customer class to update the details.
Follow the procedures described in “Adding the ListAccounts servlet to the Web
project” on page 515 and “Implementing the ListAccounts servlet” on page 517
for building the servlet, including the doGet and doPost methods. The name of
this servlet class should be UpdateCustomer.
Follow the procedures described in “Adding the ListAccounts servlet to the Web
project” on page 515 and “Implementing the ListAccounts servlet” on page 517
for building the servlet. The name of the class should be AccountDetails.
Follow the procedures described in “Adding the ListAccounts servlet to the Web
project” on page 515 and “Implementing the ListAccounts servlet” on page 517
for building the servlet. The name of the class should be Logout.
The design for this was presented in “Controller layer” on page 484, and this
implementation is based on the sequence diagram (Figure 12-9 on page 486).
Chapter 12. Develop Web applications using JSPs and servlets 519
Import the code for the commands package. The source is located in the folder:
C:\7501code\webapps\itso.rad7.webapps.command
Create the package itso.rad7.webapps.command. In the Project Explorer,
right-click the Java Resources: src folder and select New → Package.
Enter itso.rad7.webapps.command as the package name and click Finish.
From the context menu of the new package, select Import, then General →
File system. Click Next.
Click Browse and navigate to the folder:
C:\7501code\webapps\itso.rad7.webapps.command
Click OK.
Select the five Java files and click Finish:
Command.java
DepositCommand.java
ListTransactionsCommand.java
TransferCommand.java
WithdrawCommand.java
The command classes perform the operations on the RedBank model classes
(from the RAD7Java project) through the Bank facade. They also return the
file-name for the next screen to be shown after the command has been executed.
In this example, the listAccounts.jsp file is built up using page data variables
for customer and accounts (and array of Account classes for that customer).
These variables are added to the page by the ListAccounts servlet and are
accessible to the Java code and tags used in the JSP.
To complete the body of the listAccounts.jsp file, perform the following steps:
Open the listAccounts.jsp file in Page Designer and select the Design tab.
Add the customer and accounts variables to the page data meta information
in the Page Data View (by default on the bottom left of the window). These
variables are added to the request object in the ListAccounts servlet, as
discussed in “Implementing the ListAccounts servlet” on page 517. Page
Designer needs to be aware of these variables:
Chapter 12. Develop Web applications using JSPs and servlets 521
– In the Page Data view expand Scripting Variables, right-click
requestScope, and select New → Request Scope Variable.
– In the Add Request Scope Variable dialog, enter the following information
and click OK:
• Variable name: customer
• Type: itso.rad7.bank.model.Customer
Tip: You can use the browse-button (marked with an ellipsis) to find
the class using the class browser.
In the Palette view, select Form Tags → Form and click anywhere on the JSP
page in the content table. A dashed box appears on the JSP page,
representing the new form. Resize the box to take up most of the width of the
content area.
In the Properties view for the new Form element, enter the following items:
– Action: UpdateCustomer
– Method: Select Post.
Note that you can use the Outline view to navigate to the form tag quickly.
Add a table with customer information:
– In the Page Data view, expand and select Scripting Variables →
requestScope → customer (itso.rad7.java.model.Customer).
– Select and drag the customer object to the top half of the area inside the
form that was previously created.
– In the Object Type dialog, accept Object and click OK. We could set the
type of the accounts field.
– In the Insert JavaBean dialog (Figure 12-31), do these steps:
• Select Displaying data (read-only).
• Use the arrow up and down buttons to arrange the fields in the order
shown, and overtype the labels.
• Clear the accounts field (we do not display the accounts).
• Click Finish.
Note: The newly created table with customer data is changed in a later
stage to use input fields for the title, first name, and last name fields. At the
time of writing, this was not possible to achieve through the use of the
available wizards.
Right-click the last row of the newly created table (select the LastName cell)
and select Table → Add Row Below.
In the Palette view select Form Tags → Submit Button and click in the
right-hand cell of the new row. Enter Update in the Label field and click OK.
The Name field can be left empty.
In the Palette view, select HTML Tags → Horizontal Rule and click in the
area immediately below the form. Resize the line to be the same size as the
form above it.
In the Page Data view, expand and select Scripting Variables →
requestScope → accounts (itso.rad7.java.model.Account[]).
Select and drag the accounts object to area below the horizontal rule. Click
OK in the Object Type dialog.
Chapter 12. Develop Web applications using JSPs and servlets 523
In the Insert JavaBean wizard (Figure 12-32), do these steps:
– Clear transactions (we do not display the transactions).
– For both fields, select Output link in the Control Type column.
– In the Label field for the accountNumber field, enter Account Number.
– Ensure that the order of the fields is accountNumber and balance.
– Click Finish, and the accounts Bean is added to the page and is displayed
as a list.
The wizard inserts a JSTL c:forEach tag and an HTML table with headings,
as entered in the Insert JavaBean window. Because we selected Output link
as the Control Type for each column, corresponding c:url tags have been
inserted. We now have to edit the URL for these links to make sure they are
identical and to pass the accountId variable as a URl parameter.
– Select the first c:url tag under the heading Account Number, which has
the text ${varAccounts.accountNumber}{}. In the Properties view, enter
AccountDetails in the Value field (Figure 12-33).
– The tag changes to AccountDetails{}.
– Select the second c:url tag: under the heading Balance, which has the
text ${varAccounts.balance}{}. In the Properties view, enter
AccountDetails into the Value field. This specifies the target URL for the
link, which in this case maps to the AccountDetails servlet.
– Now we must add a parameter to this URL, so ensure the link goes to the
correct account. In the Palette view select JSP Tags → Parameter and
and click on the first c:url in the Account Number column. This has the
text AccountDetails{} (Figure 12-34).
– In the Properties view, for the c:param tab, enter accountId in the Name
field and ${varAccounts.accountNumber} in the Value field. This adds a
parameter to the account url with a name of accountId and the value of
the accountNumber request variable.
Chapter 12. Develop Web applications using JSPs and servlets 525
Click here to add parameters to the c:url tags
– Repeat the two previous steps to add a parameter to the second c:url tag
in the Balance column, showing the text Account Number{}. Note the
field values are the same as used in step c, accountId in the Name field
and ${varAccounts.accountNumber} in the Value field.
Click anywhere in the Balance column, and select the td tag in the Properties
view. Select Right in the Horizontal alignment list box. This makes the
contents of the Balance cells right-justified.
Select the Source tab and compare the code to display the accounts to
Example 12-1. This JSP code displays the accounts as a list, using the
c:forEach tag to loop through each account, and the c:out tag to reference
the current loop variable. The c:url tag builds a URL to AccountDetails and
the c:param tag adds the accountId parameter (with account number value)
to that URL.
Example 12-1 JSP code with JSTL tags to display accounts (formatted)
<c:forEach var="varAccounts" items="${requestScope.accounts}">
<tr>
<td>
<c:url value="AccountDetails" var="urlVariable">
<c:param name="accountId"
value="${varAccounts.accountNumber}"></c:param>
</c:url>
<a href="<c:out value='${urlVariable}' />">
<c:out value="${varAccounts.accountNumber}"></c:out>
</a>
</td>
<td align="right">
<c:url value="AccountDetails" var="urlVariable">
In the Palette view, select HTMLTags → Horizontal Rule and click in the area
below the account details table. You might have to increase the size of the
content area.
Add a logout form:
– In the Palette view, select Form Tags → Form and click below the new
horizontal rule. A dashed box will appear on the JSP page, representing
the new form.
– In the Properties view for the new form tag, enter the following items:
• Action: Logout
• Method: Select Post.
– In the Palette view, select Form Tags → Submit Button and click in the
right-hand cell of the new form. When the Logout button is clicked, the
doPost method is called on the Logout servlet.
– In the Insert Submit Button dialog, enter Logout in the Label field and click
OK.
– Click in the space above the form and button (this selects the <td> tag)
and set the Horizontal alignment to Center.
The remaining part is to change the title, first name and last name to be entry
fields, so that the user can update the customer details.
Do the following steps to convert the Title, First Name, and Last Name text
fields to allow text entry:
– Select the ${requestScope.customer.title} field.
– Select the Source tab and you can see the code:
<td><c:out value="${requestScope.customer.title}" /></td>
– Change the code to:
<td><input type="text" name="title"
value="<c:out value='${requestScope.customer.title}' />" /></td>
– Repeat this for the first name and last name fields:
<td><input type="text" name="firstName"
Chapter 12. Develop Web applications using JSPs and servlets 527
value="<c:out value='${requestScope.customer.firstName}' />" /></td>
......
<td><input type="text" name="lastName"
value="<c:out value='${requestScope.customer.lastName}' />" /></td>
This changes the customer fields from display only fields to be editable, so
that the details can be changed.
You can increase the length of the fields.
The width of the content areas can be change in the source code as well.
The balance is a BigDecimal and must formatted, otherwise it displays with
many digits:
– Click on the balance field.
– Select JSP → Insert Custom.
– In the Insert Custom Tag dialog, click Add to add another tag library.
– Locate and select the http://java.sun.com/jsp/jstl/fmt URI and click OK.
– Select the new tag library and select formatNumber as the custom tag
(Figure 12-35). Click Insert and Close.
Chapter 12. Develop Web applications using JSPs and servlets 529
Select all the JSP files except listAccounts.jsp (which has already been
completed). Click Finish.
When prompted whether to override the existing files, click Yes to All.
It is now possible to view the other JSP files in Page Designer. Unfortunately,
these pages will not have the associated request beans showing in the Page
Data view. These are maintained in the .jspPersistence file immediately under
the Web project directory, but have to be specifically added to the PageData View
for Application Developer to be aware of them.
For completeness, you can add the required variables to the appropriate Page
Data view. Open the JSP file and in the Page Data view, select Scripting
Variables → New → Request Scope Variable (Table 12-1).
Form to
perform
transactions
Chapter 12. Develop Web applications using JSPs and servlets 531
Uses account bean to show number/balance
Chapter 12. Develop Web applications using JSPs and servlets 533
Running the sample Web application
To run the RedBank Web application in the test environment, do these steps:
Right-click RAD7BankBasicWeb in the Project Explorer and select
Run As → Run on Server.
In the Server Selection dialog, select Choose an existing server, select
WebSphere Application Server v6.1, and click Finish.
The main page of the Web application should be displayed in a Web browser
inside Application Developer.
Click Submit, and the customer and the accounts are listed (Figure 12-41).
Chapter 12. Develop Web applications using JSPs and servlets 535
123.45
Try a withdraw of an amount greater than the balance. The Show Exception
JSP is displayed with an error message (Figure 12-44).
Chapter 12. Develop Web applications using JSPs and servlets 537
RedBank Web application conclusion
We hope that all of the foregoing demonstrations worked successfully for you.
The example has demonstrated the following features, which are just a subset of
the tools available within Application Developer for Web development:
Basic servlets
Basic JSPs
Page Designer
Page templates
Web Site Navigation editor
CSS editor
JSP tags
New Servlet wizard
New Web Project wizard
Web Library projects
Navigation tabs
JSTL tag library
More information
There are many ways that the RedBank application can be improved, by adding
features or using other technologies. Some of these are covered in subsequent
chapters of this book, including these:
Using EJBs to store the model—Chapter 16, “Develop Web applications
using EJBs” on page 719
Using a database rather than HashMaps—Chapter 9, “Develop database
applications” on page 355
Using Struts to handle the requests—Chapter 13, “Develop Web applications
using Struts” on page 541
Using JSF components rather than JSTL—Chapter 14, “Develop Web
applications using JSF and SDO” on page 587
Debugging the application—Chapter 22, “Debug local and remote
applications” on page 1041
The Help feature provided with Application Developer has a large section on
Developing Web sites and applications. It contains reference information for all
the features presented in this chapter and further information on topics only
covered briefly here, including JSP tag libraries, Security, and use of the Web
Diagram Editor.
Chapter 12. Develop Web applications using JSPs and servlets 539
540 Rational Application Developer V7 Programming Guide
13
The focus of this chapter is on the Application Developer tooling used to develop
Struts-based Web applications. Although we do introduce some basic concepts
of the Struts framework, we recommend that you refer to the following sites for
further in-depth information:
Apache Struts home page:
http://struts.apache.org/
Apache Struts User Guide:
http://struts.apache.org/userGuide/introduction.html
Note: Since the prior version of Application Developer (Version 6.x), Struts
has forked into three distinct frameworks:
Struts Classic (which is the original Struts framework)
Struts 2 (which is Struts + Webwork)
Struts Shale (which is a JSF version of Struts, now known as Shale
Application Developer V7.0 includes support for only Struts Classic. The
versions supported by Application Developer are Struts Version 1.0.2 and 1.1.
At the time of writing this book, the latest version of the Struts Classic
framework was V1.3.8.
Action
: JSP
ActionServlet Action Model
: ActionForm
Action
configuration
Application file Action
Resources
Struts Support
Figure 13-2 shows the basic flow of information for an interaction in a Struts Web
application.
HTTP setXxx()
validate()
execute() getXxx()
setXxx()
"forward"
forward()
getXxx()
A request from a Web browser is first received by the Struts action servlet.
If the action that handles the request has a form bean associated with it,
Struts creates the action form and (and if specified, automatically) populates it
with the data from the input form.
It then calls the validate method of the action form. 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. The action often call session EJBs to perform the business
logic.
When done, the action either creates a new action form (or other appropriate
view bean) or reuses the existing one, populates it with new data, and stores
it in the request (or session) scope.
The action then returns a forward object to the action servlet, which forwards
to the appropriate output JSP (or alternatively forwards to another action).
The JSP uses the data in the action form to render the result.
Note: The Web Diagram in Application Developer, which supports the creation
of various Struts components, can also be applied in the creation of Struts
components when using the IBM Struts Portlet framework.
Specifically, when working with a Portlet project and the project has been
enabled to use the IBM Struts Portlet framework, the same palette options of
the Web Diagram are available to the Portlet project.
Note: A completed version of the ITSO RedBank Web application built using
Struts can be found in the project interchange file:
C:\7501code\zInterchangeFiles\struts\RAD7Struts.zip
If you do not want to develop the sample yourself, but want to see it run, follow
the procedures described in “Importing the final sample application” on
page 585.
The instructions for creating the ITSOBANK database are given in “Setting up the
ITSOBANK database” on page 1312.
In the banking sample, we use the Struts framework for the controller and view
components of the Web application. We implement the model using JavaBeans
and the Derby database (or DB2).
Figure 13-3 displays the Struts Web Diagram for the sample banking application.
The basic description and flow of the banking sample application are as follows:
The logon.jsp page is displayed as the initial page of the banking sample
application. The customer is allowed to enter her or his social security
number. In our case we use simple validation of the Struts framework to check
for an empty value. If the customer does not enter a valid value, the Struts
framework returns to the logon.jsp page and display the appropriate
message to the user.
The logon action logs in the user, and on successful logon retrieves the
customer and the account information and lists all the accounts associated
with the customer using the customerlisting.jsp Web page.
In the customerlisting.jsp, the customer can select to see details of an
account using the accountDetails action, or perform a transaction on an
account using the transact.jsp.
In the accountDetails.jsp, the details of the account are displayed, including
the transactions that have been performed on the account. The customer can
select to perform another transaction using the transact.jsp.
The transact.jsp invokes the performTransaction action. After a successful
transaction the accountDetails action is invoked to redisplay the
accountDetails.jsp.
The customer can log off using the logoff link, which invokes the logoff
action.
In this section we focus on creating the various Struts components, including the
Struts controller, actions, action forms, and Web pages, and relate these
components together. We implement the following steps to demonstrate the
capabilities of Application Developer:
Create a dynamic Web application with Struts support: In this section the
process of creating a dynamic Web application with Struts support and the
wizard generated support for Struts is be described.
Create Struts components: In this section we focus on creating Web pages,
actions, action forms, exceptions (local and global), and forwards using the
Web Diagram, and modify the properties of Struts components using the
Struts Configuration Editor.
Struts Configuration Editor: In this section we focus on creating Struts
components using the Struts Configuration Editor that provides a visual editor
to modify the Struts configuration file struts-config.xml.
After having used the wizards to create some components (JSPs, form beans,
actions), you might find it faster to create new components by copying and
pasting from your existing components than by using all the wizards.
Accept the defaults in the Web Module dialog for Context Root, Content
Directory and Java Source Directory, and click Next.
Accept the defaults in the Struts Settings dialog for Resource Bundle and click
Finish.
Note: At the time of writing, Struts V1.0.2 and 1.1 are the only versions
supported and available from the Struts list box.
At this point, a new dynamic Web project with Struts support (RAD7StrutsWeb)
and an enterprise application project (RAD7StrutsEAR) have been created, and
the Web Diagram Editor is open.
Deployment descriptor
with servlets
Struts artifacts
Web Diagram
Application Resources
Note that we do not build the entire application using the Web Diagram. We just
show examples of building Struts components.
Figure 13-6 Web Diagram with the Struts drawer (Web Parts) open in the Palette
To create and associate the logonForm form bean to the logon action, do these
steps:
Hover with the mouse over the /logon action, then click the Add Form Bean
icon ( ) from the selections presented.
In the Form Bean Selection dialog, do these steps:
– Click New.
– In the New Form Bean dialog, type logonForm as the Form Bean Name
and accept the defaults for the rest. Click Next.
– In the Choose new fields for your ActionForm class dialog, you can select
existing items (from projects) to be generated a field with getter and setter
methods. We do not have existing fields. Click Next.
– In the Create new fields for your ActionForm class dialog, you can add
fields to the action form. Click Add to create a field named ssn of type
string. Click Next.
– In the Create a mapping for your ActionForm class dialog, accept the
defaults for package, modifiers, superclass, and method stubs. Accept the
generated name LogonForm for the ActionForm class name.
– Click Finish.
– The logonForm bean is added to the Form Bean Selection dialog. Click
OK.
When you select Connection from the palette and drag it from a Struts action to
any other node, you are able to create the following:
Local Exception: When Local Exception is selected, the action mapping
entry is modified in the struts-config.xml file. The handler class created
during the creation is invoked when the Struts action throws the local
exception.
In our sample, when a user enters an invalid customer ID (SSN), the logon action
fails and then forwards the user back to the logon page to enable the user to
re-enter this information. Likewise, if the logon action succeeds, the customer
has to be forwarded to the customerListing.jsp that displays the customer’s
account information.
To create the local forwards for success and failures for the logon action, do
these steps:
Create a connection from the logon.jsp to the logon action. Click
Connection in the Palette, select logon.jsp, and drag the connection to the
logon action. Select Struts Form when prompted.
This is done to indicate that the action that is to be invoked when the form is
submitted is logon.
Create an Action Input that is used by the Struts validation framework for
validating the form data in logon.jsp to redirect the user back to the
logon.jsp page.
Select Connection in the Palette, select the logon action, and drag it to the
logon.jsp. Select Action Input when prompted.
Create a local forward back to logon.jsp. This is used to forward the user
back to the logon page when business exceptions occur in the logon action.
– Create a connection from the logon action to the logon.jsp.
– Select Local Forward when prompted.
– Rename the generated forward named success to failure.
Tip: You can select a component in the Web diagram and overtype the name
and the forward names.
To improve the layout of the application flow, you can drag components to
another spot. You can rearrange connections by dragging their middle point.
Struts Form Beans Creating a new form bean from within an action creates a
new form bean class. In addition, it also updates the
struts-config.xml file with a form bean mapping and form
bean to action association.
Struts Actions Dragging a new action onto the palette creates a new
action class. In addition, it also updates the
struts-config.xml with an action mapping.
JSP Dragging a Web page onto the palette creates a new Web
page JSP.
While developing Struts applications, you usually find yourself having this file
open, because you typically add messages to it as you go along writing your
code. Again, this properties file is meant to externalize messages and more
importantly support i18n. Example 13-1 shows a completed
ApplicationResources.properties file.
form.ssn=SSN
form.accountId=Account Id
form.balance=Balance
form.amount=Amount
form.accountDetails.transactionId=Transaction ID
form.accountDetails.transactionType=Transaction Type
form.accountDetails.transactionTime=Transaction Date-Time
form.accountDetails.transactionAmount=Transaction Amount
Initially this file only contains optional header and footer for errors. At this point
you can open the file and add two lines:
form.ssn=SSN
errors.required={0} is a required field.
To validate the logonForm using the Struts validation framework, do these steps:
We have provided a validation.xml and validation-rules.xml as part of
the sample code.
Import the validation.xml and validator-rules.xml from the
C:\7501code\struts\WebContent\WEB-INF directory into the
RAD7StrutsWeb\WebContent\WEB-INF directory of the workspace.
Add the Struts validator plug-in and required property to the plug-in indicating
the location of the validation configuration files.
– Expand RAD7StrutsWeb → WebContent → WEB-INF.
– Open the struts-config.xml file in the Struts Configuration Editor.
– Select the Plug-ins tab in the Struts Configuration Editor.
The validation.xml file contains all the Struts form beans and the fields within
the form bean that is validated, and the rule that is applied to validate the bean.
The snippet that validates the logonForm is shown in Example 13-2.
The validator-rules.xml file contains the rule configurations for all the rules
defined in the validation.xml file. In our example above, the rule that is defined
is required for the field ssn, as shown in Example 13-2. The snippet for the
required rule is shown in Example 13-3.
Example 13-3 validator-rules.xml snippet - Rule configuration for the required rule
<form-validation>
<global>
<validator name="required"
classname="org.apache.struts.validator.FieldChecks"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg="errors.required" />
</global>
</form-validation>
Open the logon.jsp to see the Palette in Page Designer (Figure 13-11):
Struts HTML tags: Struts provides tags to render HTML content. Examples
of the Struts HTML tags are button, cancel, checkbox, form, errors, etc. These
tags can be dragged and dropped into a page in the page designer’s design
perspective. We drag and drop the errors tag to the logon.jsp and display a
message to the user if no ssn is entered later on in this section.
Struts Bean tags: The bean tag library provides tags to access bean
properties, request parameters, create page attributes, and so forth.
Struts Logic tags: The Logic tag library provides tags to implement
conditional, looping, and control related functionality.
Struts Nested tags: The Nested tag library provides tags to access complex
beans with nested structures.
Struts Template tags: The Template tag library provides tags for creation of
dynamic JSP templates.
Struts Tiles Tags: The Tiles tag library facilitates development of dynamic
Web applications in a tiled fashion where the tile can be reused throughout
the application.
Tip: If you do not see all the Struts tag libraries in the palette, right-click the
palette and select Customize. From the Customize Palette dialog box, select
all drawers you want to have available in the palette. Note that you must be in
the process of editting a JSP in order to see the Struts tag libraries options.
Figure 13-12 Struts tags: Struts errors tag rendered by Page Designer
The source for the rendered logon.jsp is shown in the Example 13-4. Notice
the <html:errors /> and the form that the wizard has added for rendering the
action form.
Example 13-4 Struts tags:- Logon.jsp snippet of the tag in the source view
......
<html:errors />
<html:form action="/logon">
<TABLE>
<TBODY>
<TR>
<TD align="left">Customer ID:</TD>
<TD width="5"> </TD>
<TD><html:text property="ssn"></html:text></TD>
</TR>
<TR>
<TD align="left"><html:submit property="Submit"
value="Submit"></html:submit></TD>
<TD width="5"> </TD>
<TD><html:reset /></TD>
</TR>
</TBODY>
</TABLE>
</html:form>
......
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
try {
CustomerBean customerBean = new DatabaseAccess().getCustomer(ssn);
request.setAttribute("customer", customerBean);
request.getSession().setAttribute("ssn", logonForm.getSsn());
Helper classes
The action methods are supported by helper classes provided in:
C:\7501code\struts\bank\beans
C:\7501code\struts\bank\database
JavaBean data transfer objects: CustomerBean, AccountBean, and
TransactionBean (rad7strutsweb.beans package). These classes are simple
Java beans with a few properties.
Database retrieve and update: DatabaseAccess and DataSourceFactory
(rad7strutsweb.database package). The DatabaseAccess class provides
methods to retrieve the customer with accounts and an account with
transactions, and to update the account balance and create a transaction
record.
For example, to retrieve the customer with accounts for the logon action:
– A data source connection to the database is created using the
DataSourceFactory utility class. This factory can be used by all actions.
– The SQL statement (CUSTOMER_STMT) is executed to retrieve customer and
account information using a join.
– The result set is retrieved. Customer information is stored in the
CustomerBean and account information is stored in an accountList (of
AccountBean objects), which is then added to the CustomerBean.
– An exception is thrown if the customer is not found or if any other SQL
exception occurs.
We use this editor to add a local forward called cancel to the logon action. This
forward can be used by the logon action’s execute method to forward the user to
the logon.jsp page, as we map this forward to the logon.jsp page.
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 or the
Struts validation framework fails to validate. Usually you want to display the input
page where the user entered the data so they can correct their entry.
Open the struts-config.xml file under RAD7StrutsWeb → WebContent →
WEB-INF.
The editor has tabs at the bottom of the screen to navigate between the
different Struts artifacts it supports.
– In the Action Mappings tab select the /logon action. You can see the
logonForm (Form Bean Name) and the logon.jsp (Input).
– Notice the Scope value of request; an alternative would be session.
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 (or send 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.
You can also redirect or forward to other actions. It does not necessarily
have to be a JSP.
As you can see, the Application Developer Struts tools have defined the
logonForm bean in the <form-beans> section and the logon action in the
Notes: We recommend 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.
Figure 13-17 Web Diagram action with and without the action form
666-66-6666
If you click Submit without entering an ID, the Struts Validation Framework is
activated and displays the error message added to the resources:
Verify that the customer ssn is entered correct
Enter a sample ID of 666-66-6666 and click Submit. The customer and a list
of accounts is displayed (Figure 13-19). Here the logon action is responsible
for retrieving this information. In a real world application, the logon action talks
to the business tier to retrieve this information. The business tier architecture
is described in detail in Chapter 16, “Develop Web applications using EJBs”
on page 719.
The Account Details page is redisplayed with an entry made for the last
transaction (Figure 13-22).
Run a few more transactions and the list of transaction grows (Figure 13-23).
Application Developer now provides support for Tiles framework. However, the
support for Tiles is rather minimal. Nevertheless, we are going to show the extent
of Tiles support.
There is also another piece of configuration that you have to put in manually. In
the struts-config.xml, after the Action Mappings section, insert the line shown
in Example 13-9.
For each action, create a local forward by selecting the action and Add Link →
Local Forward (or use the arrow icon when hovering over the action). Accept the
default local forward name of success (Figure 13-24).
For /contactUs, have the path of the success local forward point to
contactUs.config, and for /aboutUs to aboutUs.config.:
The path value can be set in the Properties view, Forward Config tab, when
selecting the success local forward (Figure 13-25).
Add two connections from customerListing.jsp to the two actions, and select
Struts Link when prompted.
Delete the <div> section after copying the links into the HTML table.
Tiles recapitulation
We have created and/or imported the necessary components. In essence, we
have created two action classes which each (when executed successfully)
forwards to a Tiles configuration. The Tiles configuration contains information on
how the eventual page should render. The actual page is constructed at runtime.
More information
For more information about Struts and Tiles, consult these Web sites:
Apache Struts home page:
http://struts.apache.org/
Apache Struts User Guide:
http://struts.apache.org/userGuide/introduction.html
Apache Tiles home page:
http://tiles.apache.org/
IBM developerWorks (search for Struts and Tiles):
http://www.ibm.com/developerworks/
This chapter introduces the features, benefits, and architecture of JSF and SDO.
The focus of the chapter is to demonstrate the Rational Application Developer
support and tooling for JSF. We also discuss the new feature Asynchronous
JavaScript and XML (AJAX) for developing JSF applications. The chapter
includes an example Web application using JSF, SDO, and AJAX.
The focus of this section is to highlight the JSF application architecture depicted
in Figure 14-1.
Component
Tree JSF Libraries/Tags
Validators
Events
Business
Logic
Other Modules (EJB)
Chapter 14. Develop Web applications using JSF and SDO 589
Faces JSP pages are built from JSF components, where each component is
represented by a server-side class.
Faces servlet: One servlet (FacesServlet) controls the execution flow.
Configuration file: An XML file (faces-config.xml) that contains the
navigation rules between the JSPs, validators, and managed beans.
Tag libraries: The JSF components are implemented in tag libraries.
Validators: Java classes to validate the content of JSF components, for
example, to validate user input.
Managed beans: JavaBeans defined in the configuration file to hold the data
from JSF components. Managed beans represent the data model and are
passed between business logic and user interface. JSF moves the data
between managed beans and user interface components.
Events: Java code executed in the server for events (for example, a push
button). Event handling is used to pass managed beans to business logic.
JSF stylesheet
Application Developer includes the following support and tooling for JSF Web
application development:
Visual page layout of JSF components using Page Designer
Web Diagram Editor for defining the flow of a JSF application
Built-in Component Property editor
Built-in tools to simplify and automate event handling
Page navigation defined declaratively
Automatic code generation for data validation, formatting, and CRUD
functions for data access
Multiple faces configuration file support for different purposes, such as
navigation and managed beans
Relational database support
EJB support
Web services support
Data abstraction objects for easy data connectivity (Service Data Objects)
Data objects can be bound easily to user interface components
Support for runtime page templates with Tiles
Asynchronous JavaScript and XML (AJAX) support
Application Developer v7.0 has now additional rich and powerful components for
JSF. These components include:
Menu Bar: Displays a (hierarchical) menu bar of buttons and/or hyperlinks.
Panel - Dialog: Creates a block panel that behaves like a modal or modeless
dialog box. The panel floats above the main page, displays an appropriate title
bar, can be moved, and normally has a pair of OK and Cancel buttons.
Panel - Form Box: Creates a block panel that contains a header area and
one or more form items (label/field pairs).
Panel - Section: Creates a block panel that has a header that can be used to
expand/collapse the display of the panel's content.
Select - Color: Displays a drop-down combo box from which the user
chooses a color.
Chapter 14. Develop Web applications using JSF and SDO 591
Select - Calendar: Adds small calendar to the page. A user can select a date
by clicking a day in the calendar.
Progress Bar: Displays an animated progress bar.
Link - Request: Generates an HTML link with a URL that can pass
parameters and navigate to a page by passing a string to JSF navigation
rules via a string returned from a JSF action or static action string.
Data Iterator: Iterates over rows of model data allowing values from each row
to be used in child components. For each row of data available, a set of child
components are rendered. The iterator tag itself does not have any control
over what is rendered, it just provides data to child components.
Improved Quick Edit view: Quick Edit view lets you add short scripts to your
HTML and JSP files. The view now supports a library of pre-defined
JavaScript functions on JSF components (Figure 14-6).
Chapter 14. Develop Web applications using JSF and SDO 593
Figure 14-6 Improved Quick Edit view
The Java specification request is JSR 235 for Service Data Objects (SDO) and
can be found at:
http://www.jcp.org/en/jsr/detail?id=235
Note: For more detailed information on JavaServer Faces and Service Data
Objects, we recommend the following Redbooks publication:
WebSphere Studio 5.1.2 JavaServer Faces and Service Data Objects,
SG24-6361
AJAX tags for JSF components are added as child tags of any of the panel tags.
Their content defines an alternative content for the panel. When an action is
triggered, a request is made back to the server for the new content to put in the
panel. The server computes the new content, returns the content to the client
where it is plugged into the panel, replacing its existing content.
Chapter 14. Develop Web applications using JSF and SDO 595
Application Developer v7.0 AJAX components include these:
inputTypeAhead: Extended input text component to support type ahead
functionality.
ajaxRefreshRequest: Defines how content from the same JSF page
replaces the existing content of the parent tag. Content is received using an
HTTP get request.
ajaxRefreshSubmit: Defines how content from the same JSF page replaces
the existing content of the parent tag. Content is received using an HTTP
submit request.
ajaxExternalRequest: Defines how content from a different page replaces
the content of the parent tag. Content is retrieved using an HTTP get request
against an arbitrary data source.
Note: A completed version of the Web application built using JSF and SDO
can be found in the c:\7501code\zInterchangeFiles\jsfsdo\RAD7JSF.zip
project interchange file. If you do not wish to create the sample yourself, but
want to see it run, follow the procedures described in “Running the sample
Web application” on page 647.
In the Project Facets dialog, accept the default (Figure 14-9), and click Next.
Enhanced Faces
components enables
the IBM extensions.
Chapter 14. Develop Web applications using JSF and SDO 597
Tip: Project facets features can also be added to a project later using the
Project Facets panel of the project Properties dialog.
In the Web Module dialog, accept the defaults and click Finish.
After creating the JSF application, the Web Diagram Editor automatically opens
for creating Web resources, designing page flow, and adding data to pages
(Figure 14-10).
The Web Diagram provides a visual way for you to create and manage the flow of
a Web application. The Web Diagram Editor helps you visualize and structure the
user interface of a Web application. You can create Web pages, add actions and
mappings (such as inputs and outputs), add page data, and so on. In many
cases, these items can be created for you automatically. Consider the Web
Diagram as a way to create the logical flow and the basic user interface of a Web
application.
While developing JSF and SDO Web applications with Application Developer
v7.0, the data source is created automatically when you add an SDO Relational
Record or SDO Relational Record List to a Faces JSP file. The data source
configuration is added to the Deployment tab of the EAR deployment descriptor.
You can also use the data source configured in the server, as described in
“Configuring the data source in WebSphere Application Server” on page 1313.
Chapter 14. Develop Web applications using JSF and SDO 599
the Web server at run-time. You can insert JSP fragments and configure the
content areas of your template when you edit the template in Page Designer.
In our sample Web application we use a dynamic page template.
In the Project Explorer view (Figure 14-13), there are some files added to the
Java Resources folder, which contains the generated managed bean classes.
The PageCodeBase.java class file is a super class for all the generated managed
bean classes. A RAD7JSFTemplate.java class is created as the managed bean for
the template page. Each JSF page has its own managed bean class generated.
Chapter 14. Develop Web applications using JSF and SDO 601
Views for editing page template files
There are many views and tools that can be used when editing page templates.
This section highlights some views that we found helpful for editing a page
template.
Note: This section is not required for the working example. To continue with
the working example, skip to “Customizing the page template” on page 607.
Page Designer
The Page Designer is the main editor pane and is composed of three tabs:
Design, Source, and Preview:
Design tab (Figure 14-14): The Design tab is the main GUI editor that allows
you to select the components on the page in a graphical manner. It also gives
you a good representation of the resulting page. Also, you notice in the top
right of Figure 14-14 that there are some drop-down options; these options
allow you to select the layout mode, select an existing component on the
page, and select font options for presentation, respectively. If you right-click
the Design editor, the context menu allows you to be able to insert a variety of
components, as well as edit embedded documents.
Source tab (Figure 14-15): The Source tab allows you to view the page
template source. This tab allows you to tweak the template by changing the
source directly. If you right-click in the source editor, you have the option to
clean up the document, format the source, and refactor components:
– The Cleanup option allows you to change the casing of HTML tags and
attributes. It also gives you the ability to clean up tags with missing
attributes, place quotes around attributes, insert missing tags, and format
the source.
Preview tab (Figure 14-16): The Preview tab allows you to preview the
resulting JSF page template. It presents the page template as it would appear
in a browser. Notice in the top right corner that there are buttons similar to the
navigation buttons in a browser. They allow you to go to the previous page,
next page, or reload the page.
Palette view
This view allows you to select palettes to work with. Examples of palettes in the
Palette view can be seen in Figure 14-17. Palettes contain the reusable
components that can be dragged on to the page to be added to a file.
Chapter 14. Develop Web applications using JSF and SDO 603
Figure 14-17 Palette view
The palettes that are available for page template files include:
HTML Tags: This palette contains common HTML tags such as images, lists,
tables, links, and so on.
Form Tags: This palette contains common Form tags such as form, submit
button, reset button, radio button, text box, and so on.
JSP Tags: This palette contains common JSP tags such as beans,
expressions, scriptlets, declarations, include directives, as well as some
logical tags such as if, when, otherwise, and so on.
Crystal Report Faces Components: This palette contains Crystal Report
Faces Components. You can drag these reusable Crystal Report
Components to be used on the page template.
The Palette view can be customized to hide and display palettes that you want to
use. The palettes listed above are the default palettes presented when editing a
page template with JSF and SDO components. Other palettes that can be
included are Portlet, Struts, and Server Side Include (SSI) directives.
Expand a palette
to show/hide the
components of
the palette
Chapter 14. Develop Web applications using JSF and SDO 605
The Customize Palette dialog allows you to hide and show palettes, as well as
reorganize the order in which they appear. Clear Hide for each palette that you
want to display on the palette. Notice that in the dialog, the hidden palettes are a
lighter shade of gray.
Some palettes contain more components that can fit on the screen and arrows
allow you to scroll up and down. Also, you can pin open frequently used palettes
to stop them from being closed when you open other palettes.
Properties view
The Properties view allows you to define the most common set of attributes of a
selected component, and you can also see options for adding controls, actions,
or other components. The Properties view shown in Figure 14-19 shows the
properties of the body tag. Notice the highlighted button on the top right, which
allows you to view all the attributes of the tag in tabular format.
You can add these data objects using the highlighted New button on the Page
Data toolbar or by right-clicking on the view. An appropriate wizard opens,
depending on the type of object selected.
Chapter 14. Develop Web applications using JSF and SDO 607
Tip: You can also navigate to the itso_logo.gif in Windows Explorer and
drag it into the theme folder in the Project Explorer of Application Developer.
You should now see a box on your page with the text box1: Drag and Drop
Items from the palette to this area to populate this region.
From the Enhanced Faces Components palette, select Image and
click into the box. After adding the image, the page is shown in Figure 14-22.
Figure 14-22 Page template after adding an image to Panel - Group box
Select the image on the page and update the image values in the Properties
view. Enter headerImage in the Id field and theme/itso_logo.gif in the File
field (Figure 14-23).
Figure 14-24 Page design after adding image and title to the template
Chapter 14. Develop Web applications using JSF and SDO 609
Figure 14-25 Style dialog used to configure the style of the selected components
To add the content area to the page template, do these steps (Figure 14-26):
Right-click under the Output box (ITSO RedBank) and from the context menu,
select Insert → Horizontal Rule.
Expand Page Template in the Palette view.
From the Page Template, select the Content Area and drag it
under the horizontal rule. In the Insert Content Area for Page Template dialog
accept the default name (bodyarea) and click OK.
You should now see the text Content area “bodyarea” filled by Web pages on
the page.
Right-click under the content area and from the context menu, select
Insert → Horizontal Rule.
Save and close the page template file.
Chapter 14. Develop Web applications using JSF and SDO 611
Figure 14-27 Create a new Web Page
Note that is the template you created in the previous steps. You can see the
preview of the selected template in the preview pane.
In the Web Page Selection dialog, select the RAD7JSFLogin.jsp and click
Finish.
A realized node is shown in the diagram (Figure 14-29).
In a Web Diagram, realized and unrealized nodes are shown differently. Realized
nodes have color and black title text. Unrealized nodes are gray and have gray
title text. In our sample, the RAD7JSFLogin page is realized.
Tip: If you want to create the associated resource later, press Shift+Enter
after you drag Web Page onto the page, otherwise the underlying
resource is created automatically.
Repeat the process to create Web pages for the other two JSF pages
(Figure 14-30):
– RAD7JSFCustomerDetails.jsp—Customer details and account overview
– RAD7JSFAccountDetails.jsp—Account details with transactions
Notice that all three pages are realized (black title). Save the Web Diagram.
Chapter 14. Develop Web applications using JSF and SDO 613
Create connections between Faces JSP pages
Now that the pages have been created, we can create connections between the
pages using the Web Diagram Editor.
Connection handle
In the New Faces Action dialog, enter logout in the Managed bean name and
logout in the Action method field. Click New to create a new Managed bean
class (Figure 14-34).
Chapter 14. Develop Web applications using JSF and SDO 615
Figure 14-34 Create new Faces Action
The new action class (LogoutAction) is displayed in the editor. Modify the
source code to match Example 14-1.
Note: The Java code for the LogoutAction class can be copied from the file
c:\7501code\jsfsdo\Logout.jpage.
import java.util.Map;
import javax.faces.context.FacesContext;
Chapter 14. Develop Web applications using JSF and SDO 617
The Web Diagram should now look similar to Figure 14-37.
Most functions in the Web Diagram Editor are available from the context-menu.
To access any of these functions, right-click in the diagram and select an item
from the menu (Figure 14-39).
Grid, Rulers
Chapter 14. Develop Web applications using JSF and SDO 619
Editing the Faces JSP pages
This section demonstrates the JSF editing features in Application Developer by
using the JSF pages created in “Create Faces JSP pages using the Web
Diagram Editor” on page 611.
Chapter 14. Develop Web applications using JSF and SDO 621
Add a variable for the SSN
When a page has a field where text is entered, the input can be stored. This is
accomplished by creating a session scope variable to store the entered value
and bind it with an input field.
Chapter 14. Develop Web applications using JSF and SDO 623
To add simple validation to an input field, do these steps:
Select the Input component in the Design view.
In the Properties view for the input component, select the Validation tab.
Enter the following items in the Validation tab (Figure 14-46):
– Select Value is required.
– Select Display validation error message in an error message control.
When you select this checkbox an error message component is added
next to the Input box.
– Enter 11 in the Minimum and Maximum length fields.
Select the Error Message for ssn component in the Design view.
In the Properties view, for Style: Props enter color: red. (You could also click
the Style icon and select Red for the Color field.
Do the same for the {Error Messages} field (color: red).
After adding simple validation for the input component, the login page is shown in
Figure 14-47.
Chapter 14. Develop Web applications using JSF and SDO 625
We have to compare the customer SSN to the values in the database. We do so
by creating an SDO object to retrieve the records from the database.
– Enter the user ID itso (we are using the ITSO schema), leave the password
empty, and click Next.
Important: In this step you have to ensure that itso is used as the user ID to
connect to the Derby database. Derby considers any non-qualified reference
to be in the current user’s schema. You must specify a Derby user that has a
schema in the Derby database you are accessing.
Chapter 14. Develop Web applications using JSF and SDO 627
– Select the ITSO schema and click Finish (Figure 14-51).
The Record Properties page is populated with the database tables. Select the
ITSO.CUSTOMER table, and click Next (Figure 14-52).
Chapter 14. Develop Web applications using JSF and SDO 629
Figure 14-55 SDO record: Editing a filter condition
As a result of creating the relational record list, several files were generated. The
/WebContent/WEB-INF/wdo/customer.xml file is of most interest to us in that it
contains the configuration details entered in the wizard.
<?xml version="1.0" encoding="UTF-8"?>
<com.ibm.websphere.sdo.mediator.jdbc.metadata:Metadata xmi:version="2.0"
xmlns:xmi="http://www.omg.org/XMI"
xmlns:com.ibm.websphere.sdo.mediator.jdbc.metadata=
"http:///com/ibm/websphere/sdo/mediator/jdbc/metadata.ecore"
rootTable="//@tables.0">
<tables schemaName="ITSO" name="CUSTOMER">
<primaryKey columns="//@tables.0/@columns.0"/>
<columns name="SSN" type="4"/>
<columns name="TITLE" type="4" nullable="true"/>
<columns name="FIRSTNAME" type="4" nullable="true"/>
<columns name="LASTNAME" type="4" nullable="true"/>
<filter predicate="( SSN = ? )">
<filterArguments name="sessionScopeSSN" type="4"/>
</filter>
</tables>
</com.ibm.websphere.sdo.mediator.jdbc.metadata:Metadata>
Chapter 14. Develop Web applications using JSF and SDO 631
doCustomerDeleteAction—Delete a customer record
getCustomerParameters—Get the parameters for retrieve
getCustomerMediator—Get the mediator that handles all database access
doCustomerCreateAction—Insert a customer
doCustomerFetchAction—Fetch a customer record
getCustomer—Retrieve a customer (calls doCustomerFetchAction)
The simplest way to use these methods is by calling getCustomer, which invokes
the other methods required to perform the action.
Alternative:
Binding the Enter button to the login method replaces the static navigation that
we used before. The action attribute (Properties view or Source tab) now has the
value:
action="#{pc_RAD7JSFLoginFragment.login}"
Tip: Select the Enter button and select the Quick Edit view (behind the
Properties view). You can see the code of the login method. You can also edit
the method code in the Quick Edit view if there is not too much code.
Now we have bound the command button (Enter) to run the login method,
which retrieves the customer from the database using the SDO relational record.
The method verifies that one customer record is retrieved, and issues an error
message otherwise. The login method returns login if a customer is found, and
failed otherwise. The login outcome is linked to a navigation rule, that invokes
the customer details screen.
This section describes how to edit the other pages of the sample application by
using JSF and SDO.
Chapter 14. Develop Web applications using JSF and SDO 633
Prepare the content area
To prepare the content area, do these steps:
Open the RAD7JSFCustomerDetails.jsp in the editor.
In the Dynamic Page Template pop-up click Yes to configure the content area.
In the Configure Content Areas of Dynamic Page template dialog, do these
steps:
– Highlight bodyarea from the content area list.
– Select New or existing fragment file and enter
RAD7JSFCustomerDetailsFragment.jsp in the Name field.
– Click OK.
The fragment file (RAD7JSFCustomerDetailsFragment.jsp) is created under
WebContent/tilesContent directory and included in the actual
RAD7JSFCustomerDetails.jsp. Now you can design the page.
Close the RAD7JSFCustomerDetails.jsp and open the
RAD7JSFCustomerDetailsFragment.jsp.
Select the default text Place RAD7JSFCustomerDetailsFragment.jsp's
content here and Delete.
Chapter 14. Develop Web applications using JSF and SDO 635
Figure 14-60 Insert Record wizard
Click Options and In the Options dialog, clear Delete button, enter Update
in the Label field for the Submit button, and click OK (Figure 14-61).
The customer details can now be displayed in the Web page, with the input fields
available to update the data (Figure 14-62).
Select the Update button and study the code in the Quick Edit view. The button is
linked automatically to the doCustomerUpdateAction method. This is also visible
in the Properties view after clicking the All Attributes icon.
To add the relational record list for the accounts, do these steps:
In the Page Data view, right-click Relational Record and select New →
Relational Record List.
Note: You can also select the Relational Record List in the Data drawer
of the Palette and drag it into the JSF fragment in Page Designer.
In the Add Relational Record List dialog, enter accounts in the Name field
and click Next.
Select the ITSO.ACCOUNTS_CUSTOMERS table and click Next.
Click the Filter results under the Tasks on the right of the dialog.
In the Filters dialog, click the icon and add a condition to retrieve by SSN:
– Select the CUSTOMERS_SSN from the Column drop-down list.
– Select Variable and click the icon to the right of Value.
– In the Select Page Data Object dialog, select sessionScope → SSN and
click OK.
– In the Conditions dialog, click OK.
– In the Filters dialog, click Close.
In the Add Relational Record List dialog, click Add another database table
through a relationship under Advanced tasks.
– In the Choose Your Relationship dialog, select Create an existing
relationship from the database.
Chapter 14. Develop Web applications using JSF and SDO 637
– Select the ITSO.ACCOUNTS_CUSTOMERS → ITSO.ACCOUNT
relationship and click Next (Figure 14-63).
Figure 14-66 Page Data view with customer record and accounts record list
In the Insert Record List - Configure Data Control dialog (Figure 14-67):
– Clear ACCOUNTS_ID and CUSTOMERS_SSN.
– Change the label for ACCOUNT.ID to Account.
– Click Finish.
Chapter 14. Develop Web applications using JSF and SDO 639
Figure 14-67 Insert Record List
Figure 14-68 Design view with the table for customer accounts
Our sample data has only three accounts per customer, so we arbitrarily set the
number of rows to two (not very realistic).
This action creates a pager with arrow controls for first, back, forward, and last,
and a text indicating Page n of nn.
By default, the pager is created in the data table footer (Figure 14-70). You can
reposition the pager by dragging it into the header or into one of the columns.
Chapter 14. Develop Web applications using JSF and SDO 641
Figure 14-70 Data table with deluxe pager
You can also change the design of deluxe pager by changing the attributes of the
deluxe pager component:
Select the deluxe pager component from the Design view.
In the Properties view, select Hide “First” and “Last” buttons and Hide
disabled button (Figure 14-71).
Now first and last buttons are hidden from the deluxe pager in the Design view.
Select the row action added in the Design view, and in the Properties view,
click Switch to QuickEdit View (Figure 14-73).
In the Quick Edit view, read the code in comments, and replace the return
statement with the code from Example 14-3, which is available in:
c:\7501code\jsfsdo\CustomerDetailRowAction.jpage
Chapter 14. Develop Web applications using JSF and SDO 643
This action code retrieves the index of the selected row, then gets the account
ID, and stores the ID in session scope for the next page.
Create a session scope variable named accountId, which is used by the
code that is added for row action:
– In the Page Data view, right-click Scripting Variables and select New →
Session Scope Variable.
– In the Add Session Scope Variable dialog, enter accountId as name and
java.lang.String as type.
Chapter 14. Develop Web applications using JSF and SDO 645
Select the button, and in the Quick Edit view, click into the code and change
the return statement to return "customerDetails"; to produce the required
outcome for the navigation rule.
Add the reusable logout Java Bean getter method as we did in the previous
section (right-click logout(...) and select Add Getter to Page Code).
Add a Logout command button and bind the logout action to the command
button (drag logout(itso...) → logout from the Page Data view onto the
button).
Add a row to the account information table containing the customer SSN:
– Place the cursor in the Id: cell
– Right-click and select Table → Add Row Below.
– Enter SSN: in the left-most cell of the new row.
– Drag an Output component from the Palette into the right cell of the new
row.
– Drag the SSN session variable on top of the output component.
Chapter 14. Develop Web applications using JSF and SDO 647
You also must have set up the ITSOBANK database as described in “Setting up
the sample database” on page 598.
Preparation
SDO generated a data source for the ITSOBANK database with the JNDI name
jdbc/ITSOBANK. For other chapters we already defined a data source in the
server with the JNDI name of jdbc/itsobank. This can lead to conflicts.
Chapter 14. Develop Web applications using JSF and SDO 649
Note: The formatting of
the balance could be
improved. Unfortunately
the database was
designed with an integer
column to store the
balance in cents.
Change the fields to update customer information. This verifies write access
to the database using SDO. For example, change the Title to Miss and click
Update.
Click one of the accounts (002-999000777) to display the account information
with the transactions, resulting in the page displayed in Figure 14-78.
– Note that the error messages are duplicated in the error message field of
the input field and in the error message field of the page. We could
certainly eliminate one of the two message fields.
– Type 222-22-2221 and click Enter. You receive an error message saying
Customer record not found. Note that this action displays error trace
information in the Console view:
[...] 00000022 SystemOut O org.eclipse.emf.common.util.
BasicEList$BasicIndexOutOfBoundsException: index=0, size=0
at org.eclipse.emf.common.util.BasicEList.get(BasicEList.java:511)
at pagecode.tilesContent.RAD7JSFLoginFragment.doCustomerFetchAction
(RAD7JSFLoginFragment.java:233)
at pagecode.tilesContent.RAD7JSFLoginFragment.getCustomer
(RAD7JSFLoginFragment.java:260)
at pagecode.tilesContent.RAD7JSFLoginFragment.login
(RAD7JSFLoginFragment.java:269)
– Leave the SSN empty and click Enter. You get an error that the value is
required.
You can enter other SSN values, however, only 222-22-2222 and
000-00-0000 (and maybe 111-11-1111 from the database chapter) have
transactions associated with the accounts.
Chapter 14. Develop Web applications using JSF and SDO 651
Adding AJAX behavior to the sample Web application
In the section we use the AJAX support of Application Developer to enhance the
application.
Chapter 14. Develop Web applications using JSF and SDO 653
}
return ssnSuggestions;
}}
#{ssnSuggestions)
In the Select Page Data Object dialog, click New Data Object (Figure 14-83).
– In the New Data Component dialog, select Page Bean → JavaBean and
click OK.
– In the Add JavaBean dialog:
• Enter ssnSuggestions for the Name.
• Locate the CustomerSsnSuggestions class.
• Select Make this JavaBean reusable.
• Select session scope.
• Click Finish.
– In the Select Page Data Object dialog, select ssnSuggestions and click
OK.
Chapter 14. Develop Web applications using JSF and SDO 655
Figure 14-85 page Data view with suggestions bean
Whenever an action is triggered (for example, a button click), the client requests
the alternative content for the panel and it replaces the existing panel content
with new content. The page containing the panel is not replaced by the get,
instead, this tag allows part of the page to be replaced. The revised content is
retrieved from the same JSP from which the original content came.
Both the server life cycle copy of the page and the client-side page are kept in
sync. The new page content is retrieved using a post HTTP request operation.
The contents of the form containing the panel are posted as part of the request
so that the values in the form are available to the server code calculating the new
content to put in the panel.
Chapter 14. Develop Web applications using JSF and SDO 657
Figure 14-86 Properties view of the combo box
if (sessionScope.containsKey(CUSTOMERSSN_KEY)) {
getAllCustomers();
Iterator iter = allCustomers.iterator();
while (iter.hasNext()) {
DataObject element = (DataObject) iter.next();
if (element.getString("SSN")
.equals(sessionScope.get(CUSTOMERSSN_KEY))) {
name = "Hello " + element.getString("FIRSTNAME") + " "
+ element.getString("LASTNAME") + "! Click Submit to login...";
}
}
The output component is now bound to the getName method to display the name
of the selected customer (Figure 14-87).
Chapter 14. Develop Web applications using JSF and SDO 659
Add AJAX behavior to the combo-box
To add AJAX behavior to the combo-box, do these steps:
Select the combo-box component in the Design view.
Select the Quick Edit view (Figure 14-89:
– Select onchange in the left pane. Select Use pre-defined behavior and
click the button.
– In the Configure multiple Action/Target pairs dialog, select Invoke Ajax
behavior on the specified tag for the Action field and box1 for the Target.
Click OK.
In the Quick Edit view, select Command on the left side (preselected), and
click into the code section. Replace the return statement with:
return "customerDetails";
Save and close the RAD7JSFLoginAJAXFragment.jsp.
Chapter 14. Develop Web applications using JSF and SDO 661
Test the AJAX enabled login page
To test the new login page with AJAX refresh, do these steps:
Right-click RAD7JSFLoginAJAX.jsp, and select Run As → Run on Server.
The new AJAX enabled login page is displayed (Figure 14-92).
Select a customer SSN from the combo-box and the name is returned from
server without refreshing the page.
Possible improvements
The performance could be improved in a number of ways:
Retrieve only SSNs in the allCustomers relational record list.
Use a relational record to retrieve the name of the customer (reuse the
customer relational record for that purpose).
Store the customer names in session data for faster retrieval.
Chapter 14. Develop Web applications using JSF and SDO 663
664 Rational Application Developer V7 Programming Guide
15
The primary justification for the use of EGL (the basic value proposition of
EGL), is programmer productivity; EGL is easier to learn, use, and maintain
than C/C++, Java/J2SE, or Java/J2EE, for example. EGL is built for the business
application developer, with many wizards, language constructs, and tools to
support rapid application development. While EGL is procedural and declarative
in nature, EGL also provides many object-oriented programming features, such
as encapsulation, function overloading, user defined data types, events based
programming, and abstraction. You can start small, and adopt object-oriented
programming type capabilities as you advance.
Key terms and ideas that are specific to EGL include these:
Data items: EGL has constants and variables like any programming
language. Additionally EGL has data items, which in the simplest case are
variables with additional properties. For example, a data item can extend an
integer to include a default value, the range or list of acceptable values, and
more. There are 30 or more properties that data items can contain, each with
a distinct purpose.
The advantage towards using data items is code re-use. You can program a
given variable’s behavior one time, and then re-use it wherever necessary.
EGL installation
EGL ships as a package called IBM Rational Business Developer Extension
and is installed using the IBM Installation Manager into the same Eclipse shell as
Rational Application Developer.
Tip: To follow this chapter, we suggest that you use a new workspace.
However, this is not required, and you can certainly use the same workspace
used for the other chapters.
You can select a new workspace when you are prompted after starting
Application Developer, or you can switch to a new workspace by selecting
File → Switch Workspace from the menu bar.
Note: Most EGL developers work in the Web perspective. The Project
Explorer view offers a hierarchical display of entities inside each project, and is
the view most commonly used to manage EGL projects.
Tip: You might already have this connection from Chapter 9, “Develop
database applications” on page 355. You can reuse that connection or create
a new connection: Clear Use default naming convention and enter a
connection name.
Figure 15-2 Testing the Database Connection Resource, Database Explorer view.
Before leaving the Database Explorer view, release this (single user)
connection to Derby by right-clicking ITSOBANK [Derby 10.1] and selecting
Disconnect.
At times, you may want to disconnect and reconnect from this database
connection resource by using this same context menu.
Figure 15-4 Project Properties: Extending the Java Build Path with Derby
– On the left side of the Properties dialog, select JDBC Connections. When
prompted to save the changes, click Apply.
– Click New and the New JDBC Connection dialog opens (Figure 15-5):
– Select Use an existing connection and select ITSOBANK from the list.
– Click Finish and the connection is added to the Properties dialog.
– Click OK to close the Properties dialog.
All of this prior activity was preparatory in nature towards defining our run time
environment. Now we are ready to create EGL program code.
Select File → New → Other → EGL → EGL Data Access Application, and
click Next.
The EGL Data Access Application dialog opens (Figure 15-6):
– Select RAD7EGLnonWeb for the Project Name.
– Select ITSOBANK for the Database Connection.
– Select ITSO.CUSTOMER for Select Tables.
Click Next.
In the EGL Data Access Application - Define the Fields dialog, leave all the
defaults and click Next.
In the EGL Data Access Application - Define Project Creation Options dialog:
– For Default package name enter the value generated.
Some SQL database servers require presence of the schema identifier when
accessing SQL tables, while other database servers do not; in other words, is
the SQL table name ITSO.CUSTOMER or just CUSTOMER. To make matters more
complicated, SQL databases have the concept of a current schema, versus
distinct (absolute path name to) schemas.
The net result of this topic is that we are using fully (schema) qualified SQL
table names.
Click Finish.
This action produces several progress dialog boxes and eventually the New EGL
Data Access Application dialog closes.
This action also produces a several EGL packages and EGL files under
EGLSource\generated.
You can use the Project Explorer to open and examine these new entities. Close
all of these files without change when you are done.
Example 15-1 SimpleBatch.egl program listing (line numbers are for reference only)
002 package MyPrograms;
003
004 import generated.data.*;
005
006 program SimpleBatch type BasicProgram {}
007
As a language, EGL is not case sensitive. There are, however, identifiers which
are exported to and from EGL that are case sensitive. For example, any variable
names passed as part of an HTTP request header are case sensitive.
The Java code generated from the compilation is visible in the Project Explorer
under JavaSource. If you understand Java, open myprograms/SimpleBatch.java.
Notice that the original EGL statements are shown as comments, with the
generated Java code after each statement.
Repeating the contents of Chapter 22, “Debug local and remote applications” on
page 1041 is beyond the scope of this section. Review the chapter to get the
basic concepts and operation of the Application Developer Debugger, then apply
this skills towards debugging SimpleBatch.egl:
Open SimpleBatch.egl and set a breakpoint: Double-click into the gray side
bar on the left on the line SQLLib.connect("jdbc:derby...). A small blue dot
appears in the side bar.
Click the Step Over icon to step through the EGL code.
As you go though the source code, the results are displayed in the Console
view.
Click the icon to run through the program.
Debug the program once more. When stopped at the breakpoint, overtype the
value of var1 in the Variables view with:
"SELECT lastname FROM itso.customer ORDER BY 1"
Run through the program and only last names are displayed.
If we just run a Web page from an EGL Web project, we would receive a series of
prompts that would start the application server (if not running), deploy the EGL
Web project (if not previously deployed), and start the application contained
within the EGL Web project. This one call to action would invoke a number of
sub-actions, some of which can be resource intensive when run for the first time.
To minimize any chance for error, we perform each of these steps manually in the
sections that follow.
Note: The Web Diagram Editor may optionally open at this point. If this editor
opens, close it. Using the Web Diagram is outside our scope.
If you define a JNDI resource on the server side, then all Web project EAR
files hosted on that application server would have access to that single JDNI
definition. If you define the JNDI resource inside the EAR file, then that
(application) has one less external dependency, one less thing that can break.
We are defining our JNDI resource inside the application, inside the EAR file.
Note that we configure the data source with JNDI name jdbc/itsobank in the
server in “Configuring the data source in WebSphere Application Server” on
page 1313. There is no harm to have the same JNDI name configured also in
the EAR file, as long as they point to the same database.
In the Project Explorer, locate the EAR file entry for the EGL Web project,
RAD7EGLWebEAR.
If you need a memory aid to distinguish why we are currently referencing the
EAR file, and not the EGL Web project, we are currently setting deployment
options, which is work generally done in the EAR file.
Expand RAD7EGLWebEAR and open the Deployment Descriptor in the
Application Deployment Descriptor editor.
This actually opens the file /META-INF/application.xml.
Select the Deployment tab (Figure 15-11 shows the completed editor).
The first area of interest is the JDBC provider list.
In effect, this is where you register a category of database vendor as
determined by their JDBC driver packaging. If your application used the open
source Derby database server, DB2 UDB, and IBM Informix IDS, you would
have three entries in this section, because these three servers use different
JDBC driver packaging.
We are using Derby in this example and the entry for Derby is already present
in this list. If our example were only using DB2 UDB, we would add an entry
for DB2 UDB. To be extra clean, we would likely delete the entry for Derby.
The second area of interest in the section entitled Data source defined in the
JDBC provider section selected above.
This is the area where we define a specific data source (a database) for the
selected JDBC driver (Derby JDBC Provider (XA) is currently selected).
Click Add next to the data source section to define a data source for Derby.
In the Create Data Source dialog, select the type of JDBC provider as Derby
JDBC Provider (XA) and click Next (Figure 15-12).
With other database providers, you would have to add an entry for Container
managed authentication alias, and this alias must be defined with a user ID
and password in the Authentication section.
In the third and final step (Figure 15-13), select the databaseName property
and enter the directory name of the Derby database as value, in our case:
C:/7501code/database/derby/ITSOBANK
This is the only required property for embedded Derby.
Different vendors display different variables to be set in this dialog. For
example, a network accessible database has a port number and host name or
IP address.
Click Finish and the dialog closes. The properties are added to the Resource
properties section in the deployment descriptor.
You can select an entry in any section and click Edit to modify a value.
Each section of work we have completed thus far for this example were
preparatory in nature; meaning that these sections are performed one time only.
Once you have created and configured a given EGL Web project as detailed
above, the only tasks you are left with are painting and linking the Web pages.
If you go to your favorite on-line bookseller and query an author or subject area,
you are likely to receive a list page, that is, a Web page offering multiple listings
(multiple hits), each with its associated minimal identifying or key data. In the
case of books, you might receive the book title, and a very brief descriptive entry
regarding each given book. Then a link or menu command allows you to access
a more detailed entry for a any given (book); the link sends you to a detail page,
which has the full (single) book listing.
The example we are about to create uses two Web pages: A list page that shows
numerous customer records with only a subset of the customer columns, and
then a detail page with the full width of customer columns. A link on the list page
allows access to the detail page, and a button on the detail page allows to return
to the list page.
In online transaction processing systems, often the list page is read only, while
the detail page allows writes. To offer a simple example, both of our pages just
read.
Note: Whereas all EGL source code goes under EGLSource, all HTML, XML,
JavaScript, CSS, and related files go under WebContent.
Note: Page templates are one method that allow you to include re-usable
visual components on single or sets of Web pages. Page templates also
promote a consistent look and feel across numerous pages.
Click Finish and the CustomerListPage.jsp opens in the Page Designer. The
JSP file itself is added to the WebContent folder.
When designing Web pages with Page Designer, you work with these views:
Page Designer (editor) with Design, Source, and Preview tabs
Palette view with HTML, JSP, EGL, Faces, Data, and other parts
Properties view for details of elements selected in Page Designer
Page Data view for session and request block data and JavaBeans
The Page Designer is in the top middle position. This editor is like our canvas,
where we drop visual controls from the Palette view. Most of our work is done
in the Design tab, although you can edit the HTML and JSP source directly in
the Source tab if you want.
The Palette view has drawers (as in desk drawers), that open (expand) and
present visual components that may be dragged and dropped into Page
Designer (both Design and Source tab).
The remaining views we present by example.
First we compile our EGL JSF handler, then we change its associated Web page
to display some of its results.
To compile the EGL JSF handler, right-click EGLSource (in RAD7EGLWeb) and
select Generate.
Figure 15-17 Drag and drop customers from Page Data to Page Designer
Releasing customers in the JSP opens the Insert List Control dialog.
Change to Insert List Control dialog (Figure 15-18):
– Select Displaying an existing record (read-only).
– Clear Title and Firstname, we only retrieve Ssn and Lastname.
– Change the labels of Snn to SSN and Lastname to Last name.
– Click Finish.
This action closes the Insert List Control dialog and adds a new visual control
to the Web page editor. The official name for this type of visual control is,
hx:dataTableEx(tended)—visible in the Properties view when selected—in
effect, it is an HTML table that is bound to our dynamic array of SQL records.
The binding is visible in the Properties view in the Value field and specifies
that the data comes from the CustomerListPage JSF handler and the
customers variable:
#{CustomerListPage.customers}
Save the JSP. The layout of the JSP (so far) is shown in Figure 15-19.
Remove other
projects from the
server and only
deploy the EGL
Web project.
The Add and Remove Projects dialog has two sides to its display; the left side
lists projects which are not deployed but could be (Available projects), and the
right side lists projects which are deployed and can be un-deployed
(Configured projects).
Click Finish to close the Add and Remove Projects dialog, and the EAR
project is deployed to the server.
Be aware that the deployment may take a while. Notice the progress
information at the bottom right of the Application Developer window.
Extending the Web list page with a hyperlink to the detail page
Per our intended design, we have one change remaining to the Web page,
CustomerListPage.jsp. We have to add a link that displays the second Web
page.
Next, we describe how to add the link to the SSN column. You can then add
another link on the Last name column on your own; the procedure is the same.)
We can add the link(s) now, and then create the second Web page afterwards.
While we use the term link in the generic sense, technically what we are about to
add is a data aware hyper-link (outputLinkEx). This type of link automatically
retrieves the given key value from a list of records and forwards this value to the
Web page with which it is associated.
For this next set of tasks, we use the Page Designer, Properties view, and Palette
view. Open the CustomerListPage.jsp and select the Design tab:
In the Ssn column, select (click) {Ssn}abc. A box appears around the word
(Figure 15-22).
After {Ssn}abc is selected, go to the Palette view and open the Enhanced
Faces Components drawer. Locate the Link component, and double-click it.
In the Configure URL dialog, enter the value CustomerDetailPage.faces in
URL field, and click OK.
Notice the Link icon that is added in front of Ssnabc.
Note: Alternatively, to double-clicking Link you can drag the Link control on
top of the Ssnabc control in the Design tab. The result is the same.
We want to pass the SSN of the customer as a parameter to the detail page.
Parameters must have a name and a value. We want to dynamically bind the
value to the SSN of the customer.
– Click in the Name field and overtype Name0 with CID.
CID is the variable name that is passed in the HTTP request header. HTTP
request header variables are passed by name; hence, this variable name
is significant, as is its case.
– Click in the Value field and a button with an image similar to a book
(indicating the availability of a lookup) appears on the right side of the cell.
– Click the button to open the Select Page Data Object dialog.
Expand customers - Customer[] and select Sss - Ssn, then click OK.
– The new value in the Value cell is now #{varcustomers.Ssn}. This variable
value is created and managed for us automatically. and it equals the value
of the Ssn column for any specific row that display. These variables are
automatically managed and populated from dynamic JSP visual controls,
and are in scope inside the JSP.
Save the JSP.
You can see the JSP code of the hyperlink in the Source tab:
<hx:outputLinkEx id="linkEx1" styleClass="outputLinkEx"
value="CustomerDetailPage.faces">
<h:outputText id="textSsn1" value="#{varcustomers.Ssn}"
binding="#{CustomerListPage.customers_Ssn_Ref}"
styleClass="outputText">
</h:outputText>
<f:param name="CID" id="param1" value="#{varcustomers.Ssn}"></f:param>
</hx:outputLinkEx>
For now, this is expected. This link forwards us to a Web page that does not exist.
We create this Web page in the next section.
Tip: If you are interrupted by a pop-up stating that User Operation is Waiting,
click the red icon to stop the server publishing activity.
import generated.data.Customer;
customer Customer;
function doButtonClick()
forward to "CustomerListPage";
end
end
To keep our discussion of EGL brief, the examples in this chapter only read data;
they did not write data. Also, after the EGL batch job, we suppressed any error
program recovery code when reading data. Writing data and having full program
error recovery is easy in EGL. Hopefully these examples gave you enough to
begin your mastery of EGL.
To implement a detail page with update capability is not much different from the
current detail page. We provide only short instructions on how to accomplish this.
You can find the JSP and EGL code in the C:\7501code\egl\update folder.
function doUpdateClick()
SysLib.writeStdout("Customer updating: " + customer.ssn);
try
replace customer with #sql{ update itso.customer
set title = :customer.Title, firstname = :customer.Firstname,
lastname = :customer.Lastname where ssn = :customer.Ssn };
onException (e AnyException)
SysLib.writeStdout("Error: " + e.messageid);
SysLib.writeStdout("Error: " + e.message );
Drop the customer bean from the Page Data view into the Design tab:
– This time, select Update an existing record. All the fields are input fields.
– Change the labels to nicer text.
– Click Options and select Submit button with the name Update
Customer.
– Click OK to create the form with a table with input fields, and a button for
updating under the table.
Add a Button - Command and name it Return to List.
Bind the Update Customer button to the doUpdateClick function. This
invokes the SQL update statement.
Bind the Return to List button to the doGoback function that returns to the
customer list.
Select the SSN input field, and in the Properties view, h:inputText →
Behavior tab, select Control is read-only (the SSN cannot be updated).
Note that we cannot use an output field, because we must have the SSN
submitted with the other fields to have the key for the table update.
Finally, run the CustomerListPage.jsp on the server. Click a last name in the
customer list, make changes to the fields, and click Update Customer. If you
change the last name the customer list displays the new name.
More information
For more information on EGL, refer to these resources:
Redbooks publication: Transitioning: Informix 4GL to Enterprise Generation
Language (EGL), SG24-6673
Redbooks publication: Legacy Modernization with WebSphere Studio
Enterprise Developer, SG24-6806
Whitepaper: Exploiting Enterprise Generation Language for Business
Oriented Developers:
ftp://ftp.software.ibm.com/software/rational/web/whitepapers/G507-0995-0
1-bodev.pdf
IBM developerWorks articles on Enterprise Generation Language:
http://www.ibm.com/developerworks/rational/products/egl/
http://www.ibm.com/developerworks/rational/products/egl/egldoc.html
http://www.ibm.com/developerworks/rational/library/05/510_java/
http://www.ibm.com/developerworks/rational/library/07/0126_sayles/
Wikipedia:
http://en.wikipedia.org/wiki/Enterprise_Generation_Language
DevX.com:
http://www.devx.com/ibm/Article/31574
We describe how to develop entity beans, and explain the relationships between
the entity beans and session beans. Then we integrate the EJBs with a front-end
Web application for the sample application. We include examples for creating,
developing, and testing the EJBs using Rational Application Developer.
The EJB architecture shown in Figure 16-1 reduces the complexity of developing
business components by providing automatic support for such system level
services, thus allowing developers to concentrate on the development of
business logic. Such focus can bring a competitive advantage to a business.
EJB EJB
Home Object
In the following sections we briefly explain each of the EJB architecture elements
depicted in:
EJB server
EJB container
EJB components
EJB server
An EJB server is the part of an application server that hosts EJB containers. It is
also called an Enterprise Java Server (EJS). WebSphere Application Server is
an EJS.
The EJB server provides the implementation for the common services available
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
eight services that must be provided by an EJB server:
Naming
Transaction
Security
EJB container
The EJB container functions as a runtime environment for enterprise beans by
managing and applying the primary services that are needed for bean
management at runtime. 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.
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.
The responsibilities that an EJB container must satisfy can be defined in terms of
the primary services. Specific EJB container responsibilities are as follows:
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 can 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 (for example, begin, commit, rollback).
Security: The container provides security realms for enterprise beans. It 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.
Note the similarity here to the list in “EJB server” on page 722. This is due to the
unspecified division of responsibilities between the EJB server and container.
EJB components
EJB components represent the actual EJBs themselves and include all the
classes, interfaces, and constructs that make up the enterprise bean. We
distinguish between:
EJB types
EJB interfaces and classes
EJB client view
EJB relationships
EJB query language
EJB types
There are three types of enterprise beans: entity, session, and message-driven
beans (Figure 16-2).
Synchronous Asynchronous
The motivation for local interfaces is 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 clients, because local and remote depict the clients’ view of the bean. An EJB
client can be a remote client, such as a servlet running on another process, or
can be a local client, such as another EJB in the same container.
Even though a component can 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.
Additionally, Web service clients can access stateless session beans through the
Web service client view. The view is described by the WSDL document for the
Web service the bean implements, and corresponds to the bean’s Web Service
endpoint interface.
Relationships
Relations are a key component of object-oriented software development.
Non-trivial object models can form complex networks with these relationships.
It is the developer’s task to implement the differences among the three kinds of
relationships. These differences can require considerations of characteristics,
such as the navigation of the relationship and the encapsulation of the related
objects.
Component-level inheritance is not part of the EJB 2.1 specification, even though
it is planned for future releases. In want of standardized component-level
inheritance, IBM WebSphere Application Server V6.1 and Application Developer
implements proprietary component-level inheritance.
Note: Both finder and EJB select methods are used to query the back-end
where the actual data is stored. The difference is that finder methods are
accessible to clients, whereas select methods are internal to the
implementation and are not visible to clients.
EJB QL queries are defined by the bean provider in the deployment descriptor.
The SQL statements for the actual database access is generated automatically
by the deployment tooling. 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
The focus of this chapter is on implementing EJBs for the business model,
instead of regular JavaBeans. The rest of the application’s layers (control and
view) still apply as designed.
Business
Entities
Figure 16-3 EJB module class diagram for the sample application
The EJBBank session bean acts as a facade for the EJB model. Our business
entities (Customer, Account, Transaction, Credit, and Debit) are implemented as
CMP entity beans with local interfaces, as opposed to regular JavaBeans. By
doing so, we automatically gain persistence, security, distribution, and
transaction management services. On the other hand, this also implies that the
control and view layers are not able to reference these entities directly, because
they can be placed in a different JVM. Only the session bean (EJBBank) can
access the business entities through their local interfaces.
You might be asking yourself, then, why we do not expose a remote interface for
the entity beans as well? The problem with doing that is two-fold. First, in such a
design, clients would probably make many remote calls to the model to resolve
each client request. This is not a recommended practice because remote calls
are more expensive than local ones. Finally, allowing clients to see into the model
breaks the layer’s encapsulation, promoting unwanted dependencies and
coupling.
Because the control layer is not able to reference the model objects directly, we
reuse the Customer, Account, Transaction, Credit, and Debit from the Java
application in Chapter 7, “Develop Java applications” on page 227as data
transfer objects, carrying data to the servlets and JSPs, but allowing no direct
access to the underlying model.
HTTP RMI/IIOP
Web Client 1 Control Proxy 2 Facade
3
4 Entity
5
7 Model
Web Container
Application Server
Required software
To complete the EJB development sample in this chapter, you must have the
following software installed:
IBM Rational Application Developer V7.0
Database software, either of these products:
– Derby V10.1 (installed by default with Application Developer)
– IBM DB2 Universal Database V8.2
In this chapter we develop the entity beans shown in Figure 16-3 on page 731.
In the EJB Module dialog (Figure 16-7) enter the following items:
– Source folder: ejbModule (default)
– Select Create an EJB Client JAR Project to hold client interfaces and
classes (default).
– Name: RAD7EJBClient
– Client JAR URI: RAD7EJBClient.jar
– Click Finish.
The EJB client jar can be deployed together with a client application that
accesses the EJBs. This results in a smaller client application as compared to
deploying the EJB project with the client application.
If the current perspective is not the J2EE perspective when you create the
project, Application Developer prompts, asking if you want to switch to the
J2EE perspective. Click Yes.
Important: After creating the EJB project (RAD7EJB) you see an error in the
Problems view saying An EJB module must contain one or more enterprise
beans. An EJB project must contain at least one enterprise bean. The error is
corrected automatically when we create an enterprise bean in the later steps.
We have to add the RAD7EJBJava project to the EJB project and the enterprise
application so that we can reference the data objects and exceptions defined in
the Java project from the EJB project.The Java project has the actual data model
of the sample application. To configure the dependencies do these steps:
Open the deployment descriptor of the RAD7EJBEAR project:
– Select the Module tab and in the Project Utility JARs section (where
RAD7EJBClient.jar is listed) click Add. Select the RAD7EJBJava project and
click Finish.
– Save and close the deployment descriptor.
Right-click RAD7EJB and select Properties:
– In the Properties dialog, select J2EE Module Dependencies.
– Select RAD7EJBJava.jar and click OK.
Right-click RAD7EJBClient and select Properties:
– In the Properties dialog, select J2EE Module Dependencies.
– Select RAD7EJBJava.jar and click OK.
In the Select Connection dialog, select Create a new connection and click
Next.
Tip: You can also reuse the ITSOBANK connection from Chapter 9, “Develop
database applications” on page 355.
This section describes how to configure the data source using the WebSphere
enhanced EAR capabilities. The enhanced EAR is configured in the Deployment
tab of the EAR Deployment Descriptor editor. If you select to import the complete
sample code, you only have to verify that the value of the databaseName property
in the deployment descriptor matches the location of the database.
In this section, we focus on defining and implementing the business logic for the
entity beans. In “Object-relational mapping” on page 764, we define the mapping
to the relational database.
Note: Most of the time, the suggested values for the type names
(derived from the bean name) are fine, so you do not have to worry
about them. According to best practices, entity beans should have only
local interfaces, so Local client view is selected by default.
If you do not define at least one key CMP attribute, you cannot create the
CMP entity bean. Here are some considerations:
Array: If the attribute is an array, select the Array check box and specify
the number of the dimensions for it.
Key field: By selecting Key field, you indicate that the new field should
be part of the entity’s unique identifier. You can 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
declares that type as the key class. If you select an attribute of a
non-object type (int, double), or if you select more than one key
attribute, the environment automatically creates a new key class for
you, implements all its methods (including equals and hashCode), and
declares it as the key class.
The two last check boxes let you indicate whether 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, and if the attribute is a key field.
Tip: You can enter String, instead of java.lang.String, in the Type field
and Application Developer changes the type to java.lang.String.
After closing the CMP Attribute dialog, the Enterprise Bean Details page
(bottom part) is shown in Figure 16-17. Select Use the single key attribute
type for the key class. Click Next.
Figure 16-17 Creating an entity bean (2) after adding CMP attributes
In the EJB Java Class Details page, accept the defaults and click Next.
Important: The Bean superclass in the EJB Java Class Detail page is not
related to the Bean supertype field in the previous page (Figure 16-15 on
page 744). The former is used to define Java class inheritance for the
implementation classes that make up the EJB. The latter is used to define
the EJB inheritance hierarchy. Refer to “Define a bean supertype” on
page 749 for use of the Bean supertype and EJB inheritance feature.
Note: Although this page allows you to specify a class diagram, we found
that it defaulted to use the diagram named default.dnx, located in the root
of the RAD7EJB project. We chose to place all diagrams in a separate folder
named diagrams.
The new UML class diagram is displayed with the Customer entity bean
(Figure 16-18). Save and close the diagram.
Figure 16-18 Class diagram with Customer entity bean
Important: Make sure to select Use the single key attribute type for the
key class (Figure 16-17 on page 746).
In the Select Class Diagram for Visualization page, expand and select
RAD7EJB → diagrams → ejbs.dnx.
Composition
In the following sections we use the first two strategies described above to create
the association and the composition relationships, respectively.
Note: The names at the ends of the association (in this case customer and
account) are used to generate accessor methods in the two beans’
interface.
The plus sign (+) means that the relationship is visible to the associated
entity at the respective end.
If you select Delete from Diagram, or simply press Delete, the relationship is
only removed from the diagram, but stays in the model.
If a relationship is deleted from the diagram but stays in the model, it can be
redrawn by right-clicking one of the related entities and selecting Filters →
Show / Hide Relationships. The resulting Show/Hide Relationships dialog
can then be used to show or hide specific relationship types.
Figure 16-24 Defining relationships with the EJB Deployment Descriptor editor
Select the Customer-Account relationship and click Edit to see its diagram.
Save the deployment descriptor and close it.
Note: There is a fourth type associated with the Account bean: String. It is
the primary key class. If we had chosen a non-object key field or multiple
key fields, a key class would also have been generated.
Open the AccountBean class and select the Outline view (Figure 16-27).
Business methods:
Manipulate the CMP
attributes
Tip: The Java code for this section can be copied from the file
c:\7501code\ejb\source\Transactions.jpage.
– Select the ejbCreate method in the Outline view and Enterprise Bean →
Promote to Local Home Interface. This action updates the
TransactionLocalHome class.
Open the CreditLocalHome class. You should see a warning in the problems
view:
CHKJ2504W: The ejbCreate matching method must exist on itso.rad7.bank.mo
del.ejb.CreditBean (EJB 2.0: 10.6.12)
– Modify the create method signature to match the signature:
public itso.rad7.bank.model.ejb.CreditLocal create(int amount)
throws javax.ejb.CreateException;
Open the DebitLocalHome class and change the create method signature in
the same way.
Tip: The Java code for this section can be copied from the file
c:\7501code\ejb\source\Transactions.jpage.
Note: The TYPE_KEY constant defined in the Debit and Credit classes is
used by the EJB container to determine what type a given record in the
database refers to, because both Credit and Debit instances are persisted
to the same database table. The value of this constant is compared to the
value of the discriminator column (TRANSTYPE) in the TRANSACTIONS table.
Tip: The Java code for this section can be copied from the file
c:\7501code\ejb\source\AccountBean.jpage.
Tip: For refactoring, if you need to edit the signature of any method that
already belongs to either the remote or home interface, the easiest way is
as follows:
First demote the method from the interface.
Edit the signature.
Promote the method back to the interface.
If you do not demote the method from the interfaces first, you will have to
manually edit the method signatures in these interfaces. Using the
approach mentioned here, you let Application Developer update the
method signatures in the interfaces when the method is promoted back to
the interfaces.
Since the throws clause for a method is part of the method signature, this
procedure should also be followed when changing this clause.
Now add the create method back to the home interface by selecting
ejbCreate(CustomerLocal) in the Outline view and Enterprise Bean →
Promote to Local Home Interface.
When we created the relationship between the Account and the Customer
beans, the method setCustomers(Collection) was created. It does not have
to be available to clients. Right-click setCustomers(Collection) in the Outline
view and demote it from the local interface by selecting Enterprise Bean →
Demote from Local Interface.
Demote the accessors for the Account-Transaction relationships:
As you might recall, the relationship between the Account bean and the
Transaction bean is a composition. This means that references to transaction
objects cannot be exported to objects outside of the Account bean.
When we created the relationship, getTransactions and setTransactions
methods were generated and added to the local interface for the Account
bean. We want clients to be able to access the transaction log. If we were to
allow access to these methods, clients would be able not only to do so, but
also to add transactions to the log without correctly processing them using the
processTransaction method, which we define later in this section. The result
would be that the affected account object would be put into an invalid state.
This would be breaching the object’s encapsulation, and thus should not be
allowed.
Demote both getTransactions and setTransactions(Set) methods, then add
the getLog method as follows:
– Select both getTransactions and setTransactions(Set) in the Outline
view and Enterprise Bean → Demote from Local Interface.
Our example requires two similar simple custom finders: One for the Account
bean and the other for the Customer bean.
Open the EJB deployment descriptor. On the Bean page, select Account,
scroll-down to Queries, and you can find the findAll query. You can define
and update queries also in the deployment descriptor.
Object-relational mapping
Container-managed persistence (CMP) entity beans delegate their persistence
to the container. As mentioned in “Relationships” on page 727, this means that it
is the responsibility of the EJB container to handle the details of how to store the
internal state of the EJBs.
For the container to be able to do this, we have to provide information about how
the EJB fields are mapped to the relational database. This information is stored
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.
Note: This strategy is preferred when the data back-end does not exist and
is created from scratch.
Bottom-up is done 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. It is
the opposite of top-down approach. This approach is also called reverse
engineering.
Note: This is the folder that was created when we imported the database
metadata to the EJB project in “Import the physical data model” on
page 738.
In the Create new EJB / RDB Mapping dialog, select Meet In the Middle and
click Next (Figure 16-31).
The wizard has already mapped the Customer and Account beans to the correct
tables, and some of the fields are mapped to the correct columns. The mapped
items carry a little triangle as an indicator, and they are listed in the bottom pane.
There are two possible methods of completing the mapping: Drag-and-drop, and
using the context menus and selecting Create Mapping.
Select the Credit bean (in the Overview or Outline). In the Properties view
verify the value of the TRANSTYPE attribute as Credit. If the actual value in the
database table was different, we would specify it here.
Fro the Debit bean the discriminator value is Debit.
The Outline view of the mapping editor summarizes the mapping activities
(Figure 16-36).
The next EJB that we have to build is the session facade: The Bank stateless
session bean (Figure 16-37).
In the Enterprise Bean Details dialog, ensure that Stateless is selected for
Session type and Container is selected in the Transaction type
(Figure 16-39) and click Finish.
Tip: The Java code for this section can be copied from the file
c:\7501code\ejb\source\EJBBankBean.jpage.
Integer versus BigDecimal: The database and the entity EJBs keep the
balance and amounts as integers (int). The data transfer objects in the
RAD7EJBJava project and in the Web front-end define the balance and amounts
as BigDecimal. We have to convert between the two formats by dividing
integer values and multiplying decimal values by one hundred.
These conversions are done in the session facade (EJBBank) so that the view
and the model are unaware of the difference.
import java.util.Collection;
import java.util.Iterator;
import java.util.Set;
import java.math.BigDecimal;
import java.sql.Timestamp;
Tip: The Snippets view is usually located in the same pane as the
Properties view.
These methods are shown in Example 16-2. You can simply copy the four
methods from c:\7501code\ejb\source\EJBBankBean.jpage.
The EJBBank session bean is now complete. In the following sections we first test
the EJBs using the Universal Test Client and then proceed to integrate the EJBs
with the sample Web application.
Note: If you encounter errors with the deployment, import the interchange file
RAD7EJBonly.zip file from C:\7501code\zInterchangeFiles\ejb, and deploy
again: Right-click the RAD7EJB project and select Prepare for Deployment.
In this section we describe some of the operations you can perform with the
Universal Test Client. We use the test client to find the Customer EJB home, find
and create instances of the Customer bean, and send messages to those
instances.
Local EJBs
Remote EJBs
Click Work with Object. Notice how the object is added to the Objects
compartment and not to EJB Beans.
Running transactions
To run a deposit, select EJBBank 1 → void deposit(..), enter 002-999000777 as
the first parameter (account number) and 222 as the second parameter (amount),
then click Invoke. A message: The method completed successfully is displayed
(the method has no result).
You can play with the UTC to make sure all of your EJBs work. When you are
done, close the UTC window.
Persistence: In the first implementation, every time you started the Web
application you got the same data because it was created from memory. Now
we are running with EJBs accessing the underlying ITSOBANK database. All the
updates are persistent. The updated balance is stored in the database and the
transaction records accumulate for each account.
We now add client code to the Web application to utilize the EJBs that we
developed and tested in this chapter. A skeleton ITSOBank class is already in the
Web application. We have to implement the methods of the Bank interface.
}
return ejbBank;
}
Place the cursor inside the if statement and double-click EJB → Call an EJB
“create” method in the Snippets view.
In the Insert EJB Create wizard click New EJB Reference.
In the Add EJB Reference dialog, select Enterprise Beans in the
workspace, expand and select RAD7EJBEAR → RAD7EJB → EJBBank,
ensure that Remote is selected in the Ref type drop-down, and click Next.
Select Use default connect properties for doing a lookup on this
reference and click Finish.
When you return the Insert EJB Create wizard, click Finish.
The wizard generates a line into the getEJBBank method and a new
createEJBBank method (at the end).
Complete the getBankEJB method with the code from the generated
createEJBBank method, and delete the createEJBBank method:
private EJBBank getBankEJB() throws ITSOBankException {
if (ejbBank == null) {
Example 16-3 Completed facade methods invoke the EJBBANK session EJB
public Customer searchCustomerBySsn(String ssn)
throws InvalidCustomerException {
try {
return getEJBBank().getCustomer(ssn);
} catch (Exception e) {
throw new InvalidCustomerException(ssn + " (" + e.getMessage() +")");
}
}
public ArrayList<Account> getAccountsForCustomer(String customerSsn)
throws InvalidCustomerException {
try {
return new ArrayList<Account>(Arrays.asList(
getEJBBank().getAccounts(customerSsn) ));
} catch (Exception e) {
throw new InvalidCustomerException("Unable to retrieve accounts for: "
+ customerSsn + " (" + e.getMessage() +")");
}
}
public ArrayList<Transaction> getTransactionsForAccount
(String accountNumber)
throws InvalidAccountException {
try {
return new ArrayList<Transaction>
(Arrays.asList(getEJBBank().getTransactions(accountNumber)));
} catch (Exception e) {
throw new InvalidAccountException("Unable to retrieve transactions for:"
Application problem: If you get an error and the Web application does not
connect to the EJB application, then the sequence of the module
dependencies is wrong. Here are instructions for how to fix this problem:
Select the RAD7EJBWebEAR project and Properties and select the
J2EE Module Dependencies page:
– Clear RAD7EJBWeb.war and click Apply.
– Select RAD7EJBWeb.war and click Apply and OK.
After the application is restarted in the server, everything works (hopefully).
Note that these dependencies are stored in the .settings folder of the
project.
Note that the transaction listing is sorted by the timestamp. Relationships are
retrieved in no particular order by the container. We added extra code to the
EJBBANK session bean getTransactions method to sort the returned objects by
timestamp.
The final Web application also includes a ListCustomer servlet that uses the
getCustomers method of the EJBBank session bean to list customers by partial
last name. You can run this servlet using this URL:
http://localhost:9080/RAD7EJBWeb/ListCustomers
http://localhost:9080/RAD7EJBWeb/ListCustomers?partialName=i
More information
For more information on EJB, we recommend the following resources:
EJB 2.0 Development with WebSphere Studio Application Developer,
SG24-6819, Redbooks publication, found at:
http://www.redbooks.ibm.com/abstracts/sg246819.html
What are Enterprise JavaBeans components? Part 1: The history and goal of
EJB Architecture, white paper, found at:
http://www.ibm.com/developerworks/java/library/j-what-are-ejbs/part1/
What are Enterprise JavaBeans components? Part 2: EJB Programming
Model, white paper, found at:
http://www.ibm.com/developerworks/java/library/j-what-are-ejbs/part2/
What are Enterprise JavaBeans components? Part 3: Deploying and using
Enterprise JavaBeans components, white paper, found at:
http://www.ibm.com/developerworks/java/library/j-what-are-ejbs/part3/
These resources are most often accessed from a component that is running
within the J2EE application server itself, such as an EJB, servlet, or JSP.
However, these resources can also be used from a stand-alone Java application
(known as a J2EE application client) running in its own Java Virtual Machine
(JVM), possibly on a different computer from the server. Figure 17-1 shows the
resource access scenarios described.
EJB
client EJB EJB
JMS JDBC
J2EE application Queue Data
client container Source
JNDI service
Messaging
application
J2EE application
client container
Because a regular JVM does not support accessing such application server
resources, additional setup for the runtime environment is required for a J2EE
application. There are two methods to achieve this:
Add the required packages to the Java Runtime Environment manually.
Package the application according to the J2EE application client specification
and execute the application in a J2EE application client container.
When the JVM starts, it loads the necessary runtime support classes to make it
possible to communicate with WebSphere Application Server and to support
J2EE application clients that will use server-side resources. Refer to the
WebSphere Application Server Information Center for more information about
installing and using the Application Client for WebSphere Application Server.
Note: Although the J2EE specification describes the JAR format as the
packaging format for J2EE application clients, the Application Client for
WebSphere Application Server expects the application to be packaged as a
JAR inside an Enterprise Application Archive (EAR). The Application Client for
WebSphere Application Server does not support execution of a standalone
J2EE client JAR.
After the Import wizard has completed the import, four projects have been added
to the workspace:
RAD7EJBEAR: This is the deployable enterprise application, which functions
as a container for the remaining projects. This enterprise application must be
executed on an application server.
You should see a number of warnings existing in the workspace. If you do not
want to see these warnings, do these steps:
Select Window Preferences → Java → Compiler → Errors/Warnings →
Potential programming problems and change the option for Serializable
class without serialVersionUID from Warning to Ignore.
Expand the Unnecessary code section, and change the option for Local
variable is never read from Warning to Ignore.
Expand the Generic Types section, and change the option for Unchecked
generic type operation from Warning to Ignore. Click OK.
At the resulting Error/Warnings Settings Changed pop-up, click Yes.
Note: While it is possible to use the new client application with the existing
RAD7EJBEAR enterprise application, this is not the recommended approach.
The EJB project contains other server resources that should not be distributed
to the clients, such as passwords or proprietary business logic.
To finish the J2EE application client sample, you need to complete the following
tasks:
Creating the J2EE application client projects
Configuring the J2EE application client projects
Importing the graphical user interface and control classes
Creating the BankDesktopController class
Completing the BankDesktopController class
Registering the BankDesktopController class as the main class
When the wizard is complete, the following projects should have been created in
your workspace:
RAD7AppClientEAR: This is an enterprise application project that acts as a
container for the code to be deployed on the application client node.
RAD7AppClient: This project will contain the actual code for the ITSO Bank
application client.
To import the framework classes for the J2EE application client, do these steps:
In the Project Explorer expand RAD7AppClient, right-click
appClientModule, and select Import.
In the Import dialog, expand General → Archive File and click Next.
In the Archive file page click Browse to locate
c:\7501code\j2eeclient\RAD7AppClient_GUI.jar.
Expand / in the left panel and ensure that only itso is selected, and click
Finish (Figure 17-6).
Note: The code found in this section can be copied from the complete
BankDesktopController class that is supplied in the sample code:
c:\7501code\j2eeclient\BankDesktopController.java
We suggest that you copy the sections as noted in our procedure from the
completed BankDesktopController.java (step by step). If you simply import
the class, the serviceLocatorMgr.jar is not added as a Java JAR
dependency to the RAD7AppClient project, and thus you will have can not
resolve errors in the source code. The serviceLocatorMgr.jar is added by
using the Insert EJB wizard.
When you return to the Insert EJB create dialog, click Next.
To allow the application client to run on a node, separate from the application
server, just specify the server name when starting the J2EE client container.
In the Application Client for WebSphere Application Server, this can be done
by using the -CCBootstrapHost parameter in the launchClient command.
Refer to the WebSphere Application Server InfoCenter for more information
about using the Application Client for WebSphere Application Server.
The code for the ITSO Bank J2EE application client is now complete. Now we
just need to register the BankDesktopController class as the main class for the
application client.
The error regarding the missing main class disappears from the Problems view
when the file is saved.
Tip: If you get errors regarding classes not found (Account), rebuild each
project (select the project and Project → Build Project).
Note: Although the J2EE specification names the JAR format as the principle
means for distributing J2EE application clients, the WebSphere Application
Server application client container expects an Enterprise Application Archive
(EAR) file.
The exported EAR file can now be deployed to a client node and executed using
the Application Client for WebSphere Application Server.
Service
Broker
look up register
Service Service
Requester Provider
bind
Service provider
The service provider creates a service and can publish its interface and access
information to a service broker.
A service provider must decide which services to expose and how to expose
them. There is often a trade-off between security and interoperability; the service
provider must make technology decisions based on this trade-off. If the service
Service broker
The service broker, also known as the service registry, is responsible for making
the service interface and implementation access information available to any
potential service requester.
The service broker will provide mechanisms for registering and finding services.
A particular broker might be public (for example, available on the Internet) or
private—only available to a limited audience (for example, on an intranet). The
type and format of the information stored by a broker and the access
mechanisms used will be implementation-dependent.
Service requester
The service requester, also know as a service client, discovers services and then
uses them as part of its operation.
Web services are self-contained software services that can be accessed using
simple protocols over a network. They can also be described using standard
mechanisms, and these descriptions can be published and located using
standard registries. Web services can perform a wide variety of tasks, ranging
from simple request-reply to full business process interactions.
XML
Extensible Markup Language (XML) is the markup language that underlies 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.
All elements of Web services use XML extensively, including XML namespaces
and XML schemas.
SOAP
Simple Object Access Protocol (SOAP) is a network, transport, and
programming language neutral protocol that allows a client to call a remote
service. The message format is XML. SOAP is used for all communication
between the service requester and the service provider. The format of the
individual SOAP messages depends on the specific details of the service being
used.
WSDL
Web Services Description Language (WSDL) 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
The parameters and data types of these operations
The service access information
The specifications for Web services support in J2EE V1.4 are available at:
http://java.sun.com/j2ee/
The WS-Security 1.0 standard was published in March 2004. The standard also
includes the UsernameToken profile and X.509 Certificate Token profile.
Additional token profiles for REL and SAML are currently published as
Committee Drafts. For additional information, refer to:
http://www.oasis-open.org/specs/index.php#wssv1.0
http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=wss
In the top-down approach, a Web service is based on the Web service interface
and XML types, defined in Web Services Description Language (WSDL) and
XML Schema Definition (XSD) files. The developer first designs the
implementation of the Web service by creating a WSDL file using the WSDL
editor. The developer can then use the Web services wizard to create the Web
service and skeleton Java classes to which the developer can add the required
code.The developer then modifies the skeleton implementation to interface with
the business logic.
The bottom-up pattern is often used for exposing existing function as a Web
service. It might be faster, and no XSD or WSDL design skills are needed.
However, if complex objects (for example, Java collection types) are used, then
the resulting WSDL might be hard to understand and less interoperable.
Client development
To assist in development of Web service clients, Application Developer provides
these features:
Java client proxy from WSDL: The Web Service client wizard assists you in
generating a proxy JavaBean. This proxy can be used within a client
application to greatly simplify the client programming required to access a
Web Service.
Sample Web application from WSDL: Rational Application Developer can
generate a sample Web application, which includes the proxy classes
described above, and sample JSPs that use the proxy classes.
Web Service Discovery Dialog: This dialog allows you to discover a Web
service that exists online or in your workspace, create a proxy to the Web
service, and then place the methods of the proxy on a Faces JSP file.
After the build, all the warnings in the workspace should disappear.
Sample projects
The sample application that we use for creating Web service consists of the
following projects:
RAD7WebServiceUtility project: Simple banking model with BankMemory,
Customer, and Account beans. This is a simplified version of the RAD7Java
project used in Chapter 7, “Develop Java applications” on page 227.
RAD7WebServiceWeb project: Contains the SimpleBankBean, a JavaBean
with a few methods that retrieve data from the MemoryBank, a search HTML
page, and a result JSP.
We now have some resources in preparation for the Web services sample,
including a JavaBean in the RAD7WebServiceWeb project and a session EJB in the
RAD7WebServiceEJB project. We use these as a base for developing and testing
the Web services examples.
Slider
Tip: Alternatively, you can start the Web Services wizard using File →
New → Other → Web Services → Web Service.
The slider allows you to select the stages of Web services development. It
allows more granular division of Web services development:
Develop: Develops the WSDL definition and implementation of the Web
service. This includes such tasks as creating the modules which will
contain the generated code, WSDL files, deployment descriptors, and Java
files when appropriate.
Assemble: Ensures that the project which will host the Web service or
client will get associated to an EAR when required by the target application
server.
Deploy: Creates the deployment code for the service.
Install: Installs and configures the Web module and EARs on the target
server. If any changes to the endpoints of the WSDL file are required, they
are made in this stage.
Start: Starts the Web service once the service has been installed on the
server.
Test: Provides various options for testing the service, such as using the
Web Service Explorer or sample JSPs.
In Application Developer V6, the user has to create a server and start the
server in order to generate Web services code. In Application Developer v7,
the server does not have to be created if you move the slider to Deploy or
below. If the user does not have WebSphere Application Server 6.0 or 6.1
installed, the wizard uses the Web services emitters in the base_v6_stub or
base_61_stub folder to generate the code.
– This page allows you to select the server and runtime. We will leave this
page as default and click Cancel to exit this page.
Answer:
The recommended Web service runtime to use within Application
Developer is the WebSphere JAX-RPC Web services runtime.
Axis runtime shipped with Application Developer v7 (Axis v1.3) is a J2SE
SOAP engine and it supports the JAX-RPC standard. It does not require a
J2EE container and does not support the JSR 109.
The WebSphere JAX-RPC Web service runtime leverages the work that
IBM contributed to the Apache Axis code base. It is derived from Apache
Axis, but has diverged and contains many enhancements, such as
improved performance, WS-Security, multi-protocol support, J2EE
compliance, in-process optimization, compression, smart parsing, and
other enhancements.
– Clear Publish the Web service (we do not publish to a UDDI registry) and
clear Monitor the Web service (we will do that later).
– Click Next in the Web Services page.
In the Service Endpoint Interface Selection dialog, accept the default settings
and click Next (Figure 18-4).
In the Web Service dialog, accept the default options and click Next
(Figure 18-5).
Figure 18-5 Web Service wizard: Web Services Java Bean Identity
If you do not start the server before you run the wizard, you are directed to the
dialog shown in Figure 18-6. Click Start Server. It takes a while to start the
server. After the server is started, click Next.
The Test Web Services dialog (Figure 18-8) shows because we moved the
slider for the service to the Test position. Click Launch to launch the Web
Services Explorer.
The Web Services Explorer opens in an external Web browser (Figure 18-8).
Behind the scenes: The Web Services Explorer is a JSP Web application
hosted on the Apache Tomcat servlet engine contained within Eclipse. The
Web Services Explorer uses the WSDL to render a SOAP request. It does
not involve data marshalling and unmarshalling. The return parameter is
stripped out and the values are displayed in a pre-defined format.
Note: The Web Services Explorer can also be started by selecting a WSDL
file in Project Explorer and Web Services → Test with Web Services
Explorer. In this case, an internal browser in the Workbench is opened.
Starting JavaBean
WSDL file
WebSphere binding file
WebSphere extension file
JAX-RPC type mappings
Web services deployment
descriptor
Figure 18-10 Web services generated resources: Web project view
Note: In some cases, you might not be able to see the Web services or clients
under the JSR-109 Web Services category. Restarting the Workbench should
solve the problem.
The Web Services view only shows information about Web services defined in
projects within the workspace.
The Service Classes section shows how the Web Service is registered in a
Web project as a Servlet (this can also be seen in the Web project’s
deployment descriptor).
We recommend that the Web service and Web service client are in separate
Web and EAR projects:
– Click Client project: RAD7WebService Web. The Specify Client Project
Settings dialog comes up.
– Change the client project name to RAD7WebServiceClient.
– Select Dynamic Web project as the project type.
– Change the client EAR project name to RAD7WebServiceClientEAR.
– Click OK. The wizard creates the Web and EAR projects for you.
– Click Next.
In the Web Service Proxy Page dialog, accept the default (no security) and
click Next.
When prompted, enable automatic file overwrite.
In the Web Service Client Test dialog (Figure 18-13), use these settings:
– Select Test the generated proxy.
– Test facility: Select Web Service sample JSPs (default).
– Folder: sampleSimpleBankBeanProxy (default). You can specify a different
folder for the generated application if you want.
– Methods: Leave all methods selected.
– Select Run test on server.
– Click Finish.
The sample application starts and is displayed in a Web browser.
Select the getCustomerFullName method, enter a valid value in the
customer ID field (such as 111-11-1111), and then click Invoke.
The results are displayed in the result pane (Figure 18-14).
The TCP/IP Monitor is also started. The TCP/IP Monitor lets you intercept and
examine the SOAP traffic coming in and out of a Web service.
If you invoke the getEndpoint method in the Sample JSP page, you will get a
URL as follows:
http://localhost:8940/BankWebServiceEARWeb/services/SimpleBankBean
You might see a port number other than 8940. It depends on what port
number the wizard generated for the Monitor.
If you select Window → Preferences → Run/Debug → TCP/IP Monitor, you
can see the new Monitor is there to listen to the same port number. The
TCP/IP Monitor is started and ready to listen to the SOAP request and direct it
to the Web service provider.
All requests and responses are routed through the TCP/IP Monitor and
appear in the TCP/IP Monitor view.
To ensure that the Web service SOAP traffic is WS-I compliant, you can
generate a log file by clicking the icon at the top right corner. In the dialog
box that opens, select a name for the log file and specify where you want it to
be stored (for example in the client project).
The log file is validated for WS-I compliance. You will see a confirmation
dialog stating The WS-I Message Log file is valid. You can open the log file in
an XML editor to examine its contents.
Stop the TCP/IP Monitor by selecting Window → Preferences →
Run/Debug → TCP/IP Monitor and stop the TCP/IP Monitor from the list.
Note: You might notice that there are some warnings in the workspace. If you
do not want to see these warnings, select Window → Preferences → Java →
Compiler → Errors/Warnings → expand Deprecated and restricted API
section and change the option for Deprecated API from Warning to Ignore.
Expand the Unnecessary code section, and change the option for Local
variable is never read from Warning to Ignore. Click OK.
Figure 18-16 Drag and drop Web Service to JSF design view
Tip: You can add a Web service to a JSF page in the Web Diagram by clicking
Data in the pop-up toolbar of a page (the same discovery dialog opens).
The client side will receive one of the following types of exceptions:
java.rmi.RemoteException
javax.xml.rpc.soap.SOAPFaultException
A user-defined exception
In the last section we created a Web services JSF client to invoke the
getCustomerFullName operation. If the customer ID does not exist in the bank, the
Web service throws a CustomerDoesNotExistException, which is a user-defined
exception. On the client side, the generated Web service conveys the exception
to the client so that the client is able to catch the user defined exception and
display a user friendly message in the JSF page.
In this section we show you how to handle use-defined exception in the JSF
client code.
To resolve the compilation errors, right-click in the JSP page and select Edit
Page Code.
In the WSJSFClient.java code, select Source → Organize Imports. Save the
code.
In the page designer, select {Error Messages}. In the Properties view, for
h:messages, type color: red in the Styles: Props field.
Rerun the JSF application in the server and enter a bad social security
number to test the error handling (Figure 18-21).
You can go through the rest of the Web Service wizard pages (and accept the
defaults), or click Finish.
The WSDL editor is now opened with the new WSDL file. Select the Design
tab in the WSDL editor.
– In the WSDL editor, switch to Detailed View by clicking the down arrow at
the top right corner.
– Select the Properties view. Now you are ready to edit the WSDL file, as
shown in Figure 18-24.
– Change the element name from in to accountId, and select the type as
xsd:string.
– Clicking the icon at the top left shows all the directives, elements,
types, attributes, and groups in the WSDL.
– In the Types category, right-click and select Add Complex Type. Change
the name to Account.
Note: In Application Developer V6, you received a dialog box to display the
validation result. At the time of writing, the behavior is that the dialog box is not
displayed. The user has to check the Problems view to see if the WSDL is
valid or not.
If you have a problem when creating the WSDL file, you can import the
BankWS.wsdl from the C:\7501code\webservices folder.
Explore!
Once you have created a Web service, you might want to make changes to it:
For example, you might want to add a new WSDL operation
getBalanceByAccountId to the WSDL. Once the WSDL is changed, you
have to regenerate the Web service code and the existing business logic
will be wiped out.
To retain your changes while updating the Web service, you can use the
skeleton merge feature. This allows you to regenerate the Web service
while keeping your changes intact.
This option can be enabled by selecting Window → Preferences → Web
Services → Resource Management → Merge generated skeleton file.
In this section, we will use Ant tasks to automate the top-down code generation
process as we did in the last section.
Create a new dynamic Web project to host the Web service generated by Ant
tasks: RAD7WebServiceAnt in RAD7WebServiceEAR.
Copy the BankWS.wsdl from RAD7TopDownBankWS/WebContent folder to the
RAD7WebServiceAnt folder (not under WebContent).
You have the option of disabling the JAX-RPC schema to Java mappings that the
wizards use by default and instead using the Java Eclipse EMF 2.2 SDO
representation of XML schema. This can be useful if the XML schema contains
content that the JAX-RPC mappings do not handle gracefully.
Requestor Provider
Project: SDOClient Project: SDO
XSD
Main
Client WSDL
Application
AddressBookProxy AddressBook AddressBook
Proxy-
Proxy Bean SEI SEI
SDO Bean AddressBookBindingImplSDO
WAS WAS
AddressBookProxySDO Runtime Runtime
Skeleton-
Stub Skeleton
SDO
AddressBookBindingImpl
SDO
Serializer SDOs
PersonSOAPElementUtil
Utilities Deserializer
Project: SDOModel
Note: For more detailed information about the SDO facade for Web services,
refer to the developerWorks article at:
http://www.ibm.com/developerworks/webservices/library/ws-emfsdo/
Tip: The Web services preferences page is very useful and has great impact
on Web services development. For more detailed information, refer to the
developerWorks article at:
http://www.ibm.com/developerworks/rational/library/07/0508_cui/
Create Skeleton Web services and Web services client using SDO facade
tooling:
Generated code
A number of packages are generated into both server and client projects. Some
packages hold the SDO objects (org.example.bank.ws.impl) and the interfaces
(org.example.bank.ws), and other packages hold helper classes.
You can now use the navigatable and programmable SDO classes instead of
traversing the SOAPElement:
public class BankWSSOAPImplSDO {
public Customer getCustomer(CustomerIdType parameters) {
return null;
}
}
Create the Web services Web client to invoke the generated SDO facade proxy:
Import CustomerInquiry.html from C:\7501code\webservices into the
RAD7SDOFacadeBankWSClient/WebContent folder.
Right-click Web project RAD7SDOFacadeBankWSClient and New →
Servlet.
– Java Package: org.example.bank.servlet
– Class name: CustomerInfo
– Click Finish.
Replace CustomerInfo.java from C:\7501code\webservices into the servlet.
Study the servlet code. The customerId ssn or sin can be set in the parameter
of the Web service call. The resulting Customer bean has either the ssn or sin
attribute filled:
if (idType.equals("SSN"))
customerId.setSsn(request.getParameter("id"));
else customerId.setSin(request.getParameter("id"));
Customer customer = BankProxy.getCustomer(customerId);
At runtime, the Web service engine converts the SOAP fault into a
SOAPFaultException and throws it through the business method as an
unchecked exception, meaning that there is no representation of the exception
in the throws clause.
Looking ahead, JAX-WS 2.0, the successor to JAX-RPC, uses JAXB as the
preferred binding between XML schema and Java. This replaces the relatively
poor JAX-RPC data mapping. JAX-B promises mappings for all XML schemas.
The Web Services Feature Pack supports JAX-WS 2.0. We will explore the rich
features of Web Services Feature Pack at the end of this chapter.
– None: This will not enable security. This is the only WS-I compliant option.
– XML Digital Signature: This provides integrity against elements of a
SOAP message. It allows you to digitally sign elements in the SOAP
message protecting integrity.
– XML Encryption: This allows you to encrypt elements of a SOAP
message and propagate the encrypted data.
– XML Digital Signature and XML Encryption: This combines the
previous two options.
The security options available through the wizard are for illustration
purposes only. They should never be used in a production environment. They
point to the sample keystore and certificate files in WebSphere Application
Server.
2. Enabling Web services security using the WS Security wizard.
This is a new feature in Application developer v7. You can enable
production-level security for your Web services using the WS Security wizard,
which provides the following options:
– Add XML digital signature
– Add XML encryption
– Add a stand alone security token
A stand alone security token provides authentication for the Web service;
it will validate the user, and determine whether a client is valid in a
particular context.
Two key stores that contain the following keys are provided:
Server key store—Key store used by the Web service provider, and holds:
– Server public and private keys
– Client certificate with only a public key
When the Web service provider sends a SOAP response to the Web service
consumer, it encrypts the message with the Web service consumer’s public key.
When the Web service consumer receives the encrypted message, it uses its
own private key to decrypt the message.
In the Server Side Request Consumer XML Encryption page (Figure 18-34),
enter the following settings:
– Key store password: henry
– Key store path: C:\7501code\webservices\ServerKeyStore.jks
– Key store type: JKS
– Select Use a key
– Key alias: servercert
– Key password: henry
– Click Next.
In the Server Side Response Generator XML Encryption page, enter the
following settings:
– Key store password: henry
– Key store path: C:\7501code\webservices\ServerKeyStore.jks
– Key store type: select JKS from the drop-down menu
– Select Use a key
– Key alias: clientcert
– Key password: cui
Click Finish.
Click Finish.
Figure 18-36 Using the TCP/IP Monitor to see the encrypted message
In this section, we use the Web Services Feature Pack to create Web services
and a Web services client using the same WSDL we created in “Creating a
skeleton Web service” on page 817. We use the JAX-WS Web services runtime
to generate Web services and secure the Web service client with the RAMP
policy.
You also have to select Web Services Feature Pack and IBM WebSphere
Application Server Version 6.1 Feature Pack for Web Services option in the
Select the features you want to install page. Detailed steps can be found in
Appendix A, “Product installation” on page 1281.
Note that new installable product features, such as the Web Services Feature
Pack, are not displayed and cannot be added while running the Update Packages
wizard in Installation Manager. To install Web Services Feature Pack, run the
Modify Packages wizard in Installation Manager after you have installed the fix
pack and select Web Services Feature Pack and IBM WebSphere Application
Server Version 6.1 Feature Pack for Web Services option in the wizard to
install these new features.
The installation of IBM WebSphere Application Server V6.1 Feature Pack for
Web Services creates a new profile named AppSrvWSFP01, which is enabled
for the feature pack. To use this profile, when you launch the Workbench for the
first time after installing IBM WebSphere Application Server V6.1 Feature Pack
for Web Services, do these steps:
Create a new server definition that uses the AppSrvWSFP01 server profile.
Right-click in the Servers view and select New → Server. Click Next twice,
select AppSrvWSFP01 for the WebSphere profile name and click Finish. We
renamed the new server to WebSphere v6.1 Server WSFP for clarity.
You could modify the existing default server to point to the AppSrvWSFP01
server profile, but this is not suggested (we do have the new profile anyway).
– On the Project Facets page, select WebSphere 6.1 Feature Pack for
Web Services 1.0 and click Finish.
Import the BankWS.wsdl from C:\7501code\webservices into the
RAD7WSFP/WebContent folder.
Start WebSphere Application Server v6.1. Make sure the server uses the
Web Services Feature Pack enabled profile.
When you select to enable an asynchronous client, for each method in the
Web service, two additional methods are created. These are polling and
callback methods, which allow the client to function asynchronously. Click
Next.
In the Web Service Client Test page, select JAX-WS 2.0 JSPs as the Test
Facility. Leave all the methods selected. Click Finish (Figure 18-42).
Securing the Web service and client with the RAMP policy set
You can use policy sets to simplify configuring the qualities of service for Web
services and clients. Policy sets are assertions about how Web services are
defined. Using policy sets, you can combine configurations for different policies.
You can use policy sets with JAX-WS applications, but not with JAX-RPC
applications.
You can use the policy sets that are included with Application Developer to
simplify configuring the qualities of service for your Web services and clients. For
example, the Reliable Asynchronous Messaging Profile (RAMP) default policy
set consists of instances of the WS-Security, WS-Addressing, and
WS-ReliableMessaging policy types.
A policy set attachment defines which policy set is attached to service resources,
and which bindings are used for the attachment. The bindings define how the
policy set is attached to the resources. An attachment is defined outside of the
policy set, as meta data associated with the application. To enable a policy set to
work with an application, a binding is required. Use the policy set attachment
wizards to configure bindings.
The service is now listed in the Application table and the RAMP default policy.
Click Finish.
Secure the Web service client with the RAMP policy set
To secure the Web service client with the RAMP policy set, do these steps:
Select JAX-WS Web Services → Clients → RAD7WSFPClient:
{http://www.example.org/BankWS/}BankWS, and select Manage Policy
Set Attachment.
In the Application section, click Add to attach a policy set to the endpoint and
specify the bindings.
In the Endpoint Definition dialog, do these steps:
– Select BankWSSOAP as the Endpoint and getCustomer as the
Operation Name.
– From the Policy Set drop-down list, select RAMP default.
– In the Binding field, enter RAD7WSFPClientBinding as the name for the
binding that you want to associate with the attachment. Because the
information that a binding contains is unique to a given environment or
platform, you can use each binding with only one attachment. Click OK.
Select the WSSecurity policy and click Configure. The WSSecurity Binding
Configuration page is displayed (Figure 18-47).
Note: This example uses the sample keystore and certificate files in
WebSphere Application Server v6.1. The policy set configuration wizard in
Application Developer v7.0.0.3 Web Services Feature Pack does not support
Web service side custom binding configuration. This could be done through
the use of the WebSphere Administrative Console. The support for custom
binding configuration from the tools will be available in future version of
Application Developer.
MTOM uses the XML-binary Optimized Packaging (XOP) in the context of SOAP
and MIME over HTTP. XOP defines a serialization mechanism for the XML
Infoset with binary content that is not only applicable to SOAP and MIME
packaging, but to any XML Infoset and any packaging mechanism. It is an
alternate serialization of XML that just happens to look like a MIME multipart or
related package, with XML documents as the root part.
That root part is very similar to the XML serialization of the document, except that
base64-encoded data is replaced by a reference to one of the MIME parts, which
is not base64 encoded. This reference enables you to avoid the bulk and
overhead in processing that is associated with encoding. Encoding is the only
way binary data can work directly with XML.
In this section we use the top-down approach to create a JAX-WS Web service to
send binary attachments along with SOAP request, and receive binary
attachments along with SOAP response using MTOM.
The Web service client sends three types of document: Microsoft Word, image,
and PDF file. We describe several ways to send the documents:
The client uses byte[] to send the Word document.
The client uses java.awt.Image to send the image file.
The client uses javax.activation.DataHandler to send the PDF file.
image/gif java.awt.Image
image/jpeg java.awt.Image
text/plain java.lang.String
text/xml javax.xml.transform.Source
application/xml javax.xml.transform.Source
*/* javax.activation.DataHandler
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import javax.activation.DataHandler;
import javax.imageio.ImageIO;
@javax.jws.WebService(endpointInterface =
"com.ibm.rad7.mtom.ProcessDocumentDelegate",
targetNamespace = "http://mtom.rad7.ibm.com/", serviceName =
In the Result pane, click View image. The author image is displayed in the
Results pane (the author image is in the Preface of this document).
Examine the C:\7501code\webservices\AttachmentServer folder. You can
see that RAD7Team.jpg is stored in this folder. Note that the size is different
from the same file in the AttachmentClient folder (probably a different JPEG
compression is used).
Figure 18-51 SOAP traffic when MTOM is only enabled for the Web service
Example 18-7 SOAP response message and HTTP header with MTOM enabled
HTTP/1.1 200 OK
Content-Type: multipart/related;
boundary=MIMEBoundaryurn_uuid_0A4725631EA4903E161185655686209;
type="application/xop+xml";
start="<0.urn:uuid:[email protected]>";\
ÿØÿà
Run the sample JSP again.The SOAP request also has a small payload after
MTOM is enabled for the Web service client (Figure 18-52).
Figure 18-52 SOAP message with MTOM enabled for both client and server
Using annotations from the JSR 181 standard, you can annotate a service
implementation class or a service interface. Then you can generate a Web
service with a wizard or by publishing the application to a server. Using
annotations within both Java source code and Java classes simplifies Web
service development. Using annotations in this way defines additional
information that is typically obtained from deployment descriptor files, Web
Services Description Language (WSDL) files, or mapping metadata from XML
and WSDL into source artifacts.
The sample project is almost identical to the project we imported at the beginning
of this chapter. There is one difference: the WebSphere 6.1 Feature Pack for
Web Services facet is added to the project.
Annotate a JavaBean
You can annotate types, methods, fields, and parameters in the JavaBean to
specify a Web service. To annotate the JavaBean, open the SimpleBankBean in
the Web project RAD7WSFPAnnotationWeb and add the imports and
annotation tags highlighted in Example 18-9 (available in
C:\7501code\webservices\SimpleBankBeanAnnotation.txt).
@WebService(name="BankWebService",
targetNamespace="http://ibm.com/rad7/BankWebService")
@SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,
parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)
public class SimpleBankBean implements Serializable {
public SimpleBankBean() {
}
@WebMethod(operationName="RetrieveCustomerName",
action="urn:getCustomerFullName")
@WebResult(name="CustomerFullName")
public String getCustomerFullName(@WebParam(name="ssn")String ssn)
......
When you select the WebSphere 6.1 Feature Pack for Web Services facet for a
project, you enable the JAX-WS annotations processor. When you enable the
annotations processor, warnings and errors for annotations are displayed like
Java errors. You can work with these warnings and errors in various workbench
locations, such as the Problems view.
By using the annotations processor to detect problems at build time, you can
prevent these problems from occurring at run time. For example, if you make the
changes of Example 18-10 (instead of Example 18-9), you receive validation
errors as shown in Example 18-11.
public SimpleBankBean() {
}
@WebMethod(operationName= "!RetrieveCustomerName",
Test the JAX-WS Web service using the Web Services Explorer
To test the Web service, do these steps:
In the Project Explorer expand the JAX-WS Web Services folder.
Expand Services → RAD7WSFPAnnotationWeb:{http://ibm.com/rad7/
BankWebService}SimpleBankBeanService and select Test with Web
Services Explorer (Figure 18-53).
Figure 18-53 Test JAX-WS Web service using Web Services Explorer
Figure 18-54 JAX-WS Web service test result with Web Services Explorer
A simple test to verify that the Web service is running in the server can be
performed using this URL:
http://localhost:xxxx/RAD7WSFPAnnotationWeb/SimpleBankBeanService
The result displayed in the browser is:
{http://ibm.com/rad7/BankWebService}SimpleBankBeanService
Hello! This is an Axis2 Web Service!
http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.
ibm.websphere.wsfep.multiplatform.doc/info/ae/ae/rwbs_jaxwsannotations.html
Note: For more detailed information on IBM WebSphere Portal v6.0, refer to
“More information” on page 960.
Portals deliver e-business applications over the Web to many types of client
devices from PCs to PDAs. Portals provide site users with a single point of
access to multiple types of information and applications. Regardless of where the
information resides or what format it is in, a portal aggregates all of the
information in a way that is relevant to the user.
Portal page
A portal page is a single Web page that can be used to display content
aggregated from multiple sources. The content that appears on a portal page is
displayed by an arrangement of one or more portlets. For example, a World
Stock Market portal page might contain two portlets that display stock tickers for
popular stock exchanges and a third portlet that displays the current exchange
rates for world currencies.
Portlet application
Portlet applications are collections of related portlets and resources that are
packaged together. Portlets within the same portlet application can exchange
and share data and act as a unit. All portlets packaged together share the same
context, which contains all resources such as images, properties files, and
classes.
Portlet states
Portlet states determine how individual portlets look when a user accesses them
on the portal page. These states are very similar to minimize, restore, and
maximize window states of applications run on any popular operating system just
in a Web-based environment.
The state of the portlet is stored in the PortletWindow.State object and can be
queried for changing the way a portlet looks or behaves based on its current
state. The IBM portlet API defines three possible states for a portlet:
Normal: The portlet is displayed in its initial state, as defined when it was
installed.
Minimized: Only the portlet title bar is visible on the portal page.
Maximized: The portlet fills the entire body of the portal page, hiding all other
portlets.
PORTLET
PORTLET PORTLET
Portlet modes
Portlet modes allow the portlet to display a different face depending on how it is
being used. This allows different content to be displayed within the same portlet,
depending on its mode. Modes are most commonly used to allow users and
administrators to configure portlets or to offer help to the users. There are four
modes in the IBM Portlet API:
View: Initial face of the portlet when created. The portlet normally functions in
this mode.
Portlet events
Some portlets only display static content in independent windows. To allow users
to interact with portlets and to allow portlets to interact with each other, portlet
events are used. Portlet events contain information to which a portlet might need
to respond. For example, when a user clicks a link or button, this generates an
action event. To receive notification of a given event, the portlet must also have
the appropriate event listener implemented within the portlet class. There are
three commonly used types of portlet events:
Action: Generated when an HTTP request is received by the portlet that is
associated with an action, such as when a user clicks a link.
Message: Generated when one portlet within a portlet application sends a
message to another portlet.
Window: Generated when the user changes the state of the portlet window.
Portal solutions such as IBM WebSphere Portal are proven to shorten the
development time. Pre-built adapters and connectors are available so that
customers can leverage on the company's existing investment by integrating with
the existing legacy systems without re-inventing the wheel.
Development strategy
A portlet application consists of Java classes, JSP files, and other resources,
such as deployment descriptors and image files. Before beginning development,
several decisions must be made regarding the development strategy and
technologies that is used to develop a portlet application.
The standard portlet API was formalized as the JSR 168 specification from the
Java Community Process (JCP) program that addresses the requirements of
content aggregation, personalization, presentation, and security for portlets
running in a portal environment. It was finalized in October of 2003. Portlets
conforming to the standard portlet API are more portable and reusable, because
they can be deployed to any JSR 168 compliant portlet container. Application
Developer supports two portlet containers: One for portlets written using the
Standard portlet API and one for the portlets written using the IBM portlet API.
Unlike the IBM portlet API, the standard portlet API does not extend the servlet
API. It does, however, share many of the same characteristics, such as servlet
specification, session management, and request dispatching. The JSR 168
container—as implemented in WebSphere Portal V5.1—provided the Property
Broker support, which can act as a messaging broker for either portlet
messaging or wired (automatic cooperating) portlets. But this container did not
support the click-to-Action (user-initiated cooperating) portlets. Application
Developer and its Portal 6 Server support this feature now.
Note: IBM recommends using JSR 168 for all new portlet development when
the functionality it provides is sufficient for the application requirements, or
when the portlet is expected to be published as a Web Service for Remote
Portlets (WSRP) service. IBM is committed to the wider adoption of open
standards in WebSphere Portal.
JSF is now seemingly a preferred UI framework for developing J2EE Web and
portlet applications because of its component-based architecture.
Struts
Struts-based application development can also be applied to portlets, similar to
the way that Struts development is implemented in Web applications. The Struts
Portal Framework (SPF) was developed to merge these two technologies. SPF
support in Application Developer simplifies the process of writing Struts portlet
applications and eliminates the need to manage many of the underlying
requirements of portlet applications. In addition, multiple wizards are present to
help you create Struts portlet-related artifacts. These are the same wizards used
in Struts development. Refer to the Application Developer Struts documentation
for usage details.
In WebSphere Portal V5.1, Struts was fully supported in both the IBM and
Standard portlet APIs; however, there was no tooling support in Application
Developer v6 for this configuration. Application Developer v7 provides tooling
support for Struts portlet configuration.
Application Developer includes several new portal site creation tools that enable
you to visually customize portal page layout, themes, skins, and navigation.
The portal site configuration on WebSphere Portal server contains the following
resources: the global settings, the resource definitions, the portal content tree,
and the page layout. Importing these resources from WebSphere Portal server to
Application Developer overwrites duplicate resources within the existing Portal
project. Non-duplicate resources from the server configuration are copied into
the existing Portal project. Likewise, resources that are unique to the Portal
project are not affected by the import.
Now you can access the Portal Import wizard by selecting File → Import and
expand Portal then selecting Portal. You have to specify the server and options
for importing the project into Application Developer.
Important: You should not name your project wps or anything that resembles
this string, in order to avoid internal naming conflicts.
The project that you create with this wizard does not have any portlet definitions,
labels, or pages. The themes and skins that are available in this wizard are the
same as if you had imported a portal site from a WebSphere Portal server. To
create a new Portal Project, do these steps:
Select File → New → Project → Portal.
Expand Portal and select Portal Project. Click Next.
In the New Portal Project dialog, enter MyPortal in the Project Name field.
Use the default path, select the Portal Server V6.0 as your server, select the
WebSphere Portal v6.0 as the target runtime environment, enter the name of
the EAR (MyPortalEAR) project, and click Next (Figure 19-4).
In the Select Theme dialog, select the default theme (IBM) and click Next.
In the Select Theme dialog, select the default skin (IBM) and click Finish.
Click Yes in the Open Associated Perspective dialog.
The Portal Designer editor is opened with the selected theme and skin.
Portal Designer
Application Developer allows for editing both the graphic design and portlet
layout within your portal. Portal Designer is the Workbench interface that you see
upon opening a Portal project.
When using Portal Designer, the portal page layout can be altered. The layout
refers to the number of content areas within a page and the number of portlets
within those content areas. Page content includes rows, columns, URLs, and
portlets.
Once the project is published to the portal server, portal administrators can use
the administration portlets to give site users permission to edit the page layout.
In terms of portal layout and appearance, you can think of Portal Designer as a
What-You-See-Is-What-You-Get (WYSIWYG) editor. It will render graphic
interface items such as themes, skins, and page layouts.
Portal Designer provides the capability to alter the layout of the content within a
portal page with respect to navigation (the hierarchy of your labels, pages, and
URLs) and content (the arrangement of portlets via rows and columns on the
portal pages).
PortalConfiguration is the name of the layout source file that resides in the root
of the Portal project folder (Figure 19-5). To open Portal Designer, double-click
the ibm-portal-topology.xml file in the Project Explorer.
Portal Designer
Application Developer installation includes pre-built themes and skins to use with
portal projects. There are also wizards to create new themes and skins.
Changing themes and skins was previously done through portal administration.
In addition to these wizards for creating new skins and themes, there are tools
that can be used to change or edit these.
Once created, skins and themes are displayed in the Project Explorer view.
Double-click a skin or theme to manually edit it.
Application Developer already comes with a sample portlet application that does
exactly the same. Therefore, we begin by importing the sample code in our
Application Developer workspace. We will explore the code and then run it. After
that, we develop two new Portlets and use the tooling available in the Application
Developer to:
Retrieve records from a Derby database table and display the data in the JSF
Datatable component.
Use the JSF Form component to gather data and add a new record in the
Derby database.
If you are presented with a Migration Dialog (Figure 19-9), click Yes.
Important: In this step, ensure that you delete the WebSphere Application
Server V6.1 from the Servers view and restart the Workbench. The presence
of Application Server V6.1 and Portal V6.0 Server causes an issue where the
Application Developer cannot sense the proper state of Portal Server V6.x.
In the Servers view, right-click the WebSphere Portal V6.0 and select
Publish. The publishing of Portal server can take some time.
After publishing has completed, right-click the FacesPortletSDOExample
Portlet project and select Run As → Run on Server.
In the Run on Server dialog, select WebSphere Portal V6.0 as the server you
want to use to run this Portlet project. Also select Select server as project
default (do not ask again) so you are not presented with this dialog the next
time you are trying to run the portlets in this Portlet project. Click Finish.
After the portal server and the FacesPortletSDOExampleEAR enterprise
application has started, Application Developer opens a browser session in the
Workbench view and loads the running Portal application it. A new portal
page is created as the first portal page before the usual Portal Welcome
page. A child portal page is also created for each Portlet project that displays
the initial views of each portlet in that Portlet project.
For this technology sample, a portal page titled Rational portlets is created
as the first page. It has a child portal page titled FacesPortletSDOExample that
displays three portlets: Edit Records, Filter Records. and Sort Records
(Figure 19-13).
At this moment, take some time to explore the project and its artifacts, especially
the JSF components and their action methods in their page code Java classes.
The Page Data view for the Portlet JSP pages is also an excellent view to start
exploring.
In the Add Relational Record dialog, select the columns that you want to
display in your view. Click Finish.
This generates the necessary code and places a JSF Datatable component
on the JSP page with the selected columns (Figure 19-18).
Again, you can notice that a PTE portlets page has been created by the Portal
server as the first portal page. This page has a child portal page titled same as
the name of the Portlet project and all the four portlets (one new portlet and three
existing portlets) of this Portlet project are rendered on this page.
If you are wondering why the new portlet is rendered at the top, actually it was
not. By default, it would render at the bottom. However, by using the Portlet
Menu, we moved it to the top.
Figure 19-19 The new InventoryPortlet renders records of the INVENTORYSORT table
Figure 19-20 Reuse the metadata definition from the previous record list
Again, as you can notice, we have changed the layout of the page using the
Edit Layout portlet for the new page from the Portal administration console.
(Figure 19-23).
This Web service is basically the JavaBean Web service developed in “Creating
Web services from a JavaBean” on page 820.
Figure 19-26 Testing the deployed Web service using the Web Services Explorer
We want to create a Faces portlet that takes the social security number (SSN) as
an input and returns the full name of the customer, a list of all the accounts, and
the account balance, in a tabular format. The desired display should look
somewhat as shown in Figure 19-27.
Also, based on the details of operations of the Web services, we can easily
determine that we have to use the following two operations:
getCustomerFullName
getAccounts
Thus we have to make two Web services calls from the portlet and display the
result using the Faces components. That sums up the design discussion for this
use case; no need of class or sequence diagrams. This is one of the advantages
when you have chosen framework and technologies such as Portal and JSF and
using Web services to deliver the application logic and the data.
Figure 19-29 Drag the Web Service component to the JSP to start the Web Services
Discovery dialog
This completes the process of adding all the necessary input and output fields
to the view JSP and generating the code required to communicate with the
getCustomerFullName method of the Web service.
Run and test the Portlet project (Figure 19-34).
Notice that you do not have to write a single line of code, and that the tooling
generated all the necessary code.
This time, do not initiate the Web Services Discovery Dialog, but bring up the
dialog for the selection of the method of the same Web service. Click
getAccounts and click Next.
In the Input Form dialog, select the ssn that will be shown on the input HTML
form. You can also change the label of this field and also configure its look
and feel by clicking Options. Click Next.
In the Results Form dialog, select which output fields will be shown. You can
also change the label of the fields and configure the look and feel by clicking
Options. For example, you can configure the Balance out field to be always
right aligned. Click Finish (Figure 19-36).
The resulting view of the JSP now has two separate forms for the two
separate Web service methods that we want to execute (Figure 19-37).
Figure 19-37 Two separate forms for the Web service operations
Another step (optional) that you might want to complete is to format the result
that will be displayed in the account balance column so that the numbers
displayed are right aligned, displayed as a currency with a $ sign in front.
Figure 19-40 Configure the look and feel of the account balance
As you can imagine, if we execute this portlet, we are only submitting the
request to execute the getCustomerFullName method of the Web service, and
the getAccounts method is not called at all. This is because the Submit button
is bound to a method (in the page code Java class) that only has code that
communicates with the getCustomerFullName method. Therefore, we create a
new method called getAccountDetails and bind it to the Submit button and
from that method call the two methods that were bound to the two Submit
buttons we had before. Do these steps:
– To open the underlying page code of a Faces JSP, right-click in the Design
view and select Edit Page Code. This opens the Java class with the same
name as the JSP.
– Browse the code, and you can find the two methods bound to the Submit
buttons:
doSimpleBankBeanProxyGetCustomerFullNameAction();
doSimpleBankBeanProxy2GetAccountsAction();
Example 19-3 Change the action method for the Submit button
<hx:commandExButton
id="buttonDoSimpleBankBeanProxyGetCustomerFullNameAction1"
styleClass="commandExButton" type="submit" value="Submit"
action="#{pc_AccountDetailsPortletView.getAccountDetails}">
</hx:commandExButton>
If you execute the portlet as this moment, the second Web Services method
will throw back a Web services fault complaining about the null or missing
social security number. This is because we still have to change the code of
the second method of the page code class to use the SSN from the Faces
bean corresponding to the first input field as illustrated in Example 19-4.
Example 19-4 get SSN from the value submitted from the first input field
To be more specific, and in portal terminology, we are talking about the tooling
provided by Application Developer to aid the portal developer in creating and
management of following portal artifacts in a por tal (not portlet) project:
Portal themes and skins
Portal page hierarchy and layout
Portlet insertion on portal pages
Deployment, debugging, and testing of the integrated portal application with
themes and skins, portal pages, and portlets laid out in a desired page
hierarchy.
In the Project Explorer, expand the MyPortal project and double-click the
Portal Configuration to see the WYSIWYG view of the complete portal
solution with all the labels, portal pages, theme and skins, and the portlets on
the portal pages (Figure 19-43).
Figure 19-43 Workbench view of portal configuration of the imported Portal project
Figure 19-44 Project Explorer and Outline views of the imported Portal project
In the Project Explorer view, you can find the portal themes and skins artifacts
under the PortalContent folder.
Figure 19-45 Type the name of the new page and select the initial layout
The Portal Configuration view of this new portal page is displayed in the Portal
Designer Workbench (Figure 19-46).
Take some time to explore the Properties view for this portal page and you
notice that tooling provided by the Application Developer V7.0 lets the portal
developer (or designer) configure various properties of the portal pages much
more conveniently that it was possible before through the Portal
administration console or by using XMLAccess scripts. Some of the important
properties of the Portal page that can be configured through this console are:
– Unique name
– Theme and theme policy
– Supported markup
– Ordinality
– Title of portal page for different locales
– List of allowed portlets that can be inserted on this page
– Caching options
Let us change the order in which pages are displayed and move the new
Accounts page to be the first. Through the Outline view, drag and drop the
Accounts page as the first child page under the portal Home page
You also notice that after the Accounts page has been moved to be the first
displayed page, the Properties view of this page shows the updated Ordinality
for this page (Figure 19-48).
Now that we are done creating and configuring the new Accounts page, let us
now insert the AccountDetailsPortlet in the left column of this page. To do this,
right-click in the left column of the page layout and select Insert Portlet → As
Child.
In the Insert Portlet Dialog, select the AccountDetailsPortlet and click OK.
(Figure 19-49).
Figure 19-50 Initial view of the Accounts portal page in the Portal Designer
For the JSF and Struts based portlets, the JSP page for the initial view is
known and thus displayed correctly in the Portal Designer. The default JSP
page for basic portlets is automatically specified, especially if the portlet has
been generated by the Portlet wizard. To change the default JSP page to
another JSP page or to specify the default JSP page for your basic portlet, you
have to do the following tasks:
In the Project Explorer, find and expand the basic Portlet project. Select
and expand the Portlet Deployment Descriptor and right-click on the
portlet name and select Properties.
In the Properties dialog, select the JSP page that you want to be the
default, and click OK.
Now you can view the parent-child relationship between the Accounts page
and the AccountDetailsPortlet by expanding the Layout node in the Outline
view (Figure 19-51). You can change the look and feel of the portlets by
selecting a different portlet skin from the Properties view. You can modify the
portlet view by selecting the portlet in the Portal Designer and selecting
Edit → Edit Portlet, which opens the initial JSP page with the Page
Designer.
In the right-hand column of the portal page, follow the same process to insert
the out of the box About WebSphere portlet.
You must use the Export option when you are deploying to the staging and
production server. But we also recommend using the Export option when you are
testing the portal artifacts and portlets in the test environment.
The first option to deploy the portal solution using the tooling provided in
Application Developer is required especially if you want to debug the themes and
skins code in Application Developer or if you want to test the portlets in a
completely integrated portal.
In the Portlets dialog, the Deploy Portal wizard presents the list of Portlet
projects in the workspace and their portlets. The dialog also lists the
deployment status of these Portlet projects and their portlets on the selected
Portal Server.
Figure 19-53 Select which portlets to deploy along with the portal
In the Server Configuration Changed dialog, you are warned that because
changes have been made to the Portal Server configuration, during
deployment these changes are overwriting the present server configuration.
Click OK.
In the Run on Server dialog, you are asked to select the server you want to
run this Portal project. Select WebSphere Portal v6.0 Server and click
Finish.
This deployment process can take some significant amount of time,
depending upon your machine configuration and resources.
Figure 19-54 New Accounts page with Account Details; About WebSphere portlets
Following the same steps as above, create a new page titled Inventory and
make sure it is displayed to the right of the Accounts page.
On the Inventory page, insert the following two portlets that we created in the
previous exercises:
– Add Inventory Record portlet
– Inventory portlet
The Portal designer then displays the initial views of these two portlets on the
new Inventory portal page (Figure 19-55).
Deploy the Portal project once again and run it on the WebSphere Portal v6.0
server. Application Developer opens the portal application in the Browser view
in the workbench (Figure 19-56). You can test the two new Inventory portlets
on the Inventory page.
Figure 19-56 New Inventory page with Add Inventory Record and Inventory portlets
In the Portal Project Export dialog, select the Portal project EAR, and specify
the folder location where this deploy set is placed on the local file system.
Select WebSphere Portal v6.0 server as the Portal Server that you want to
deploy to. Clear Export only Themes and Skins, because we want to deploy
the complete portal application. Click Finish (Figure 19-58).
The export wizard exports the following items as a deploy set (Figure 19-59):
– nls—A folder that contains all the resource bundles.
– wps.ear—An enterprise application for deployment to the Portal Server.
– DeploymentInstructions.txt—A text document with detailed step-by-step
instructions to follow during the deployment process.
– DeployProject.xml—An XMLAccess document that contains all the portal
configuration changes made by us with all the new portal pages and the
configuration of all the portlets that were inserted on them.
Using this choice, you have control over what portal artifacts you want to include
or exclude in a new Portal project which can be regarded as a fragment of the
original Portal project. This option is especially handy when you working in a
team environment and can divide the non-overlapping portal topology fragments
To edit the skin of a Portal page, select that portlet either in the Portal Designer or
in the Outline view, right-click, and select Edit Skin to open the Control.jsp file
of the skin for that portlet.
The Default.jsp is the top level JSP page for a portal theme and includes
several JSP fragments that make up different parts of the Portal view, such as the
header section of the JSP page, top navigation, side navigation, banner (toolbar,
search control, and crumb trail), footer and flyouts.
The Page designer view provides an easy mechanism in the form of an intuitive
flyout that can be opened when you click the flyout icon of the Default.jsp. This
flyout (Figure 19-62) displays links to all the JSP fragments that are included in
the Default.jsp in an intuitive hierarchy for quick and easy navigation to the JSP
fragments and back. The flyout also displays the links to the Control.jsp for all
the skins of the all the portlets on that portal page.
Take some time to explore the code in all the JSP fragments and the purpose
they serve. You can try the following simple exercises:
Remove the footer from the portal.
Remove the search form at the top of a portal page.
Remove the crumb trail.
Change the banner image.
Add a link to the portal flyout menu that takes us to the Inventory page.
Add a greeting to welcome the user at the top of the page with their first
name.
Change the background color for the whole portal page and also change the
background color of the portlets to a different color.
This chapter describes the features and concepts of server configuration, as well
as demonstrating how to configure a server to test applications.
For example, a developer might want to have a separate server configuration for
WebSphere Application Server V6.x with a unique set of projects and
preferences in a workspace and server configuration pointing to a newly created
and customized WebSphere Application Server V6.x profile. On the same
system, the developer can create a separate portal server configuration with
unique portal workspace projects and preferences, as well as a WebSphere
Portal V6.0 Test Environment. This chapter describes how to create, configure,
and run multiple WebSphere Application Server V6.1 instances on the same
development system.
Application Developer server tools are based on the Eclipse Web Tools Platform
(WTP) project. WTP provides a facility for publishing an Enterprise Application
project and all of its modules to a runtime environment for testing purposes.
The server adapters on the following list are included in the Web Tools Platform
1.5.x based on Eclipse technology. Server adapters are tools installed into the
Workbench that support a particular server. Here is the list of server adapters:
IBM WebSphere Application Server Community Edition Version 1.1
Apache Tomcat Versions 3.2, 4.0, 4.1, 5.0, or 5.5
BEA WebLogic Server Versions 8.1, 9.0, or 9.2
JBoss Versions 3.2.3 or 4.0 from a division of Red Hat
ObjectWeb Java Open Application Server (JOnAS) Version 4
Oracle Containers for J2EE (OC4J) Standalone Server Version 10.1.3
Apache Geronimo Version 1.1
Pramati Server Version 4.1.x
With WebSphere Application Server Base and Express Editions, you can only
have standalone application servers, as shown in Figure 20-1. Each application
server is defined within a single cell and node. The administration console is
hosted within the application server and can only connect to that application
server. No central management of multiple application servers are possible. An
application server profile defines this environment.
Application Cell
Server profile
Application
Admin Server
console "server1"
Node A
Figure 20-1 System management topology: Standalone server (Base and Express)
With the Network Deployment package, you have the option of defining multiple
application servers with central management capabilities. For more information
on profiles for the IBM WebSphere Application Server V6.1 Network Deployment
Edition, refer to the WebSphere Application Server V6.1: Systems Management
and Configuration, SG247304.
Types of profiles
There are three types of profiles when defining the runtime of an application
server:
Application server profile
The primary use for this type of profile could be any of these possibilities:
To build a server in a Base or Express installation (including a test
environment within Rational Application Developer).
To build a standalone server in a Network Deployment installation that is not
managed by the deployment manager (for example, to build a test machine).
Custom profile
A custom profile is an empty node, intended for federation to a deployment
manager. This type of profile is used when you are building a distributed server
environment. You would use this as follows:
Create a deployment manager profile.
Create one custom profile on each node on which you will run application
servers.
Federate each custom profile, either during the custom profile creation
process or later using the addNode command, to the deployment manager.
Create new application servers and clusters on the nodes from the
administrative console.
For details on how to install the WebSphere Application Server V6.1 Test
Environment, refer to “Installing IBM Rational Application Developer” on
page 1283 (Figure A-13 on page 1290).
The stub folder contains minimal sets of compile-time libraries that allow you to
build applications for a server when it is not installed locally.
After the WebSphere Application Server V6.1 Test Environment is installed you
see this directory:
<rad_home>\runtimes\base_v61
Note: For simplicity, we will refer the entire path for the profile as
<profile_home>.
Start the server. Open the command prompt, and issue the following
commands:
cd <profile_home>\bin
startServer server1
Check the server log files. Once the server is started, you can see the
following message in the command prompt:
ADMU3000I: Server server1 open for e-business; process id is 4052
The server log files are in the <profile_home>/logs/server1 folder. Open the
following file to see the logging message:
<profile_home>/logs/server1/SystemOut.log
Open the WebSphere Administrative Console by accessing its URL from a
Web browser:
http://<appserver_host>:<admin_console_port>/ibm/console
http://localhost:9061/ibm/console/
The administrative console port was listed in the Profile Creation Summary
page during the profile creation.
Click Log in. Because security is not active at this time, you do not have to
enter a user name. If you choose to enter a name, it can be any name. If you
enter a name it will be used to track changes you made to the configuration.
Display the configuration from the console. You should be able to see the
following items from the administrative console:
– Application servers: Select Servers → Application servers. You should
see server1 (Figure 20-3). To see the configuration of this server, click the
name in the list.
Create a server
To create a server in Application Developer, do these steps:
Select the Servers view, in the J2EE or Web perspective.
Right-click in the Servers view and select New → Server.
In the Define a New Server dialog (Figure 20-4), select the following items:
– Host name: localhost (default)
– Select the server type: Select WebSphere v6.1 Server.
– Click Next.
In the Add and Remove Projects dialog, we do not select a project at this time,
and we click Finish.
The server will be created and is displayed in the Servers view. In our example,
the server WebSphere v6.1 @ localhost is created.
Tip: Open the new server configuration (double-click). You could change the
name of the server, for example, WebSphere v6.1 Server AppSrv02.
Customizing a server
Once the server has been created in Rational Application Developer, it is very
easy to customize the settings:
In the Servers view, double-click the server you want to customize.
There are a couple of key settings to point out in the server configuration
(Figure 20-6).
Server :
– WebSphere Profile name: Select the desired WebSphere profile.
– Under the Server connection type and admin port, use the radio
buttons to select whether to use the RMI or SOAP connection as the
communication channel between the development environment and the
server. By default, the RMI radio button is enabled when working with a
local server. If you are working with a remote server, the SOAP radio
button is enabled by default.
– Terminate server on workbench shutdown
If you want the server to be terminated after the workbench shutdown, you
have to select this option. Otherwise the server continues running after
you shut down the development environment. The next time you start the
IDE, the server is found again in its current state.
Automatic publishing:
– Use default publishing settings: Specifies to use the publishing settings
as defined in the Preferences page (Window → Preferences → Server).
To replicate server configurations across multiple profiles, you can use the
Import server configuration from server wizard to import the WebSphere v6.1
server profile configuration archive file into a workspace project folder. It
performs the same functionality as:
wsadmin AdminTask exportWasprofile
You can use the Export server configuration to server wizard to export the
WebSphere v6.1 server profile configuration archive file from a workspace
project folder to a WebSphere v6.1 server. It performs the same functionality as:
wsadmin AdminTask importWasprofile
This approach requires more disk space for each WebSphere profile and server
configuration, and requires additional memory if the servers run concurrently.
This section describes how to add an enterprise application to a server. Note that
you cannot add Web or EJB projects to a server, only enterprise applications
(EAR projects).
Once an application is added to the server you can run any of the HTML
pages or JSPs.
To address issues like the scenario described, uninstall the enterprise application
from the WebSphere Administrative Console as follows:
Make sure the server is started.
Start the WebSphere Administrative Console either by right-clicking the
server and selecting Run administrative console, or by accessing its URL
from a Web browser:
http://<appserver_host>:<admin_console_port>/ibm/console
http://localhost:9060/ibm/console/
Click Log in.
Select Applications → Enterprise Applications.
Select the desired application to uninstall, and click Uninstall.
When prompted, click OK.
When uninstallation is complete, save the changes.
Note: After you uninstall the application using the WebSphere Administrative
Console, you can see that the project still appears in the Configured projects
section if you start the Add and Remove Projects wizard. You have to click
Remove to move the project to the Available projects section.
Enhanced EAR
Resources
Resources
Enhanced J2EE App.
J2EE App.
EAR EAR
EAR
Properties
Properties
The enhanced EAR tooling is provided from the Deployment tab of the enterprise
application Deployment Descriptor editor (Figure 20-10). Deployment information
is saved under the application /META-INF/ibmconfig directory.
The upside of the tool is that it makes the testing process simpler and easily
repeatable, because the configurations it makes are saved to files that are
usually shared in the team repository. Thus, even though it will not let you
configure all the runtime settings, it is a good tool for development purposes
because it eases the process of configuring the most common settings.
The downside is that the configurations the tool makes are attached to the
EAR, and are not visible from administrative console. The console is only able
to edit settings that belong to the cluster, node, and server contexts. When you
change a configuration using the Enhanced EAR editor, this change is made
at the application context. The deployer can still make changes to the EAR file
using the Application Server Toolkit (AST), but it is a separate tool.
Furthermore, in most cases these settings are dependent on the node the
application server is installed in anyway, so it makes little sense to configure
them at the application context for deployment purposes.
The server configuration data that you specify in this editor gets embedded within
the application itself. This improves the administration process of publishing to
WebSphere Application Server v6.x when installing a new application to an
existing local or remote WebSphere Server by preserving the existing server
configuration.
For an example of configuring the enhanced EAR against the Derby database
refer to “Configuring the data source for the ITSOBANK” on page 740. In this
section, we demonstrate how to create a data source against a DB2 database
using enhanced EAR:
In the Project Explorer open the RAD7EJBEAR enterprise application
deployment descriptor.
Select the Deployment page.
Scroll down the page until you find the Authentication section. It allows you
to define a login configuration used by JAAS.
Click Add to include a new configuration (Figure 20-11).
Enter dbuser as the Alias, and the appropriate user ID and password for your
configuration. Click OK to complete the configuration.
In the Enhanced EAR editor scroll back up to the Data Sources, JDBC
provider list section. By default, the Derby JDBC Provider (XA) is predefined.
Because we are using DB2 for this example, we have to add a DB2 JDBC
provider by clicking Add right next to the provider list. The Create JDBC
Provider dialog opens (Figure 20-12).
Select IBM DB2 as the database type. Then select DB2 Universal JDBC
Driver Provider (XA) as the provider type.
Note: Note that for our development purposes, the DB2 Universal JDBC
Driver Provider (non XA) would work fine, because we do not require XA
(two-phase commit) capabilities.
In this page, enter DB2 XA JDBC Provider as the name. You also have to
replace the following variables with the actual location of your DB2 JDBC
driver path:
${DB2UNIVERSAL_JDBC_DRIVER_PATH}
${UNIVERSAL_JDBC_DRIVER_PATH}
${DB2UNIVERSAL_JDBC_DRIVER_NATIVEPATH}
For example, you have to use C:\Program Files\IBM\SQLLIB\Java instead of
${DB2UNIVERSAL_JDBC_DRIVER_PATH}.
Click Finish.
With the new DB2 provider selected, click Add next to the defined data
sources list (Figure 20-14). Select DB2 Universal JDBC Driver Provider
(XA) from the JDBC provider type list, and select Version 5.0 data source.
Finally, just set the databaseName property value to ITSOBANK, and click
Finish to conclude the wizard.
Save the deployment descriptor.
Port 9060 is the port defined for the WebSphere Administrative Console for the
application server in the WebSphere profile.
Configuring security
If the WebSphere Application Server v6.1 runtime environment has
administrative security enabled, you have to communicate the administrative
settings from your development environment to the runtime server. In the
Workbench you have to specify that security is enabled in the runtime
environment, and provide the user ID and password in the server editor to the
secured server. If you are working with a secured WebSphere Application Server
Version 6.1.x, you have to establish a trust between the development workbench
of this product and the server.
In this section, we show you how to enable administrative security with local
operating system registry using the WebSphere Administrative Console and how
to communicate the administrative settings from the development environment to
the runtime server.
Note: The specified user must have the required privileges in Windows, such
as the permission to log on as service. For more information see section 2.3 of
the IBM WebSphere Application Server V6.1 Security Handbook, SG24-6316.
Click Finish, then click Save, then click Logout to log off from administrative
console.
Stop the WebSphere Application Server v6.1.
The next time you start the server and open the administrative console, you are
prompted for a valid user ID and password.
There are five wsadmin objects available when you use scripts:
AdminControl: Use to run operational commands.
AdminConfig: Use to run configurational commands to create or modify
WebSphere Application Server configurational elements.
AdminApp: Use to administer applications.
AdminTask: Use to run administrative commands.
Help: Use to obtain general help.
With the Version 6.1 release of WebSphere Application Server, IBM announced
the start of the deprecation process for the Jacl syntax associated with wsadmin.
In this chapter, we show you how to create a Jython project and Jython script file,
how to edit the Jython script file, and how to run it.
Type the code shown in Example 20-1. It lists all defined JDBC providers in the
WebSphere Application Server. During typing, you can use content assists by
pressing Ctrl+Space. You can find the code is:
c:\7501code\Jython\listJDBCProviders.py
AdminConfig.reset()
cell = AdminControl.getCell()
node = AdminControl.getNode()
lf = java.lang.System.getProperty("line.separator")
slash = java.lang.System.getProperty("file.separator")
print "System information: Cell=" + cell
print "System information: Node=" + node
showJdbcProviders()
Note: There might be a few seconds delay before you see the Jython
command in the WebSphere Administration Command view.
IBMUTC
ivtApp
query
"Derby JDBC Provider
(XA)(cells/KLCHL2YNode01Cell/nodes/KLCHL2YNode01/servers/
server1|resources.xml#builtin_jdbcprovider)"
"Derby JDBC
Provider(cells/KLCHL2YNode01Cell/nodes/KLCHL2YNode01/servers/
server1|resources.xml#JDBCProvider_1182202633563)"
The command assist feature is great when you are learning Jython to create
scripts for future use.
More information
For more information, consult these IBM Redbooks publications:
WebSphere Application Server V6.1: Systems Management and
Configuration, SG24-7304
IBM WebSphere Application Server V6.1 Security Handbook, SG24-6316
Test concepts
Within a typical development project, there are various types of testing performed
during the different phases of the development cycle. Project requirements
based on size, complexity, risks, and costs determine the levels of testing to be
performed. The focus of this chapter is on component testing and unit testing.
Test phases
In this section we outline the key test phases and categorize them.
Unit test
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, they are written using
knowledge about the implementation details and test-specific code paths. This is
not to say that 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
might want to make use of both when defining your own unit testing policy.
Component test
Component tests are used to verify particular components of the code before
they are integrated into the production code base. Component tests can be
performed on the development environment. Within the context of Application
Developer, a developer configures a test environment and supporting testing
tools such as JUnit. Using the test environment, you can test customized code
The test run on the application of the build produced is called a build verification
test (BVT). BVT is a predefined and documented test procedure to ensure that
basic elements of the application are working properly, before accepting the build
and making it available to the test team for function verification test (FVT) and/or
system verification test (SVT).
Note: Within the Rational product family, the IBM Rational Function Tester is
an ideal choice for this type of testing.
Note: Within the Rational product family, the IBM Rational Manual Tester is
an ideal choice for this type of testing.
Performance test
Performance tests simulate the volume of traffic that you expect to have for the
application(s) and ensure that the system will support this stress, and to
determine if the system performance is acceptable.
Test environments
When sizing a project, it is important to consider the system requirements for the
test environments. Here is a list of some common test environments that are
used.
Component test environment: This is often the development system and
the focus of this chapter. In larger projects, we recommend that development
teams have a dedicated test environment to be used as a sandbox to
integrate the components of the team members, before putting the code into
the application build.
Build verification test environment: This test environment is used to test
the application produced from a controlled build. For example, a controlled
build should have source control, build scripts, and packaging scripts for the
application. The build verification team runs a subset of tests, often known as
regression tests, to verify basic functionality of the system that is
representative to a wider scale of testing.
System test environment: This test environment is used for FVT and SVT to
verify the functionality of the application and integrate it with other
components. There can be many test environments with teams of people
focused on different aspects of the system.
Staging environment: The staging environment is critical for all sizes of
organizations. Prior to deploying the application to production, the staging
environment is used to simulate the production environment. This
environment can be used to perform customer acceptance tests.
Production environment: This is the live runtime environment that
customers will use to access the e-commerce Web site. In some cases,
customer acceptance testing might be performed on the production
environment. Ultimately, the customers test the application. You must have a
process to track customer problems and to implement fixes to the application
within this environment.
Perhaps it is more useful to look at the question from the opposite perspective,
that is, why developers do not perform unit tests. In general, the simple answer is
because it is too hard or 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.
In practice, this usually turns out to be a false economy, because 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, which 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.
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.
Once you have decided to implement a unit testing strategy for 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 sooner the 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.
TPTP addresses the entire test and performance life cycle, from early testing to
production application monitoring, including test editing and execution,
monitoring, tracing and profiling, and log analysis capabilities.
Although each of these areas of testing has its own unique set of tasks and
concepts, two sets of topics are common to all three types:
Providing tests with variable data
Creating a test deployment
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.
import itso.rad7.bank.exception.InvalidAccountException;
import itso.rad7.bank.exception.InvalidCustomerException;
import itso.rad7.bank.ifc.Bank;
import itso.rad7.bank.impl.ITSOBank;
import itso.rad7.bank.model.Account;
import itso.rad7.bank.model.Customer;
import junit.framework.TestCase;
Example 21-2 lists the same test case class again, but this time using JUnit 4.x.
import itso.rad7.bank.exception.InvalidAccountException;
import itso.rad7.bank.exception.InvalidCustomerException;
import itso.rad7.bank.ifc.Bank;
import itso.rad7.bank.impl.ITSOBank;
import itso.rad7.bank.model.Account;
import itso.rad7.bank.model.Customer;
@Before
public void setUp() {
// Instantiate objects
this.bank = ITSOBank.getBank();
}
@After
public void tearDown() {}
@Test
public final void testSearchAccountByAccountNumber() {
try {
// Invoke a method
Account bankAccount = this.bank
.searchAccountByAccountNumber(ITSOBank4Test.ACCOUNT_NUMBER);
// Verify an assertion
assertEquals(bankAccount.getAccountNumber(),
ITSOBank4Test.ACCOUNT_NUMBER);
} catch (InvalidAccountException e) {
e.printStackTrace();
}
}
@Test
public final void testSearchCustomerBySsn() {
// Invoke a method
try {
Customer bankCustomer = this.bank
.searchCustomerBySsn(ITSOBank4Test.CUSTOMER_SSN);
// Verify an assertion
assertEquals(bankCustomer.getSsn(), ITSOBank4Test.CUSTOMER_SSN);
} catch (InvalidCustomerException e) {
e.printStackTrace();
}
In the foregoing example, the differences are marked in bold. In JUnit, each test
is implemented as a Java method that should be declared as public void and
should take no parameters. This method is then invoked from a test runner. In
previous JUnit releases, all the test method names had to begin with test..., so
the test runner could find them automatically and run them. In JUnit 4.x, this is no
longer required, because we mark the test methods with the @Test annotation.
assertEquals Asserts that two objects or primitives are equal. Compares objects
using equals method, and compares primitives using == operator.
assertNotSame Asserts that two objects do not refer the same object. Compares
objects using != operator.
assertSame Asserts that two objects refer to the same object. Compares objects
using == operator.
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. The full JUnit 4 API
documentation can be found here:
http://junit.sourceforge.net/javadoc_40/index.html
Example 21-3 Simple JUnit 3.8.1 test suite class: Using constructor
package itso.rad7.bank.test.junit;
import junit.framework.Test;
import junit.framework.TestSuite;
Example 21-4 Simple JUnit 3.8.1 test suite class: Using addTest method
package itso.rad7.bank.test.junit;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ITSOBank4Test.class})
public class All4Tests { }
The All4Tests class is a simple placeholder for the @RunWith and @SuiteClasses
annotations, and does not require a static suite method. The @RunWith
annotation tells the JUnit 4 test runner to use the org.junit.runners.Suite class
for running the All4Tests class. The @SuiteClasses annotation allows you to
define which test classes to include in this suite and in which order. If you add
more than one test class, the syntax is:
@SuiteClasses({TestClass1.class, TestClass2.class})
Note: We are using JUnit 4.x in this chapter, because it is our goal to make
you familiar with the new features and supported technologies of Application
Developer V7.
The completed code for this section can also be imported from the
c:\7501code\zInterchangeFiles\junit\RAD7JUnit.zip project interchange file.
Note: Instead of adding a library, you can add a variable. Classpath variables
are an indirection to JARs with the benefit of avoiding local file system paths in
a classpath. This is needed when projects are shared in a team. To add a
variable to the RAD7JUnit project, do these steps:
Right-click the RAD7JUnit project and select Properties, or press
Alt+Enter.
Select Java Build Path and select the Libraries tab. Click Add Variable.
In the New Variable Classpath Entry dialog, there is a predefined variable
called JUNIT_HOME. This variable links to the JUnit 3.8.1 directory. But we
want to use JUnit 4.x. Therefore, we have to configure the variable. Click
Configure Variables.
Select the JUNIT_HOME variable and click Edit.
In the Edit Variable Entry dialog, click Folder, and navigate to the folder
.../plugins/org.junit4_4.1.0.1 and click OK.
Note that you could also create a new variable (JUNIT4_HOME) pointing to
the JUnit4 folder (../plugins/org.junit4_4.1.0.1).
Click OK to close the dialog.
In the New Variable Classpath Entry dialog, select the JUNIT_HOME (or
JUNIT4_HOME) variable and click Extend. Select the junit-4.1.jar file and
click OK.
Click OK to close the Properties dialog.
Note: A stub is a skeleton method so that you can add the body of the
method yourself.
The wizard generates the ITSOBankTest.java and opens the file in the Java
editor.
Note: The JUnit framework calls the setUp method before each test method.
The ITSOBank class is implemented as a singleton (only one object of this
class exists). Therefore, you get always the same ITSOBank object, when you
call the static getBank method. When the setUp method gets called a second
time, you would get the same ITSOBank instance as in the first call.
For example, if you have removed all the customers in the first test method,
the ITSOBank object that you get in the second call of the setUp method would
be empty, because removing a customer from the bank closes automatically
all of his accounts. Therefore, it can be useful to call a kind of clean up service
in the tearDown method to reset the ITSOBank instance. In our example this is
not needed.
// Verify assertions
Assert.assertEquals(this.bank.searchAccountByAccountNumber(
ITSOBankTest.ACCOUNT_NUMBER_1).getBalance().doubleValue(),
account1AmountBeforeTransfer.subtract(transferAmount)
.doubleValue(), 0.00D);
Assert.assertEquals(this.bank.searchAccountByAccountNumber(
ITSOBankTest.ACCOUNT_NUMBER_2).getBalance().doubleValue(),
account2AmountBeforeTransfer.add(transferAmount)
.doubleValue(), 0.00D);
} catch (ITSOBankException e) {
e.printStackTrace();
Assert.fail("Transfer failed: " + e.getMessage());
}
}
// Invoke a method
this.bank.transfer(ITSOBankTest.ACCOUNT_NUMBER_1,
ITSOBankTest.ACCOUNT_NUMBER_2, transferAmount);
} catch (InvalidAccountException e) {
e.printStackTrace();
Assert.fail("Transfer failed: " + e.getMessage());
} catch (InvalidTransactionException e) {
Important: We found that the New JUnit Test Suite wizard does not allow us
to select between JUnit 3.8.1 and JUnit 4.x test suites. The wizard can only be
used for JUnit 3.8.1 test suites and therefore, it only lets you add JUnit 3.8.1 or
lower JUnit version test cases. This is a known Eclipse bug:
http://bugs.eclipse.org/bugs/show_bug.cgi?id=155828
We had to create the JUnit test suite for the example manually. We provide
below a step-by-step guide to create a test suite for JUnit 3.8.1 test cases.
This guide is just given for completeness and cannot be used for the example.
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ITSOBankTest.class})
public class AllTests {}
In our example we only have added a single test class, and thus a test suite is
not required. However, as you add more and more test cases, a test suite
quickly becomes a more practical way to manage your unit testing.
Figure 21-3 JUnit view: Both test methods passed the assert verifications
Tip: To run the same test again, click in the JUnit view toolbar.
Double-clicking the entry in the Failure Trace list takes you to the specified line
in the specified Java source file. This is the line where to set a breakpoint and
start debugging the application. For details how to debug an application, refer
to Chapter 22, “Debug local and remote applications” on page 1041.
Correct the process method of the Credit class, by undoing the change we
made before.
Note: If you imported the final RAD7JUnit project from the sample code and you
want to create this example on your own, delete the itso.rad7.bank.test.tptp
package.
In the JUnit Test Definition dialog, enter the following data and click Finish.
– Enter or select the parent folder:
RAD7JUnit/src/itso/rad7/bank/test/tptp
– Name: ITSOBankTest
Note: In the previous step we enter the name and location of the source
code, while in this step we enter the name and location of the TPTP Test
(the model). By default, they are identical.
The JUnit Test Suite editor opens and you can create and remove methods on
a JUnit test, and control how those methods are invoked. Three tabs are
visible: Overview, Test Methods, and Behavior.
In the Test Methods tab, click Add and enter testSearchCustomerBySsn in
the name field.
In the Behavior tab, click Add and select Loop. Select the Loop 1, click Add
again, select invocation, select the testSearchCustomerBySsn method and
click OK.
At this point the Behavior tab looks as shown in Figure 21-6.
import junit.framework.Test;
import .....;
import itso.rad7.bank.exception.InvalidCustomerException;
import itso.rad7.bank.ifc.Bank;
import itso.rad7.bank.impl.ITSOBank;
import itso.rad7.bank.model.Customer;
/**
/**
* Constructor for ITSOBankTest.
* @param name
*/
public ITSOBankTest(String name) {
super(name);
}
/**
* Returns the JUnit test suite that implements the <b>ITSOBankTest</b>
* definition.
*/
public static Test suite() {
HyadesTestSuite iTSOBankTest = new HyadesTestSuite("ITSOBankTest");
iTSOBankTest.setArbiter(DefaultTestArbiter.INSTANCE).setId(
"DDB9E1EA6622C91ECCFC7050406611DC");
loop1.addTest(new ITSOBankTest("testSearchCustomerBySsn").setId(
"DDB9E1EA6622C91EEFA8C810406611DC").setTestInvocationId(
"DDB9E1EA6622C91E109E6F20406711DC"));
return iTSOBankTest;
}
/**
* @see junit.framework.TestCase#setUp()
*/
protected void setUp() throws Exception {
this.bank = ITSOBank.getBank();
}
/**
* @see junit.framework.TestCase#tearDown()
*/
protected void tearDown() throws Exception {}
/**
* testSearchCustomerBySsn
Note: Notice that the Import JUnit test to TPTP dialog does not allow us to
select the ITSOBankTest.java or ITSOBankTest.java test cases that are
also in the itso.rad7.bank.test.junit package. The reason is that those
test cases are JUnit 4.x based and TPTP cannot handle JUnit 4.x.
To analyze the test results, double-click the test execution result (Figure 21-9).
Note: To view the reports, you have to install the Scalable Vector Graphics
(SVG) browser plug-in. You can get this free viewer from the Adobe® Web
site:
http://www.adobe.com/svg/viewer/install/main.html
The objective of Cactus is to lower the cost of writing tests for server-side
code. Cactus supports so-called white box testing of server-side code. It
extends and uses JUnit.
In addition to providing a common framework for test tools and support for JUnit
test generation, TPTP includes features allowing you to test Web applications.
The completed code for this section can also be imported from the
C:\7501code\zInterchangeFiles\junit\RAD7JUnitWebTest.zip project
interchange file.
Recording a test
To create a simple HTTP test, do these steps:
Note: To make sure your recording accurately captures HTTP traffic, clear the
browser cache.
Tip: The browser used for recording can be set in Window → Preferences →
Test → HTTP Recording.
If your recording
is empty, refer to
the Important
box below
Important: For Internet Explorer 7.0 you must use the IP-address to run the
Web application: http://<ip-address>:9080/RAD7BankBasicWeb/. No
recording is produced when using http://localhost:9080/...
For Firefox 2.0, you must first configure the network settings: Select Tools →
Options → Advanced → Network. Click Settings and select Auto-detect
proxy settings for the network.
You can import the recording files into the RAD7JUnitWebTest project from:
C:\7501code\junit\webtestrecording
The problem is a known Eclipse issue and there are a few discussions in
the following two defects:
https://bugs.eclipse.org/bugs/show_bug.cgi?id=128613
https://bugs.eclipse.org/bugs/show_bug.cgi?id=139699
Do not get confused: As you can see when we analyze the test results,
100% of the tests passed. That is because none of the requests returned
an HTTP code of 400 or greater—even those which threw an exception.
But in the console you can see that an unexpected call to the
/showException.jsp has occurred. If you want to see the exception
message on the console, you have to modify the constructor of the
itso.rad7.bank.exception.ITSOBankException class in the RAD7Java
project:
public ITSOBankException(String message) {
super(message);
printStackTrace();
System.err.println(message);
}
You can also generate the Test Pass report in the same way as for the basic
JUnit tests.
More information
For more information, consult the Application Developer Help facility and expand
Testing functionality and performance → Testing applications (Eclipse
Hyades project).
In this chapter, the main features available to developers for debugging are
described, the new debug tooling features included with Rational Application
Developer v7.0 are introduced, and two examples of how to use the debugger
are provided. The first demonstrates debugging a Web application running on a
local test environment, and the second shows how to debug an application
running on a remote Web Application Server server. Finally, a list of potential
sources for further information is supplied.
By default, when debugging Java, the views shown in the Debug perspective are
as follows:
Source view—Shows the file of the source code that is being debugged,
highlighting the current line being executed.
Outline view—Contains a list of variables and methods for the code listing
shown in the display view.
Debug view—Shows a list of all active threads, and a stack trace of the
thread that is currently being debugged.
Servers view—Useful if the user wants to start or stop test servers while
debugging.
Variables view—Given the selected source code file shown in the Debug
view, the Variables view shows all the variables available to that class and
their values.
Breakpoints view—Shows all breakpoints in the current workspace and
gives a facility to activate/de-activate them, remove them, change their
properties, and to import/export a set of them to other developers.
Display view—Allows the user to execute any Java command or evaluate an
expression in the context of the current stack frame.
Expressions view—During debugging, the user has the option to inspect or
display the value of expressions from the code or even valuate new
expressions. The Expressions view contains a list of expressions and values
which the user has evaluated and then selected to track.
Console view—Shows the output to System.out.
Tasks view—Shows any outstanding source code errors, warnings or
informational messages for the current workspace.
Error Log—Shows all errors and warnings generated by plug-ins running in
the work space.
Debug functions
From the Debug view, you can use the functions available from the icon bar to
control the execution of the application. The following icons are available:
Resume (F8): 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
from the Debug view.
Step Into (F5): Steps into the highlighted statement.
Using these buttons and the information shown in the various views available in
the Debug perspective, it should be possible to debug most problems.
To add new Java package to the Step Filter/Step Debug feature in the Debug
view, do these steps:
Select Window → Preferences.
Expand Run/Debug → Java and Mixed Language Debug → Step Filters.
Click Add Filter.
Enter the new package or class you want to filter out and click OK.
The Step Filter/Step Debug feature can be toggled on and off by clicking Step
Filter ( ) in the Debug view.
Drop to Frame
The drop-to-frame feature allows the control of an application to be reversed
back to a previously executed line of code. This feature is available when
debugging Java applications and Web applications running on WebSphere
For example, if a developer wants to test a method with the minimum and
maximum permitted values for a given parameter, a breakpoint can be added at
the end of the method, and the drop-to-frame feature can be used to back up the
control of the application to the start of the method, change the parameters, and
run it again.
When running an application in the Debug perspective, the stack frame can be
seen in the Debug view (Figure 22-2). Drop to frame allows you to back up your
application’s execution to previous points in the call stack by selecting the desired
method level from within the Debug view and then clicking Drop To Frame .
This moves the control of the application to the top of the method selected in the
Debug view.
Drop to Frame
XSLT debugging
XSL (EXtensible Stylesheet Language) Transformations (XSLT) is a language for
transforming XML documents into XHTML or other XML documents. It is a
declarative language expressed in XML and provides mechanisms to match tags
from the source document to templates (similar to methods), store values in
variables, basic looping/code branching and invoke other templates in order to
build up the result document.
Also, XSLT files can use templates stored in other files and it is possible for XSLT
files to become complicated. Application Developer features a full-featured XSL
transformation debugger, and XSLT files can be debugged using a similar set of
tools to that available for Java. Figure 22-3 shows the Debug perspective when
debugging XSLT. From the Debug perspective, the user can step through the
XSLT file and the source XML and watch the result XML being built element by
element.
Result XML
To launch a debugging session for a XSLT file and its source XML file, simply
highlight both files on the Project Explorer, and from the context menu, select
Debug As → XSLT Transformation. This action steps into the first line of the
XSL file, and from there, debugging can continue. The debug launch
configuration window (from the Context Window use Debug As → Debug)
allows the user to configure dependent files (both XSLT and Java) and other
settings to guide the XSLT debugging. These configurations can then be saved to
make launching the debugging quicker in the future.
Finally, it is also possible to debug Java code called from the XSL file. To do this
you must use the launch configuration window and make sure that the Class path
tab includes the projects that contain the Java code to be debugged. When
stepping through the XSLT debugger, it will be possible to Step Into the call to the
Java method.
Remote debugging
The debugger provided with Application Developer allows a programmer to
attach to a Java application running on a remote machine and control its
execution. This is particularly useful when debugging an application that cannot
be run on the development machine.
When starting the debug session, use Debug As → Debug (from the Project
Explorer context menu) and create a new configuration for Remote Java
Application. Make sure the Host and Port are configured for the target machine
The Debug UI daemon is a feature available from the toolbar of the Debug view
which allows developers to debug XSL transformations which are invoked by a
WebSphere application.
Pull-down menu
with Debug UI
Daemon options
When enabled, the daemon listens on a port (which you can configure) and if
during the WebSphere debug session the application invokes an XSL
transformation, Application Developer will step into the XSLT file and debugging
continues. You can disable the feature by selecting the appropriate option from
the drop-down menu in the Debug view.
The debug example includes the following tasks to demonstrate the debug
tooling:
Importing the sample application
Running the sample application in debug mode
Setting breakpoints in a Java class
Watching variables
To import the ITSO RedBank JSP and servlet Web application project
interchange file, do these steps:
In the Web perspective select File → Import → Project Interchange and
click Next.
In the Import Projects screen click Browse to locate the file:
c:\7501code\zInterchangeFiles\webapps\RAD7BankBasic.zip
Select the projects that are not in the workspace, and click Finish.
In this example, we set a breakpoint where the logic tests that the amount to
withdraw does not exceed the amount that exists in the account.
Tip: You can use the Outline view or expand Account.java in the Project
Explorer to find the processTransaction method quickly in the source
code.
Place the cursor in the gray bar (along the left edge of the editor area) on the
following line of code in the processTransaction method:
if (newBalance.doubleValue() < 0) {
Double-click to set a breakpoint marker (Figure 22-6).
Breakpoint
It should now be possible to run the application and trigger the breakpoint. Note
that it is not necessary to restart the Application Server for the new breakpoint to
work.
Note: Within the Debug view, it is now possible to show only the
suspended threads, as described in “Summary of new features in V7.0” on
page 1049. To do this, toggle the Show Running Threads option on the
context menu of the Debug view.
Watching variables
The Variables view displays the current values of the variables in the selected
stack frame (Figure 22-6).
In the variables view expand this and select balance. Although balance is of
type BigDecimal, a string representation of its value is shown in the bottom
section of the window.
Follow these steps to see how you can track the state of a variable, while
debugging the method:
Click Step Over in the Debug view (or press F6) to execute the current
statement.
Click Step Over again and the balance is updated. Note that the color of
balance changes in the Variables view.
It is possible to test the code with some other value for any of these instance
variables; a value can be changed by selecting Change Value from its context
menu. An entry field opens where the value can be changed.
To view the value of an expression within the code, select the expression (for
example, newBalance.doubleValue() in the breakpoint line), right-click, and
select Inspect. The result opens in a pop-up window showing the value
(Figure 22-9).
To move the results to the Expressions view (Figure 22-10) so that the value of
the expression can continue to be monitored, press Ctrl+Shift+I.
You can also highlight any expression in the source code, right-click, and
select Watch (or Inspect). The result is shown in the Expressions view.
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.
Alternatively, once they have been created, the breakpoints can be enabled and
disabled from the Breakpoints view (Figure 22-12). If the breakpoint is
un-selected in the Breakpoints view, it is skipped during execution.
To disable or enable all breakpoints, click the Skip All Breakpoints icon, as seen
in Figure 22-12.If this option is selected then all breakpoints are skipped during
execution.
It is possible to export a set of breakpoints, including the conditions and hit count
properties so that they can be shared across a development team. To do this,
from the context menu of the Breakpoints view select Export Breakpoints and
the breakpoints are saved as a bkpt file to the selected location.
Note that you do not see the Web page automatically in the Debug perspective.
Click the view with the World icon (in the same pane as the source code) to see
the resulting Web page. Alternatively, switch to the Web perspective.
Note that the Breakpoint properties are also available for JSPs from the context
menu. These share the same features as Java breakpoints with the exception
that content assist is not available in the breakpoint condition field.
Once a breakpoint is hit, you can analyze variables and step through lines of
the JSP code. The same functions available for Java classes are available for
JSP debugging. The difference is that the debugger shows the JSP source
code and not the generated Java code.
The JSP variables are shown in the Variables view. Note that the JSP implicit
variables are also visible, and it is possible to look at things such as request
parameters or session data (see Figure 22-15)
Step over the lines within the JSP by pressing the F6 key. Note that the
debugger will skip any lines with only HTML code.
Note the change in the variables view. Expand JSP Implicit Variables →
pageContext → page_attributes and select varAccounts, which is the
variable in the <c:forEach var="varAccounts"...> loop:
Account 004-999000777: --> Current balance: $850.00
Transactions:
1. Debit: --> Amount $50.00 on 2007-07-30 09:27:36.078
2. Debit: --> Amount $50.00 on 2007-07-30 09:44:54.125
You can perform debugging activities on the Account class or click the Resume
icon to finish the example.
Note: For the <hostname> it is sufficient to use the IP address of the machine
running WebSphere Application Server. Run the command ipconfig from the
command line to determine this. Note that our remote server runs on a
different set of ports.
From the Administration Console, expand Applications and click Install New
Application.
Select Local file system and click Browse and locate the generated EAR file
(C:\temp\RAD7BankBasicEAR.ear).
Accept the default options for the other fields an click Next.
In Step 1, select Precompile JavaServer Pages files, and click Next.
In Step 2, click Next.
In Step 3 (Summary), accept the defaults and click Finish.
You should see a screen showing the progress of the installation. After a short
time, the following message will be displayed if the application is successfully
deployed:
Application RAD7BankBasicEAR installed successfully.
Click Save directly to the master configuration link URL.
Navigate to the Applications → Enterprise Application. Select
RAD7BankBasicEAR and click Start.
Click Logout.
Verify the application is working properly by opening a Browser and
navigating to the following URL of the target machine:
http://<hostname or IPaddress>:9080/RAD7BankBasicWeb/
Note: The value of the JVM debug port is needed when connecting to the
application server with the debugger. The default value is 7777; in our case
the server used port 7779.
7777 or 7779
– On the Source tab expand the Default folder. Note that about halfway
down is the RAD7BasicBankWeb project. This lets the debugger know where
the source code is.
The debug perspective now shows the Remote debugger running in the Debug
view, as shown in Figure 22-17. The debugger is waiting for a breakpoint to be
triggered. Note that clicking the Disconnect icon ( ) stops the debugging.
local server
remote server
After that you can start a remote debug instance using localhost as the host
name and port 7777 (or the correct port, such as 7779). This will attach to the
test application server and allow the user to perform all the usual debugging
facilities.
From the main index page, select the redbank tab, enter 444-44-4444 as the
customer ID and click Submit. In the List Accounts page, select an account
number and in the Account Details page select Withdraw and enter 100 in the
amount field. Click Submit.
This causes Application Developer to prompt the user to switch to the Debug
perspective (if not already there).
Figure 22-18 Debug perspective after being triggered by a remote application breakpoint
Also note that the browser where the request was performed is frozen, waiting a
response from the server.
In the Debug perspective, click Resume ( ) and the transaction completes and
the Account Details page is displayed in the browser.
Highlight the remote debugging instance and click Disconnect to finish the
debugging session.
Jython debugger
The Jython debugger enables you to detect and diagnose errors in Jython script
that is used for WebSphere Application Server administration. With the
debugger, you can control the execution of your code by setting line breakpoints,
suspending execution, stepping through your code, and examining the contents
of variables. (Note that variable values cannot be changed in Jython.)
The Jython debugger only supports debugging of script that are running on
WebSphere Application Server Version 6.1.
You can debug a Jython script that has been developed or imported into a Jython
project. When you are debugging a Jython script, you can set line breakpoints.
When the workbench is running the script and encounters a breakpoint, the
script temporarily stops running. Execution suspends at the breakpoint before
the script is executed, at which point you can check the contents of variables. You
can then step over (execute) and see what effect the statement has on the script.
Tip: To debug a Jython script, the server does not have to run in Debug mode.
The Jython debugger is very useful when you encounter errors in your Jython
scripts. Run the script in debug mode, without having to restart the server.
This chapter provides an introduction to the concepts and features of Ant within
IBM Rational Application Developer V7.0. The focus of the chapter is to
demonstrate how to use the Ant tooling included in Rational Application
Developer to build projects (applications).
The Ant build operations are controlled by the contents of the XML-based script
file. This file not only defines what operations to perform, but also defines the
order in which 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, 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 when a build is finished.
Ant tasks
A comprehensive set of built-in tasks is supplied with the Ant distribution. The
tasks that we use in our example are as follows:
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
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
We use a simple Java project (RAD7Ant) and class (HelloAnt) for this example.
To import the HelloAnt class into the RAD7Ant Java project, do these steps:
Right-click on the RAD7Ant project and select New → Package.
In the New Package dialog, enter itso.rad7.ant.hello for the Name field.
Right-click on the itso.rad7.ant.hello package and select Import.
In the Import dialog, select General → File System, and click Next.
In the File System dialog, select c:\7501code\ant\ as directory and select
HelloAnt.java (Figure 23-1).
Click Finish.
Double-click the build.xml file to open it in the Ant editor. Copy and paste the
text in c:\7501code\ant\build.txt into the build.xml file.
We now walk you through the various sections of this file, and provide an
explanation for 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.
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 c:\temp\build and
c:\temp\RAD7Ant directories.
Build targets
The build file contains four build targets:
init
compile
dist
clean
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.
<!-- 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}">
<manifest>
<attribute name="Main-Class"
value="itso.rad7.ant.hello.HelloAnt"/>
</manifest>
</jar>
</target>
Note that the build.xml file does not call for this target to be executed. It has to
be specified when running Ant.
Content assist
To access the content assist feature in the Ant editor, do these steps:
Open the Java perspective.
Expand the RAD7Ant project.
Double-click build.xml to open the file in an editor.
Place the cursor in the file and enter <prop, and then press Ctrl+Spacebar.
Code snippets
Application Developer V7 provides the ability to create code snippets that contain
commonly used code to be inserted into files rather than typing the code in every
time.
Click Browse next to Custom, select Ant Buildfiles for Content Type
Selection, and click OK to return to the Customize Palette dialog.
In the Customize Palette dialog, select New → New Item.
In the Unnamed Template dialog, enter the following items:
– Name: Comment Tag
– Click New in the variables section.
– Variable Name: comment
– Template Pattern: <!-- ${comment} -->
Click OK in the Customize Palette dialog.
Problems view
Application Developer offers you the Problems view for the Ant file. The editor
presents an error in the view by placing a red X on the left of the line with the
problem as well as a line marker in the file on the right of the window, as shown in
Figure 23-10. The Problems view lists the problems as seen in Figure 23-11.
Each Ant build file can 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 example,
the default target is dist. The dependencies between the targets are illustrated in
Figure 23-12.
dist clean
depends on
compile
init
Running Ant
Ant is a built-in function to 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.
Note: Because the dist target depends on compile, even if you only select
dist, the compile target is executed as well.
The Console shows that Ant has created the c:\temp\build directory, compiled
the source files, created the c:\temp\RAD7Ant\lib directory, and generated a
JAR file (helloant-20070605.jar).
Rerun Ant
If you launch Ant again with the same target selected, Ant will not do anything at
all, because the c:\temp\build and c:\temp\RAD7Ant\lib directories were
already created, and the class files in the build directory were already up-to-date.
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 23-15).
Alternatively you can click Order to change the execution order.
The actual EAR being tested, and its supporting 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.
Since these individual projects can be anywhere on the development machine,
absolute path references are used.
To import the RAD7EJB.zip project interchange file containing the sample code
into Rational Application Developer, do these steps:
Open the J2EE perspective Project Explorer view.
Select File → Import.
Expand the Other folder and select Project Interchange from the list of
import sources and then click Next.
Click Select All to select all projects and then click Finish.
Repeat the import for c:\7501code\zInterchangeFiles\ejb\RAD7EJBWeb.zip,
and select both projects (RAD7EJBWeb and RAD7EJBWebEAR).
After importing the two project interchange files, you have the following projects:
– RAD7EJBEAR
– RAD7EJB
– RAD7EJBClient
– RAD7EJBJava
– RAD7EJBWeb
– RAD7EJBWebEAR
The build.xml script includes the following Ant targets, which correspond to
common J2EE application build:
deployEjb: This generates the deploy code for all EJBs in the project.
buildEjb: This builds the EJB project (compiles resources within the project).
buildWar : This builds the Web project (compiles resources within the project).
buildEar : This builds the Enterprise Application project (compiles resources
within the project).
exportEjb: This exports the EJB project to a jar file.
exportWar : This exports the Web project to a WAR file.
exportEar : This exports the Enterprise Application project to an EAR file.
buildAll: This invokes the buildEjb, buildWar, and buildEar targets.
exportAll: This invokes the exportEjb, exportWar, and exportEar targets to
create the RAD7EJBEAR.ear used for deployment.
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, whether debug statements should be included in the
generated class files, and whether 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.
Note: From the content menu for the Ant build script, the following two build
options exist:
2 Ant Build: This will invoke the default target for the Ant build. In our
example, this is the Total target, which in turn invokes buildAll and
exportAll targets.
3 Ant Build: This will launch a dialog where you can select the targets
and order, and provide parameters, as seen in Figure 23-16.
Figure 23-16 Launch Ant to build and export a J2EE project (EAR)
The Console view displays the operations performed and their results.
The runAnt.bat file included with Rational Application Developer is located in the
following directory (for example, our <rad_home> directory is found in c:\IBM\SDP70):
<rad_home>\bin
To create a headless Ant build script for J2EE project, do these steps:
Copy the runAnt.bat file to a new file called itsoRunAnt.bat.
:java
if not $%JAVA_DIR%$==$$ goto workspace
set JAVA_DIR=%AST_DIR%\jdk\jre\bin
:workspace
if not $%WORKSPACE%$==$$ goto check
REM #######################################################
REM ##### you must edit the "WORKSPACE" setting below #####
REM #######################################################
REM *********** The location of your workspace ************
set WORKSPACE=C:\workspaces\RADv7proGuide
There are several build output files, which can be found in the
c:\RAD7EAR_workdir\dist directory:
– RAD7EJBWeb.war—RAD7EJBWeb project
– RAD7EJB.war—RAD7EJB project
– RAD7EJBEAR.ear—RAD7EJBEAR project with all the dependent projects
included
In this section we review the following concepts of the J2EE and WebSphere
deployment architecture:
Common deployment considerations
J2EE application components and deployment modules
Preparing for the deployment of the EJB application
WebSphere deployment architecture
Java and WebSphere class loader
Deployment modules
The J2EE deployment components are packaged for deployment as modules:
Web module
EJB module
Resource adapter module
Application client module
Deployment descriptors
Information describing a J2EE application and how to deploy it into a J2EE
container is stored in XML files called deployment descriptors. An EAR file
normally contains multiple deployment descriptors, depending on the modules it
contains. Figure 24-1 shows a schematic overview of a J2EE EAR file. In this
figure the various deployment descriptors are designated with DD after their
name.
The deployment descriptor of the EAR file itself is stored in the META-INF
directory in the root of the EAR and is called application.xml. It contains
information about the modules making up the application.
The deployment descriptors for each module are stored in the META-INF directory
of the module and are called web.xml (for Web modules, actually in WEB-INF),
ejb-jar.xml (for EJB modules), ra.xml (for resource adapter modules), and
application-client.xml (for Application client modules). These files describe
the contents of a module and allow the J2EE container to configure servlet
mappings, JNDI names, and so forth.
Classpath information, specifying which other modules and utility JARs are
needed for a particular module to run, is stored in the manifest.mf file, also in the
META-INF directory of the modules.
For example, if you open the EJB deployment descriptor, you will see settings
that are stored across multiple deployment descriptors for the EJB module,
including:
EJB deployment descriptor, ejb-jar.xml
Extensions deployment descriptor, ibm-ejb-jar-ext.xmi
Bindings file, ibm-ejb-jar-bnd.xmi
Access intent settings, ibm-ejb-access-bean.xmi
When you have made changes to a deployment descriptor, save and close it.
Developer Production
Rational WebSphere Application
Application Server
Developer
Deploy EAR Application
Configure
Application
Server
Application
Configure
Deploy EAR Application
Deploy Server
WebSphere Application
Server
(RAD Test Environment) Application
Application Server Toolkit Externally
(AST) Packaged
EAR
WebSphere profiles
Application Server V6.0 introduced the concept of WebSphere profiles. It has
been split into two separate components:
A set of shared read-only product files
A set of configuration files known as WebSphere profiles
Note: This function is similar to the wsinstance command that was available in
Application Server V5.x, creating multiple runtime configurations using the
same installation.
In the ibmconfig directory are the well-known directories for a WebSphere cell
configuration (Figure 24-5 on page 1113). The enhanced EAR feature provides
an extension of the J2EE EAR with additional configuration information for
resources typically required by J2EE applications. This information is not
mandatory to be supplied at packaging time, but it can simplify the deployment of
applications to Application Server for selected scenarios.
The Enhanced EAR editor can be used to edit several WebSphere Application
Server V6 specific configurations, such as JDBC providers, data sources, class
loader policies, substitution variables, shared libraries, virtual hosts, and
authentication settings. The configuration settings can be made simply within the
editor and published with the EAR at the time of deployment.
The upside of the tool is that it makes the testing process simpler and repeatable,
since the configurations can be saved to files and then shared within a team’s
repository. Even though it will not let you configure every possible runtime
setting, it is a good tool for development purposes because it eases the process
of configuring the most common ones.
When you change a configuration using the Enhanced EAR editor, these
changes are made within the application context. The deployer can still make
changes to the EAR file using the Application Server Toolkit (AST), but it still
requires a separate tool. Furthermore, in most cases these settings are
dependent on the node the application server is installed in anyway, so it might
not make sense to configure them at the application context for production
deployment purposes.
Table 24-1 lists the supported resources that the enhanced EAR provides and
the scope in which they are created.
Figure 24-4 shows the view of the Deployment tab of the Application Deployment
Descriptor. This is where the enhanced EAR information can be configured in
Application Developer. It displays the configured data source (RAD7DS) and its
JDBC Provider (Derby JDBC Provider (XA)).
Note that in the first section (Data Sources) you have to select a JDBC provider
to see the associated data sources, and after selecting a data source you can
see the properties of that data source.
Figure 24-5 displays the contents of the resources.xml file that is part of the
enhanced EAR information stored in:
ibmconfig/cells/defaultCell/applications/defaultApp/deployments/defaultApp
You can also notice that in the ibmconfig directory are the well-known directories
for a WebSphere cell configuration. The XML editor of Application Developer
displays the configuration contents for the RAD7DS data source and the Derby
JDBC Provider (XA).
Note: For more detailed information and an example of using the WebSphere
enhanced EAR, refer to these sources:
Packaging applications chapter in the WebSphere Application Server V6.1:
Systems Management and Configuration, SG24-7304
IBM WebSphere Application Server V6.1 Info Center, found at:
http://publib.boulder.ibm.com/infocenter/ws60help/index.jsp?topic=/com.ib
m.websphere.base.doc/info/welcome_base.html
An example of defining a data source using the Enhanced EAR editor can be
found in “Creating a data source in the enhanced EAR” on page 985.
For example, you can place full J2EE applications (EAR files), application
modules (WAR files, EJB JAR files), or application artifacts (Java source files,
Java class files, images, and JSPs) into a configurable location on your file
system, referred to as the monitored, or project, directory. The rapid deployment
tools then automatically detect added or changed parts of these J2EE artifacts
and perform the steps necessary to produce a running application on an
application server.
There are two ways to configure the monitored directory, each performing
separate and distinct tasks (as shown in Figure 24-6):
Free-form project
Automatic application installation project
Application - Installed,
Restarted, Reinstalled
or Uninstalled
Free-Form Project
Change
Java Add J2EE Artifacts to Detection /
Servlet, Source WRD workspace - Trigger
JSP, J2EE project process
Static
File etc. structure not
(Image, required
WRD
HTML)
User creates individual
J2EE artifacts (Java
Source, Web resources,
etc.) WRD generates
J2EE artifacts
and package
With the free-form project approach, you can place in a single project directory
the individual parts of your application, such as Java source files that represent
servlets or enterprise beans, static resources, XML files, and other supported
application artifacts. The rapid deployment tools then use your artifacts to
automatically place them in the appropriate J2EE project structure, generate any
additional required artifacts to construct a J2EE-compliant application, and
deploy that application on a target server.
The advantage of using a free-form project is that you do not have to know how
to package your application artifacts into a J2EE application. The free-form
project takes care of the packaging part for you. The free-form project is suitable
when you just want to test something quickly, perhaps write a servlet that
performs a task.
The automatic application installation project allows you to quickly and easily
install, update, and uninstall J2EE applications on a server. If you place EAR files
in the project directory, they are automatically deployed to the server. If you
delete EAR files from the project directory, the application is uninstalled from the
server. If you place a new copy of the same EAR file in the project directory, the
The rapid deployment tools can be configured to deploy applications either onto
a local or remote WebSphere Application Server.
The Extensions class loader is the parent for the System class loader. The
Bootstrap class loader is the parent for the Extensions class loader. The class
loaders hierarchy is shown in Figure 24-7.
If the System class loader has to load a class, it first delegates to the Extensions
class loader, which in turn delegates to the Bootstrap class loader. If the parent
class loader cannot load the class, the child class loader tries to find the class in
its own repository. In this manner, a class loader is only responsible for loading
classes that its ancestors cannot load.
In Figure 24-8, the top box represents the Java (Bootstrap, Extension, and
System) class loaders. WebSphere does not load much here, just enough to get
itself bootstrapped and initialize the WebSphere extension class loader.
The RCP directory is intended to be used for fixes and other APARs that are
applied to the application server runtime. These patches override any copies of
the same files lower in the RP and RE directories. The RP directory contains the
core application server runtime files. The bootstrap class loader first finds
classes in the RCP directory, then in the RP directory. The RE directory is used for
extensions to the core application server runtime.
You can extend the list of directories and files loaded by the WebSphere
extensions class loaders by setting a ws.ext.dirs custom property to the Java
virtual machine settings of an application server.
EJB modules, utility JARs, resource adapters files, and shared libraries
associated with an application are always grouped together into the same class
loader. This class loader is called the application class loader. Depending on the
application class loader policy, this application class loader can be shared by
multiple applications (EAR) or be unique for each application (the default).
By default, Web modules receive their own class loader (a WAR class loader) to
load the contents of the WEB-INF/classes and WEB-INF/lib directories. The
default behavior can be modified by changing the application's WAR class loader
policy (the default being Module). If the WAR class loader policy is set to
Application, the Web module contents are loaded by the application class loader
(in addition to the EJBs, RARs, utility JARs, and shared libraries). The application
class loader is the parent of the WAR class loader.
It might make sense to break out just the lines of code that actually load the
native library into a class of its own and place this class on a static class loader.
This way you can have all the other code on a reloadable class loader.
There are several possible configurations in which our sample can be installed,
but we will use the following deployment process in this chapter:
Deploy ITSO Bank to a separate production IBM Application Server V6.0.
This scenario uses two nodes (developer node, application server node).
The sample for the working example environment consists of two nodes (see
Table 24-2 for product mapping):
Developer node—This node will be used by the developer to import the
sample code and package the application in preparation for deployment.
Application server node—This node will be used as the target server where
the enterprise application will be deployed.
Developer node
Microsoft Windows XP + Service Pack 2 + Critical fixes
and security patches.
Note: For detailed information on installing the required software for the
sample, refer to Appendix A, “Product installation” on page 1281.
Sample database
The ITSO Bank application are based on the ITSOBANK database. Refer to
“Setting up the ITSOBANK database” on page 1312 for instructions on how to
create the ITSOBANK database. You can either use the DB2 or Derby database.
For simplicity we chose to use the built-in Derby database in this chapter. But we
have also provided instructions for how to set up the ITSOBANK database using
DB2 UDB.
This value has to be configured for the databaseName resource property for the
RAD7DS data source we will define in the server (see “Configuring the data source
in the application server” on page 1128). Therefore, if you configure this location
in the data source, you will not have to set up a sample Derby database, as it has
already been done for you. Make sure that you test the data source connection.
Note: This section is only needed when using DB2. If you are using Derby
as your database server, this section is not required. This section describes
how to generate the EJB to RDB mapping for the DB2 Universal Database.
The following procedure describes how to generate the EJB to RDB mapping for
the enterprise beans when using DB2 for the ITSOBANK database.
Note: For more information, refer to “Preparing for the deployment of the EJB
application” on page 1120.
Note: There are many warnings for the RAD7EJB project in the Problems view.
These can be safely ignored, or you can filter the view and remove warnings
from the list.
Note: You can either use the EAR files exported in the previous section for
deployment to the target Application server, or alternatively use the solution
EAR files from the C:\7501code\jython directory of the sample code.
If the server is not running, start the server in any of these ways:
Use the Windows start menu. For example, select Start → Programs → IBM
WebSphere → Application Server V6 → Profiles → default → Start
server.
If you followed the instructions in Chapter 20, “Servers and server
configuration” on page 963 and installed a second WebSphere profile, you
can start that server from Application Developer.
An application server can also be started using the startServer server1
command in the bin directory where the server profile is installed, for
example:
C:\Program Files\IBM\WebSphere\AppServer\profiles\default\bin
<RAD_HOME>\runtimes\base_v61\profiles\AppSrv02\bin
If you configured the stand-alone application server as a Windows service,
you can start the server by starting its service.
Tip: You can also use the WebSphere Application Server v6.1 test
environment to go through the enterprise application installation dialogs.
However, make sure that the RAD7EJBEAR and RAD7EJBWebEAR applications are
removed from the server (right-click the server and select Add and Remove
Projects).
Must be configured
for DB2
Note: This step is required for DB2 UDB and optional for Derby.
This section describes how to configure the J2C authentication data, that is, the
database login and password to connect to the database system.
Select Security → Secure administration, applications, and
infrastructure.
Under the Authentication properties, select Java Authentication and
Authorization Service → J2C authentication data.
Click New, then specify these values (for DB2):
– Alias: dbuser
– User ID: db2admin (or the administrative password used to install)
– Password: <password>
Click Save to the master configuration when prompted.
For Derby, Step 2 is skipped (the class path is set correctly), and in Step 3:
Summary page, click Finish.
Derby
DB2
– Derby: Make sure that you enter the complete path of the database file.
For example, in our case this value is:
C:\7501code\database\derby\ITSOBANK
– DB2: Enter ITSOBANK as the database name, the driver type (4), the
host name of the server, and the connection port (default is 5000).
– Select Use this data source in container managed persistence (CMP).
This is required when using entity EJBs. Click Next.
In the summary page, verify the configuration information you entered for the
data source and click Finish.
Tip: If the connection fails, make sure that no connection is active from
Application Developer (in the Data perspective disconnect from ITSOBANK).
Select for
applications
with a Web
module with
JSPs
..................
Figure 24-19 Enterprise application installation: Map modules to the application servers
In the summary page, verify the configuration information for the new
enterprise application and click Finish to confirm (Figure 24-20).
The accounts page lists the accounts of the customer with their balance.
(Figure 24-25).
Overview of wsadmin
The wsadmin tool is a scripting client that has a command-line interface. It is
targeted towards advanced administrators. It provides extra flexibility that is
available through the Web based administrative console and helps make the
administration much quicker. It is primarily used to automate administrative
activities that can consist of several administrative commands and need to be
executed repetitively.
The wsadmin client uses the Bean Scripting Framework (BSF). The BSF allows
using a variety of scripting languages. Prior to WebSphere Application Server
V6, only one scripting language was supported, Java Command Language
(Jacl). Application Server now supports two languages: Jacl and Jython (or
jpython). Jython is the strategic direction. New tools in WebSphere Application
Server V6.1, Application Server Toolkit V6.1, and Rational Application Developer
V7 are available to help create scripts using Jython. A Jacl-to-Jython migration
tool is included with the Application Server.
There are five wsadmin objects that are available to use in the scripts:
AdminControl— This object is used to run operational commands.
AdminConfig—This object is used to create or modify Application Server
configurational elements.
AdminApp—This object is used to administer applications.
AdminTask—This object is used to run administrative commands.
Help—This object is used to obtain general help.
Overview of Jython
Jython is an implementation of the Python language. The wsadmin tool uses
Jython V2.1. The J in Jython represents its Java-like syntax. But Jython is also
quite different than Java or C++ syntax. Though like Java, Jython is a typed,
case-sensitive, and object-oriented language, but unlike Java it is an indentation
based language, which means that it does not have any mandatory statement
termination characters (like a semi-colon in Java), and code blocks are specified
by indentation. To begin a code block, you have to indent in, and to end a block,
indent out. Statements that expect an indentation level end in a colon (:).
Function
Function
Main Section
Note: We also have a section on Jython in Chapter 20, “Servers and server
configuration” in “Developing automation scripts” on page 993.
Preparation
In this section we create a Jython project and a Jython script in Application
Developer:
The RAD7EJBEAR.ear and RAD7EJBWebEAR.ear files are available in the
C:\7501code\deployment folder (where you exported the files), or you can use
the solution files from C:\7501code\jython.
Create a Jython project in Application Developer. If you followed the
instructions in Chapter 20, “Servers and server configuration” on page 963,
you already have this project, otherwise you can create it as follows:
– Click File → New → Project and the New Project wizard opens. Select
Jython → Jython Project and click Next.
– For the Project name, type RAD7Jython and click Finish.
Create a Jython script to deploy the ITSO Bank application:
– Select File → New → Other → Jython → Jython Script File and click
Next.
– In the Parent folder field, specify /RAD7Python, and for the File name, type
deployITSOBankApp.py.
– Click Finish to create the Jython script file.
In the Servers view, decide which server to use for testing. You can use the
test environment or the server profile you defined in Chapter 20, “Servers and
server configuration” on page 963.
Next we define the six functions. Note that the function code goes before the
main section.
Example 24-2 Create a JDBC provider using the template for Derby JDBC Provider (XA)
def createProvider():
prov = AdminControl.completeObjectName("name="+jdbcProv + ",
type=JDBCProvider,Server="+srvr + ",node="+nodeName + ",*")
if len(prov) > 0:
return
#endif
provName=['name',jdbcProv]
The code in Example 24-5 is the complete code for the useDSinCMP function.
The code in Example 24-6 is the complete code for the installApp function.
In the main section we had already defined variables that contain the complete
path of the EAR files and also their display names. Therefore, we can use these
variables as parameters and use the installApp function to install the
RAD7EJBEAR and RAD7EJBWebEAR applications:
installApp(webappEAR, webappEARName)
installApp(ejbappEAR, ejbappEARName)
The code in Example 24-7 is the complete code for the startApp function.
appMgr = AdminControl.queryNames
("node="+nodeName+",type=ApplicationManager,process="+srvr+",*")
AdminControl.invoke(appMgr,'startApplication',appName)
#enddef
Once again, we can use the global variables that contain the display name of
both applications and pass them as parameters to the startApp function:
startApp(ejbappEARName)
startApp(webappEARName)
Import this file into the RAD7Jython project (or copy/paste from Windows
Explorer into Application Developer. In addition to the logic discussed above,
the script has many comments and produces test output to the console (print
statements) so that the execution can be followed.
***** STEP 1 completed - The ITSO Derby JDBC Provider (XA) has been created
using the template. Config saved ..
Done creating the DS. Config saved ..
Done modifying the DS. Config Saved ..
The DS has been modified to use it in CMP. Config saved ..
More information
For more information on application deployment, refer to these resources:
WebSphere Application Server V6.1 Information Center:
http://publib.boulder.ibm.com/infocenter/wasinfo/v6r1/index.jsp?topic=/com.
ibm.websphere.base.doc/info/welcome_base.html
Understand WebSphere Extended Deployment:
http://www.ibm.com/developerworks/autonomic/library/ac-webxd/
Learn how to publish an enterprise application with WebSphere Application
Server and Application Server Toolkit, V6.1:
http://www.ibm.com/developerworks/edu/wes-dw-wes-hellowas.html
This chapter introduces the features, architecture, and process for profiling
applications using the profiling features of IBM Rational Application Developer
V7.0. We have included an example for basic memory analysis, execution time
analysis, and method code coverage analysis.
The types of problems that Application Developer profiling tooling can assist in
detecting include:
Memory usage problems
Performance bottlenecks
Excessive object creation
System resource limits
The profiling tools can be used to gather data on applications that are running:
Inside an application server, such as WebSphere Application Server
As a standalone Java application
On the same system as Application Developer
On a remote WebSphere Application Server with the IBM Rational Agent
Controller installed
In multiple JVMs
Profiling features
Within Application Developer, there are several analysis types. Each analysis
type includes associated views that provides the user with the ability to
concentrate on particular types of analysis such as memory leaks, performance
bottlenecks, and excessive object creation while profiling an application.
The following analysis types and their associated views are described in this
section:
Basic memory analysis
Execution time analysis
Method code coverage analysis
Probekit analysis
Probekit analysis
Probes are reusable Java code fragments that you write to collect detailed
runtime data about a program's objects, instance variables, arguments, and
exceptions. Probekit provides a framework on the Eclipse platform to help you
create and use probes. One common use of Probekit is to create lightweight
profilers that collect only the data developers are interested in.
A probekit file can contain one or more probes, with each containing one or more
probe fragments. These probes can be specified when to be executed or on
which program they will be used. The probe fragments are a set of Java methods
that are merged with standard boilerplate code with a new Java class generated
and compiled. The functions generated from the probe fragments appear as
static methods of the generated probe class.
There are two major types of probes available to the user (Table 25-4).
Method probe Probe can be inserted anywhere within the body of a method with the
class or jar files containing the target methods instrumented by the
BCI engine.
Callsite probe Probe is inserted into the body of the method that calls the target
method. The class or jar files that call the target instrumented by the
BCI engine.
Profiling architecture
The profiling architecture that exists in Application Developer is based on the
Eclipse Test & Performance Tools Platform (TPTP) project. More detailed
information on the Eclipse TPTP project can be found at:
http://www.eclipse.org/tptp/
In the past TPTP workbench users required the services of the standalone Agent
Controller before they could use the function in the Profiling and Logging
perspective and in the Test perspective. Even when the user tried to profile a
Java application locally or to run TPTP tests locally, the Agent Controller would
have to be installed on the local machine.
The Integrated Agent Controller is a new feature in the TPTP workbench, which
allows users to profile a Java application locally and to run a TPTP test locally
without requiring the standalone Agent Controller on the local machine. Profiling
on a remote machine or running a TPTP test on a remote machine still requires
the Agent Controller on that remote machine.
This feature is packaged in the TPTP runtime install image and therefore no
separate install step is required. The Integrated Agent Controller does not require
any configuration at all. Unlike the Agent Controller, which requires the user to
enter information, such as the path for the Java executable, the Integrated Agent
Controller determines the required information from the Eclipse workbench
during startup.
JDK
Service
Service
Service
JVMPI
Java Events
Profiler
Virtual
Agent
Machine Controls
The data collected by the agent is then sent to the Agent Controller, which then
forwards this information to Application Developer for analysis and visualization.
Note: There is only one instance of the J2EE Request Profiling agent that
is active in a process that hosts WebSphere Application Server.
There are many supporting views for the Profiling and Logging perspective. To
see the supporting views select Window → Show View → Other under Profiling
and Logging (Figure 25-2):
In the Advanced dialog expand Tester, and select Profiling and Logging
(Figure 25-4) and click OK.
Note: If you want to use the Probekit, you have to enable this capability by
selecting Probekit (Figure 25-4).
To import the ITSO RedBank JSP and servlet Web application project
interchange file, do these steps:
Open the Web perspective Project Explorer view.
Select File → Import.
In the Import dialog, select Project Interchange and click Next.
In the Import Projects dialog, click Browse and locate the file:
c:\7501code\zInterchangeFiles\webapps\RAD7BankBasic.zip
Select the RAD7BankBasicEAR, RAD7BankBasicWeb, and RAD7Java
projects, and click Finish.
To publish and run the sample application on the WebSphere Application Server
V6.1 test server, do these steps:
Open the Web perspective Project Explorer view.
Expand RAD7BankBasicWeb → WebContent.
Right-click index.html and select Run As → Run on Server.
In the Run on Server dialog, select Choose an existing server, select
WebSphere Application Server v6.1, and click Finish.
This operation will start the server and publish the application to the server. The
index.html page is displayed in a Web browser.
It takes a while to start the server in profiling mode. In the Servers view you
notice that the status of the server is changed to Profiling .
Select [PID: xxxx] and click to move the PID to the Selected agents
pane.
Select Local Direct Connection and click Test Connection. You receive a
successful message.
Select the Agents tab. Select [PID: xxxx] and click to move the PID to
the Selected agents pane (this is the same as Figure 25-5 on page 1166).
Select the Monitor tab and expand Java Profiling. Select Basic Memory
Analysis, Execution Time Analysis, and Method Code Coverage
(Figure 25-6 on page 1167). Configure Basic Memory Analysis and Execution
Time Analysis (Figure 25-7 on page 1167 and Figure 25-8 on page 1168).
In the Destination tab, you can see that a ProfileProject is created.
Click Apply, then click Profile.
Switch perspective when prompted. The agent appears in the Profiling
Monitor view (Figure 25-9 on page 1168).
Note: This step requires that you have published the project to the server as
described in “Publishing and running sample application” on page 1165.
To collect data, we will display the accounts of one customer, run a debit and a
credit transaction, list the transactions, and update the customer name:
Enter the following URL to launch the application in a Web browser:
http://localhost:9080/RAD7BankBasicWeb/index.html
In the RedBank home page, click redbank.
In the Login page, enter 222-22-2222 in the customer SSN field and click
Submit.
Select the second account.
In the Account Details page, select Withdraw and withdraw an amount of
$25.
In the Account Details page, select Deposit and deposit $33.
In the Account Details page, select List Transactions.
In the List Transactions page, click Account Details.
In the Account Details page, click Customer Details.
In the Customer page, change the last name, and click Update.
In the Customer page, click Logout.
You can also keep the profiling running while you analyze the accumulated data.
To display the collected data, we use the toolbar icons (Figure 25-12).
Alternatively, you can right-click the process and select Open With → statistic:
Open Execution Flow
Open Memory Statistics
Open Execution Statistics
Open Coverage Statistics
Open Object References
Coverage statistics
The Coverage Statistics view displays usage statistics for a selected type of
object. Coverage statistics are available at the package, class, method, and
instance level.
To analyze the coverage statistics, in the Profiling Monitor view, select the second
attached profiler process and click the icon, or select Open With →
Coverage Statistics (Figure 25-13).
The Coverage Statistics view shows how many times a package or class has
been called, and how many methods were hit and missed.
You can drill down into the methods by expanding a class to see which methods
were missed and how many times each method was called (Figure 25-15). This
type of information is useful for function testing.
The display options of the Coverage Statistics view can be changed from the
views’ toolbar menu . You can select to view package, class, or
method level information.
The view provides filtering based on the name of the package, class, or method
(Figure 25-16). You can also filter on time or heap size and on particular
attributes of the package, class, method, or object instance.
You can examine the source code for a class or method by right-clicking it in the
Coverage Statistics view and selecting Open Source.
The view also provides the reporting capability to export data in CSV, HTML, and
XML format by clicking the icon. The New Report dialog allows you to select
the report type and open the document (Figure 25-17).
Memory statistics
The Memory Statistics view displays statistics about the application heap. It
provides detailed information such as the number of classes loaded, the number
of instances that are alive, and the memory size allocated by every class.
Memory statistics are available at the package, class, and instance level.
In the Profiling Monitor view, select the second attached profiler process and click
the icon, or select Open With → Memory Statistics (Figure 25-18).
Execution statistics
The Execution Statistics view displays statistics about the application execution
time. It provides data such as the number of methods called, and the amount of
time taken to execute every method. Execution statistics are available at the
package, class, method and instance level.
To analyze the execution statistics, in the Profiling Monitor view, select the
second attached profiler process and click the icon, or select Open With →
Execution Statistics (Figure 25-19).
You can expand a class to see the statistics for each method (Figure 25-20).
Object references
The Object References view displays statistics about classes and objects, and
how many references there are to these objects.
In the Profiling Monitor view, select the second attached profiler process and click
the icon, or select Open With → Object References (Figure 25-22).
Execution flow
The Execution Flow view and table both show a representation of the entire
program execution. In this view, the threads of the program fit horizontally, and
time is scaled so that the entire execution fits vertically. In the table, the threads
are grouped in the first column and time is recorded in successive rows.
In the Profiling Monitor view, select the second attached profiler process and click
the icon, or select Open With → Execution Flow (Figure 25-23).
The top pane shows the execution stripes, but we have to zoom in to see any
details. The time in seconds is displayed on the right side. All our actions
occurred after 5 seconds of waiting to get the application started.
To see the details of an interaction, expand one of the doPost methods to see the
complete execution flow (Figure 25-24).
Zoom into the top pane using the Zoom In icon to see methods and their
times (Figure 25-25). The time spent in methods in our application is too small to
make the graph very readable.
You can open the execution flow by clicking the Open Execution Flow Table
icon (top-right in the toolbar).
You can drill down into a lifeline that allows you to view all the trace interactions
within a particular lifeline. This feature helps to trace the root cause of a problem
from a host, to a process, to a thread, and eventually to a class or an object.
For example, scroll right and locate the PerformTransaction class. Right-click the
class and select Drill down into selected lifeline. Zoom in to enlarge the
diagram (Figure 25-27).
Click to reset
the diagram
You can highlight a call stack, which allows you to view all the methods
invocations in a call stack. To highlight a call stack, right-click a method and
select Highlight call stack (Figure 25-28). All method invocations in the call
stack are highlighted.
More information
In the Application Developer Online Help, select Testing functionality and
performance → Monitoring and profiling applications.
Note: Before starting this chapter, you should install ClearCase LT on your
machine, as it is described in “Installing IBM Rational ClearCase LT” on
page 1304.
ClearCase overview
ClearCase is a software configuration management (SCM) product that helps to
automate the tasks required to write, release, and maintain software code.
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.
For the full-sized ClearCase version, the product also provides an add-on
MultiSite feature.
More information on ClearCase products can be found at:
http://www.ibm.com/software/awdtools/clearcase/
ClearCase terminology
Here, we outline some of the key terminology used in ClearCase:
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 developer’s 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.
Versioned object base (VOB): The permanent data repository where
ClearCase stores files, directories, and meta data.
View: A selection of resources in a VOB, a window to the VOB data.
Developer 1 Developer 2
Application ClearCase ClearCase Application ClearCase
Developer LT Client LT Server Developer LT Client
connect connect
In this chapter, we are simulating this setup by using two workspaces on the
same machine.
ClearCase preferences
Ensure that the ClearCase SCM Adapter capability is enabled. Refer to “Setting
up the ClearCase server environment” on page 1192 for details.
There are a number of ClearCase preferences that you can modify by selecting
Window → Preferences → Team → ClearCase SCM Adapter (Figure 26-2).
We recommend that you check out files from 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 for you, if you select
Automatically checkout for Checked in files that are saved by an internal editor.
You might want to specify to automatically connect to ClearCase when you start
Application Developer by selecting Automatically connect to ClearCase on
startup.
Note: You must be connected to ClearCase for the Advanced Options button
to be active.
The setup of this scenario and its flow are shown in Figure 26-3. ClearCase
terminology is used for the tasks.
Workbench 1 Workbench 2
Note that the integration view is like a window to the integration stream. The
integration stream should be reserved only for code that has passed the
developer’s inspection and is sharable to the entire team.
When finished with the changes, the developer delivers his or her 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.
Note: If you are creating only one VOB with a single VOB-level component,
and you do not have more than one component in the project, then it means
that you do not have a composite baseline, and therefore, a root-less
component is not required.
In the New Project—Step 2 dialog, ensure that No is selected, and click Next.
Since we are creating a project from scratch, and we do not have any other
existing projects at that time, we do not select a project to seed this project as
the baseline.
In the New Project—Step 3 dialog, click Add and make the following steps, as
shown in Figure 26-5:
– In the Add Baseline dialog, click Change >> and select All Streams.
– Select the component itso_example_vob from the Component drop-down
list, and select itso_example_vob_INITIAL under Baselines.
– Click OK.
– Click Next.
In the New Project—Step 4 dialog, select itso_example_vob in the Make the
following components modifiable list and click Policies:
– In the Project Policies Deliver tab enable the first two options, and click
OK (Figure 26-7):
• The first option ensures that there are no elements left checked out
when the developer tries to deliver the current stream. This helps
reduce the number of abandoned elements. It enforces the idea if there
is an element checked out, either it contains useful code (so we should
check it in) or the changes should be undone.
• The second option ensures that the developers always have the latest
stable code in their private work areas.
– Click Next.
In the New Project—Step 5 dialog, select No and click Finish.
Click OK in the confirmation dialog.
ClearCase now creates the ITSO_Project project and it shows up in the Project
Explorer in the Projects folder.
In the Add Element(s) to Source Control dialog, keep all resources selected
and make sure that Keep checked out is cleared. Click OK.
In the ClearCase—Select Activity dialog, click New and enter Developer 1
adds project to source control, and click OK. Click OK to continue
(Figure 26-12).
Figure 26-13 Package Explorer with resources under ClearCase source control
Tip: It can be useful to create a baseline at this time (see “Developer 1 makes
a baseline” on page 1205) and recommend the baseline to all other
developers.
Development scenario
To show how to work with ClearCase, we use a simple scenario where two
developers work in parallel on a common project. We use a servlet to illustrate
handling a situation when adding an element (the servlet) generates a potential
update to some other element(s), such as the deployment descriptor.
Before we deliver the work to the integration stream, we want to check them back
in. Do these steps:
Right-click web.xml and select Team → Check in or select it and click in
the toolbar.
In the Check in Element(s) dialog, ensure that the element is selected and
click OK. The green check mark on the resource icon is removed, indicating
that the file is no longer checked out.
No checked out files are found. Click OK to dismiss the dialog and then close
the Find Checkouts dialog.
After a while, the Deliver from Stream—Merges Complete dialog opens. Clear
Open a ClearCase Explorer window and click OK.
In the Delivering to View dialog, click Complete and after the work is done
Close.
Select Start the Diff Merge tool for this element and click OK. Click OK
again at the Diff Merge Status dialog.
The Diff Merge tool is now launched (Figure 26-23).
Take a few moments to become familiar with the information displayed and
the options available to you:
– The top panel shows the merge result and areas of conflict. Click a line to
focus on that particular conflict.
– The lower panels show the different versions that are available.
– The number icons on the toolbar (1, 2, 3) are used to indicate which
version should be used in the merged result.
In the toolbar, select 2 and 3 to determine that in this case the implementation
of developer 1 and developer 2 should be merged. Verify the change in the
merge panel.
Close the Merge Tool by saving the changes (select File → Save) and close
the tool.
After a while, the Deliver from Stream—Merges Complete dialog opens. Clear
Open a ClearCase Explorer window and click OK.
In the Delivering to View dialog, click Complete and after the work is done
Close.
Tip: For more complex projects, it is good practice to use a new workspace,
import the projects (from ClearCase), and verify that nothing has been broken
by the integration.
Summary
In this chapter we described how to set up ClearCase LT and use the product in
a team under Application Developer V7. We used a very simple scenario with two
developers to illustrate the major activities when interacting with ClearCase LT.
More information
For more information on ClearCase LT and its integration with Application
Developer, refer to these resources:
Software Configuration Management: A Clear Case for IBM Rational
ClearCase and ClearQuest® UCM, SG24-6399
Application Developer Help, under Working in a team environment
Finally, it is important to note that CVS only implements version control and does
not handle other aspects of SCM, such as requirements management, defect
tracking, and build management. There are other open source projects for
performing these functions, and also, the Rational suite of products has a large
set of tools that perform the same functions in an integrated way. (See
Chapter 26, “ClearCase integration” on page 1185 for an explanation of Rational
ClearCase, which also provides source code version control.)
CVS features
Some of the main features of CVS are as follows:
Multiple client-server protocols over TCP/IP, a feature that allows developers
access to the latest code from a wide variety of clients located anywhere with
access to the CVS Server.
For more information on these configurations, refer to the CVS home page
and Application Developer help. The option pserver is the easiest to
configure and is used in the example in this chapter.
All the versions of a file are stored in a single repository file using
forward-delta versioning, which stores only the differences between
sequential versions.
Developers are insulated from each other. Every developer works in their own
directory, and CVS merges the work in the repository when they are ready to
commit. Conflicts can be resolved as development progresses (using
synchronize) and must be resolved before any piece of work is committed to
the repository.
Application Developer provides a fully integrated CVS client, the main features of
which are demonstrated throughout this chapter. At the highest level, there are
two perspectives in Application Developer that are important when working with
CVS:
CVS Repository Exploring perspective—Provides an interface for creating
new links to a repository, browsing the content of the repository, and checking
out content (files, folders, projects) to the workspace.
Team Synchronizing perspective—Provides an interface for synchronizing
code on the workspace with code in a repository. The perspective is also used
by other version control systems, including IBM Rational ClearCase.
In addition to these two perspectives, there are numerous menu options, context
menu options, and other features throughout Application Developer to help users
work with a CVS repository.
At the time of writing, the CVSNT branch 2.5.x branch was the most stable
version.
We used CVSNT V2.5.03.2382 for the sample because all of our sample
applications where developed on the Windows platform, and the CVS home
page stated that this was the most stable recent version. We found CVSNT
easy to use and did not experience any significant problems using CVSNT,
however, the correct configuration was required.
When the installation is complete, the installation program prompts to see if you
want to to perform a restart. We recommend that you restart your system. This
step guarantees that the environment variables are set up properly and the
CVSNT Windows services are started.
We created a new administrative user for the CVS Server machine to start and
stop the CVS administration processes.
Note: The full host name must be specified, localhost does not work. To
find out the name of a machine you are using, bring up the context menu of
the computer from the Windows desktop, select Properties and select the
Computer Name tab. The full computer name is shown on this page.
Log on to the CVS repository machine to manage the users, using the
following command:
cvs login cvsadmin
You are prompted to enter the CVS password.
Enter the password for the cvsadmin user created in “Creating the Windows
users and groups used by CVS” on page 1222.
Enter the following CVS commands to add users:
cvs passwd -a -r cvsadmin <cvs user id>
– cvs passwd -a is the command to add a new user and password, or
change a password if that user already exists.
– -r cvsadmin indicates the alias or native user name that the user will run
under when connecting to the repository (we set this to be cvsadmin for
the user created in “Creating the Windows users and groups used by
CVS” on page 1222).
– <cvs user id> is the user ID to be added.
For example, to add user cvsuser1, enter the following command:
cvs passwd -a -r cvsadmin cvsuser1
Note: The first occurrence of a user being added creates the file passwd in
the directory, c:\rep7501\CVSROOT. The new user is appended to this file.
We recommend that this file not be edited directly by a text editor. It also
must not be placed under CVS control.
If everything worked correctly, you can to see a repository location in the CVS
Repositories view. The entry can be expanded to show HEAD, Branches,
Versions, and Dates (Figure 27-8).
If a particular file extension is not in the list, then this extension has to be added,
unless the resource is stored in the default binary format. Application Developer
prompts the user for the resource type when performing the first check-in (see
Figure 27-17 on page 1239) if it encounters a new type, or the new type can be
added manually in the Preferences page.
Tip: The content can also be changed by highlighting the extension and
clicking Change. This toggles the setting between ASCII and Binary.
Ignored resources
Resources that are created or changed dynamically through mechanisms such
as compilation or builds are not recommended to be saved in the repository. This
can include class files, executables, and Enterprise JavaBean stub and
implementation code.
Application Developer stores a list of these resources that are ignored when
performing CVS operations. This is accessed by selecting Windows →
Preferences and expanding Team → Ignored Resources.
Resources can be added to this list by specifying the pattern that will be ignored.
The two wild card characters are an asterisk (*)—which indicates a match of zero
or many characters—and a question mark (?)—which indicates a match of one
character. For example, a pattern of _EJS*.java would match any file that begins
with _EJS and had zero to many characters and ends in .java.
The following example shows the addition of the filename pattern *.tmp to the
ignored resources list:
Select Windows → Preferences and expand Team → Ignored Resources.
Click Add Pattern.
Enter the pattern *.tmp and click OK.
Ensure that the resource (*.tmp) is selected and added to the Ignored
Resources list (Figure 27-11). *.tmp resources are now ignored by CVS in
Application Developer.
To remove a pattern from the ignore list, select it and click Remove. Alternatively,
you can temporarily disable ignoring the file pattern by clearing its check box in
the list.
Additionally, there are two further facilities that can be used to exclude a file from
version control:
Resources marked as derived are automatically not checked into the CVS
repository by Application Developer. This field is set by builders in the Eclipse
framework, such as the Java builder. To determine if a resource is derived or
not, right-click the resource and select Properties, or look in the Properties
view. The Derived field is shown under Info. It is also possible to change the
Derived field value in the properties dialog.
Use of a .cvsignore file. This file contains a list of files or directories that
should not be placed into the repository. CVS checks this file and does not
add to CVS any files which are in this list.
A file can be added to the list by right-clicking the file on the Project Explorer
and selecting Team → Add to .cvsignore.
Watch/Edit Windows → Preferences → Settings for the CVS watch and edit
Team → CVS → Watch/Edit functionality which allows users to be
informed (via e-mail) when a file has
been edited or committed by another
user.
Application Developer, by default, has the keyword substitution set to ASCII with
keyword expansion (-kkv) under the selection Windows → Preferences →
Team → CVS and the File and Folders tab (Figure 27-12). This setting expands
out keyword substitution based on the interpretation by CVS, and is performed
wherever the keywords are located in the file.
$Author$ Expands to the name of the author of the change in the file, for example:
$Author: itsodev $
$Date$ Expands to the date and time of the change in UTC, for example:
$Date: 2007/06/27 18:21:32 $
$Header$ Contains the CVS file in repository, revision, date (in UTC), author, state
and locker, for example:
$Header: /rep7501/XMLExample/.project,v 1.1 2007/06/27 18:21:32
itsodev Exp itso $
$Id$ Like $Header$ except without the full path of the CVS file, for example:
$Id: .project,v 1.1 2007/06/27 18:21:32 itsodev Exp itso $
$Log$ The log message of this revision. This does not get replaced but gets
appended to existing log messages.
$Name$ Expands to the name of the sticky tag, which is a file retrieved by date or
revision tags, for example: $Name: version_1_3 $
$Revision$ Expands to the revision number of the file, for example: $Revision: 1.1 $
$Source$ Expands to the full path of the RCS file in the repository, for example:
$Source: /rep7501/XMLExample/.project,v $
To ensure consistency across all files created, each user would have to cut and
paste this into their document. Fortunately, Application Developer offers a means
to ensure this consistency.
Note: The double dollar sign ($$) is required because Application Developer
treats a single dollar ($) as one of its own variables. The double dollar ($$) is
used as a means of escaping the single dollar so that it can be post processed
by CVS.
This sets up a standard CVS template. The next time a new class is created,
checked in, and then checked out, the header is displayed (Example 27-2).
Example 27-2 Contents of Java file after check in and check out from CVS
/**
* class comment goes here.
*
* <pre>
* Date $Date: 2004/10/29 18:21:32 $
* Id $Id: $Id: Example.java,v 1.1 2004/10/29 18:21:32 itsodev Exp itso $
* </pre>
* @author $Author: itsodev $
* @version $Revision: 1.1 $
*/
Note: The example in this chapter calls for two simulated developer systems.
For demonstration purposes, this can be accomplished by having two
workspaces on the same machine. Refer to “Workbench basics” on page 74
for detailed instructions on setting up multiple workspaces.
To show you how to work with CVS in Application Developer, we follow a simple
but typical development scenario, shown in Table 27-3.
In the sections that follow, we perform each of the steps and explain the team
actions in detail.
Expanding a location in the CVS Repository view reveals branches and versions.
A special branch, called HEAD, is shown outside the main branches folder
because of its importance. It is the main integration branch, holding the project’s
current development state.
The CVS Repositories view can be used to check out repository resources as
projects on the Workbench. You can also configure branches and versions, view
resource histories, and compare resource versions and revisions.
First, a project must be created and shared before full use can be made of the
repository.
A dialog opens, informing you that new file types are being added, which are
not configured as types in the Application Developer preferences (see
Figure 27-17). These are *.compatibility (used for allowing previous
versions of Application Developer use the V7 project files) and *.gph
(used to store the Web Diagram files).
Set both these file types to ASCII Text, and click Next.
After this has been completed, the ITSOCVSGuide project is checked into the
repository and available for other developers to use.
Select the ITSOCVSGuide module, right-click, and select Check Out. The
current project in the HEAD branch is checked out to the workspace.
Open the Java source code for View1.java and create two private attributes in
the class an integer named count and a String named message
(Figure 27-20).
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 might occur in the process. The arrow
icons with a plus sign indicate that the files do not exist in the repository.
Because the class View1.java is new and not yet checked in it shows the plus
sign in Figure 27-22.
Add these new resources to version control by right-clicking ITSOCVSGuide
in the Synchronize view, and selecting Commit.
In the Commit Files dialog, enter Initial Commit for the commit comment
and check the files displayed on bottom half of the window to make sure the
changes are as expected (Figure 27-23).
Note: Files that are not saved have an asterisk (*) in front of their names in
the title bar of the window. This assists in identifying resources that have to
be saved.
To obtain updated resources from the CVS repository, right-click the project
and select Update. This brings a copy of the View1.java file into this
workspace.
Verify that the changes do not cause problems with existing resources in the
local workspace, by checking the Problems View. In this case, there are none.
Right-click the ITSOCVSGuide project and select Commit.
In the Commit dialog, add the comment Added static count variable to
servlet. and click OK (Figure 27-26). This checks the changes made to
Servlet1 into the repository.
The repository now has the latest changes to the code from both developers. The
user cvsuser1 is in sync with the repository; however, cvsuser2,has not yet
received the changes to the servlet.
This brings the changes made to ServletA into the workspace and makes sure
that both workspaces are completely up to date.
servletA v1.4
servletA v1.2 check in &
check out merge
CVS Repository
cvsuser1
Time
Figure 27-27 Parallel concurrent development of same resource by multiple developers
Right-click and select Commit, add the comment User1 implementing the
doPost method, and click Finish to commit.
The developer cvsuser1 has now completed the task of adding code into the
servlet. Changes can now be picked up by other developers in the team.
Note 1: The symbol indicates that the file has conflicting changes that
requires merging.
Note 2: The .classpath and .compatbility files might still show as having
changes, even though no direct actions have been taken to change these
files. The files can be committed or ignored.
Figure 27-30 The changes between the local and remote repository
In the left pane, highlight the two lines of code which were added and move
them to the correct location in the method (Figure 27-32).
Figure 27-32 Move the added code to the correct merge point
This operation creates a revision of the file, revision 1.4, which contains the
merged changes from users cvsuser1 and cvsuser2. This is the case even
though both developers originally checked out revision 1.2.
The CVS resource history displays the columns described in Table 27-4.
Revision The revision number of each version of the file in the repository. An
asterisk (*) indicates that this is the current version in the workspace.
Tags Any tags which have been associated with the revision.
Revision Time The date and time when the revision was created in the repository.
Author The name of the used that created and checked in the revision into
the repository.
Comments The comment (if any) supplied for this revision at the time it was
committed.
The following icons are available at the top of the History view:
Refresh—Refreshes the history shown for the currently shown resource.
Link Editor with Selection—A toggle switch which automatically shows
the history of the resource currently being shown in the main editor.
Pin the History View—Locks the history view into showing just the
currently selected resource’s history. When this is toggled on then the Link
Editor with Selection is automatically switched off.
Comparisons in CVS
Often developers have to view what changes have been made to a file and in
which revision. Application Developer provides a mechanism to graphically
display two revisions of a file and their differences. Two types of comparison are
possible, users can compare the version in their workspace with any version in
the CVS repository, or any two files in the CVS repository can be compared with
each other.
The Resource History view provides these mechanisms and the following
scenario has an example of how to do this.
In the top half the outline view of the changes are shown. This includes
attribute changes and which methods that have been changed.
Note: The bars in the bottom pane on the right-hand side indicate the parts
of the file which are different. By clicking them Application Developer
positions the panes to highlight the changes, This can assist in quickly
moving around large files with many changes.
The result appears as in Figure 27-40. The higher version always appears in
the left-hand pane and the lower version to the right.
Annotations in CVS
The Annotation view allows a user to view all the changes that have been
performed on a particular file in a single combination of workspace views. It
displays what lines were changed in particular revisions, the author responsible
for the change, when the file was changed and the change description entered at
the time. By showing this information across all revisions of a file and in the same
set of connected views, developers can quickly determine the origin of changes
and the explanation behind them.
The annotation view allows a developer to identify changes that have occurred in
a particular file and identify the root causes of issues that they might have.
Branches in CVS
Branches are a source control technique to allow development on more than one
baseline in the repository.
In CVS, the HEAD branch always refers to the latest or current work that is being
performed in a team environment. This is only sufficient for a development team
Maintenance Stream
Development Stream
Release of software
Time
Figure 27-43 Branching with two streams
Branching
Creating a branch is useful when you want to maintain multiple streams of the
software being developed or supported and when they are in different stages of
delivery (usually development and production support).
The scenario demonstrated here is that a particular release has been deployed
to the production environment, and a new project has started to enhance the
application. In addition to this, the existing production release has to be
maintained so that problems identified are fixed quickly. Branching provides the
mechanism to achieve this and the following example outlines how this might be
done.
Note: Note that the logical revision for View2.java is 1.1.2.1 and for
ServletA.java is 1.4.2.1. The extra two numbers in the logical revision are
added by CVS when a branch is created. The first two numbers indicate
the logical revision where the branch was created, the third indicates which
branch the change from that logical revision (currently the second one if we
count the HEAD branch) and the final number is the logical revision within
this branch. In this case both files are the first revision in the Maintenance
branch, and so the last digit is the number one.
The changes have now been committed into the Maintenance branch, which now
has different content than the main branch. These changes are not seen by
developers working on the HEAD branch, which is the development stream in our
scenario.
Merging
Merging of branches occurs when it is decided that code from one branch should
be incorporated into another branch. This might be required for several reasons,
such as if a major integration release is about to be released for testing, or if bug
fixes are required from the maintenance branch to resolve certain issues.
In our case, the branch is called Maintenance, and the version from which we
created the branch was called Branch_Root.
Merging requires that the target or destination branch be loaded into the
workspace before merging in a branch. Because in our scenario the changes are
merged to HEAD, the HEAD branch must be loaded in the workspace.
Click Browse for the Branch or version to be merged (end tag) and select
Maintenance under Branches and click OK (Figure 27-51).
The Select the Merge Points dialog (Figure 27-49) now shows the start and
end tags of the merge, which will be applied to the version in the work space.
The options to Preview Merge in the synchronize view and Perform the
merge into the local workspace provide the facility to select where to
perform the merge:
– Previewing it in the Synchronize view allows the user to review and make
changes to each file as required.
File to be added as
part of the merge
File to be changed as
part of the merge
The changes from the branch have now been merged into the main development
branch.
This scenario, although a simple one, highlights the technique required by users
to work with branches. In a real scenario there would be conflicts, and this would
require resolution between developers. Be aware that branching and concurrent
development is a complex process and requires communication and planning
between the two teams.
Such a configuration is useful when access to the source code repository has to
be restricted to a small number of users to prevent uncoordinated changes
corrupting the quality of the code. Any number of users can then contribute
changes and fixes to the repository using patches, but only through designated
code minders who can commit the work and who have the opportunity to review
changes before applying them to the repository.
This is done through the Team → Create Patch and Team → Apply patch
options available from the Project Explorer context menu. A patch can contain a
single file, a project or any other combination of resources on the workspace.
The Application Developer online help has a complete description of how to work
with CVS patches.
Select Do not delete the CVS meta information and click OK.
By not deleting the CVS meta information, we can reconnect the project with the
CVS repository later more easily. If the meta information is removed, CVS cannot
determine which revision in the repository a particular file is associated with
Reconnect
You can reconnect a project to the repository by selecting Team → Share
Project. Reconnecting is easier if the CVS meta information was not deleted:
If the meta information was deleted, the user is prompted to synchronize the
code with the an existing revision in the repository.
If the meta information is still available, the user is shown the original CVS
repository information and given the opportunity to complete the re-connect
(Figure 27-55).
This is handy if the changes being worked on are localized and other areas of the
code are changing in ways not important for the work at hand. On the other hand,
problems can occur with this mode of operation as well. Developers have to be
careful that important changes to the non-synchronized parts are not ignored for
long periods of time.
To perform the example. complete the following for the cvsuser1 workspace:
Open the Team Synchronizing perspective (Figure 27-56).
Expand the project tree to view the contents and note that all resources in the
workspace are selected. Accept the defaults for the Synchronize CVS dialog,
and click Finish (Figure 27-58).
Schedule synchronization
Application Developer allows the scheduling synchronization of the workspace.
This feature follows on from “Custom configuration of resource synchronization”
on page 1272, in which a user would like to schedule the synchronization that
has been defined. Scheduling a synchronization can only be performed for
synchronizations that have been pinned.
The user might be prompted to pin the current CVS synchronization, if it is not
already pinned. Click Yes.
More information
The help feature provided with Application Developer has a large section on
using the Team Synchronizing and the CVS Repository Exploring perspectives
and describes all the features covered in this chapter.
In addition, the following URLs provide further information for the topics covered
in this book:
CVS home page—The main source of information for CVS:
http://www.nongnu.org/cvs/
CVSNT home page—This is the main source of information for CVSNT,
which is the CVS server implementation for Windows machines and the CVS
Server software used in this chapter. See the following URL:
http://cvsnt.org/wiki
Eclipse CVS information—The CVS features available in Application
Developer V7.0 come from Eclipse 3.2. The following link is the main
information page for this project. It contains documentation, downloads, and
even the source code:
http://wiki.eclipse.org/index.php/CVS_Howto
Part 6 Appendixes
There are six wizards in the Installation Manager that make it easy to maintain
your package through its lifecycle, as seen in Figure A-1.
Note: For detailed information on the IBM Rational Application Developer V7.0
installation, refer to the product guides found in the disk1\documentation
directory:
Installation Guide, IBM Rational Application Developer v7.0. Open
install.html in a Web browser, or intall.pdf using Adobe Reader®.
Release Notes, IBM Rational Application Developer v7.0. Open
readme.html in a Web browser.
There are a number of scenarios that you can follow when installing Rational
Application Developer:
Installing from the CDs
Installing from a downloaded electronic image on your workstation
Installing from an electronic image on a shared drive
Installing from a repository on an HTTP or HTTPS server
Note that in the latter three scenarios, you can choose to run the Installation
Manager program in silent mode to install Rational Application Developer. See
the installation guide for details on each scenario.
Select Install IBM Rational Application Developer v7.0. You are directed to
install IBM Installation Manager because it is not installed yet, as seen in
Figure A-3. Click Next.
At the time of the writing, the latest version of Application Developer was
7.0.0.3. Note that IBM releases a fix pack approximately every three months.
You might see a newer version of Application Developer at the time you install
Application Developer. Each new version of Application Developer contains a
large quantity of fixes. We recommend that the customer install the latest
version to avoid encountering problems that have already been fixed. Now
Version 7.0.0.3 updates appear in the installation packages list. Select
Version 7.0.0.3 (Figure A-7) and click Next.
After the Installation Manager is updated and started, click Check for Other
Versions and Extensions. The updated Installation Manager finds the 7003
updates again (Figure A-9).
Note: You only have to install the Web Services Feature Pack if you want to
explore the new Web services functions of the feature pack.
In the Import Activation Kit page, browse to the path of the download location
for the kit, then select the appropriate Java archive (JAR) file and click Open.
Click Next.
In the Installation Manager overview, select Update Packages (see Figure A-1
on page 1282).
Selecting Update Packages takes you to the dialogue shown in Figure A-17.
You can select Update all to update all products installed, or you can be explicit
about a particular product. Clicking Next searches for the updates to the
products selected.
Before uninstallation of any products, ensure to terminate the programs that you
installed using Installation Manager.
In the Installation Manager overview select Uninstall Packages (see Figure A-1
on page 1282).
In the Uninstall Packages page select the Rational Application Developer product
package that you want to uninstall (Figure A-18). Click Next.
In the Summary page review the list of packages that will be uninstalled and then
click Uninstall. The Complete page is displayed after the uninstallation finishes.
Click Finish to exit the wizard.
Click Next and follow the instructions to install the package (similar to install
Application Developer).
The package is installed into the same Eclipse shell as Application Developer
and its functions will be available inside Application Developer.
Most of you are installing the Portal Test Environment after you have installed
Application Developer. The best way to do this is to bring up the Launchpad for
Rational Application Developer V7 (Figure A-20).
Figure A-21 Location of the install image of WebSphere Portal Setup Disk 1
Click OK to initiate the InstallShield wizard for WebSphere Portal V6.0. Select
the language when prompted. Click Next on the Welcome dialog to continue.
Click Next on the Software license agreement (if you agree).
In the next page, select the Typical as the Installation type and click Next
(Figure A-22). The Custom option is chosen when the user wants to install
the Portal Server on an existing version of the Application Server.
In the next page of the installation wizard (Specify the install location of the
Application Server), accept the default, and click Next.
In the next page (Specify the Cellname, Nodename, and the fully qualified
hostname of your machine), accept the default, and click Next.
In the New Server dialog, select WebSphere Portal V6.0 Server as the
server type and click Installed Runtimes to verify if the install wizard has
configured the newly installed Portal Server correctly.
In the Edit Server Runtime dialog (Figure A-26), verify that the install path
locations of Portal and Application Servers are correct. Click Finish to close
this dialog, and also close the Installed Server Runtime Environments dialog.
The upgrade process is quite complex and you have to follow the instructions
very carefully.
Besides these basic changes, there are more tips that you can implement to
increase the performance of the Portal Server during the development mode or
to reduce its startup time. Refer to “More information” on page 960.
Tips: 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 the
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.
We highly recommend that you use the Windows domain approach. Local
setup can be useful for testing and demonstration purposes.
Note: If the IBM Rational Setup Wizard warning dialog opens, as shown in
Figure A-29, just click Yes.
To create storage locations for VOBs and views and a process VOB, do these
steps:
Create the following directories on the machine you have installed ClearCase
LT server:
c:\clearstorage\vobs
c:\clearstorage\views
Share the directory c:\clearstorage and give permission Full Control to
Everyone.
Open the Windows Command Prompt and enter the following commands:
cd \
cleartool mkstgloc -vob vobs \\<servername>\clearstorage\vobs\
cleartool mkstgloc -view views \\<servername>\clearstorage\views\
– The vobs and views are the names of the VOB and view storage location
and how ClearCase knows how to identify them. The pathname to the
directory must be given using a UNC pathname.
– So \\server\clearstorage\ would be the server hostname followed by
the shared directory that we created.
Once this storage location exists, you can create the process VOB:
cleartool mkvob -tag \process -ucmproject -stgloc vobs
– You will then be prompted for comments, you can type your creation
comments and then enter a period (.) on an empty line to proceed when
the comments are finished.
Select the Additional materials and open the directory that corresponds with
the Redbooks publication form number, SG24-7501.
..\webapps Chapter 12, “Develop Web applications using JSPs and servlets” on page 465
..\struts Chapter 13, “Develop Web applications using Struts” on page 541
..\jsfsdo Chapter 14, “Develop Web applications using JSF and SDO” on page 587
..\ejb Chapter 16, “Develop Web applications using EJBs” on page 719
..\debug Chapter 22, “Debug local and remote applications” on page 1041
..\zInterchangeFiles Directory with subdirectories for each chapter with an interchange file containig
the finished code
Tip: After importing an interchange file for the RAD7EJB project, you have to
deploy the code again. Right-click the RAD7EJB project and select Prepare
for Deployment.
When prompted for the path and file name, enter the following:
– From zip file: Click Browse and locate the path and the zip file (for
example, C:\7501code\zInterchangeFiles\java\RAD7Java.zip).
– Project location root: Leave the default workspace location.
After locating the zip file, the projects contained in the interchange file are
listed. Select the project(s) that you want to import, and click Finish.
For example, we select RAD7Java and clicked Finish, (Figure B-2).
Derby
Command files to define and load the ITSOBANK database in Derby are provided
in the C:\7501code\database\derby folder:
DerbyCreate.bat, DerbyLoad.bat and DerbyList.bat assume that you
installed Application Developer in C:\IBM\SDP70\ folder. You have to edit
these files to point to your Application Developer installation directory if you
installed the product in a different folder.
In the C:\7501code\database directory:
– Execute the DerbyCreate.bat file to create the database and table.
– Execute the DerbyLoad.bat file to delete the existing data and add
records.
– Execute the DerbyList.bat file to list the contents of the database.
These command files use the SQL statements and helper files provided in:
itsobank.ddl—Database and table definition
itsobank.sql—SQL statements to load sample data
itsobanklist.sql—SQL statement to list the sample data
tables.bat—Command file to execute itsobank.ddl statements
load.bat—Command file to execute itsobank.sql statements
list.bat—Command file to execute itsobanklist.sql statements
DB2
DB2 command files to define and load the ITSOBANK database are provided in
C:\7501code\database\db2 folder:
Execute the createbank.bat file to define the database and table.
Here are the high-level configuration steps to configure the data source within
WebSphere Application Server for the ITSO Bank application sample:
Starting the WebSphere Application Server
Configuring the environment variables
Configuring J2C authentication data
Configuring the JDBC provider
Creating the data source
If you are using the WebSphere Application Server v6.1 test environment
shipped with Application Developer, in the Servers view, right-click WebSphere
Application Server v6.1 and select Start.
Click Next.
In the select JDBC provider page, select Derby JDBC Provider (XA). Click
Next.
Note: For DB2 UDB, select DB2 Universal JDBC Provider (XA).
Enter C:\7501code\database\derby\ITSOBANK as the Database name,
click Next.
Note: For DB2 UDB, enter ITSOBANK as the Database name and localhost
as the Server name.
Click Finish and then click Save.
Verify the connection by selecting RAD7DS (the check box) and then click
Test connection. You should get the message:
The test connection operation for data source RAD7DS on server server1
at node xxxxxNode02 was successful
JAX-B Java API for XML Binding ODBC Open DataBase Connectivity
JAX-RPC Java API for XML RPC OMG Object Management Group
The publications listed in this section are considered particularly suitable for a
more detailed discussion of the topics covered in this book.
Other publications
These publications are also relevant as further information sources:
D’Anjou, et al., The Java Developer’s Guide to Eclipse-Second Edition,
Addison Wesley, 2004, ISBN 0-321-30502-7
Eric Gamma, et al., Design Patterns, Elements of Reusable Object-Oriented
Software, Addison Wesley, 1995, ISBN 0-201-63361-2
Index 1327
CommonBaseEvents.xml 83 Architecture
compact Hyper Text Markup Language 906 Core Java APIs 29
Compare view 1257 Coverage Statistics view 1171
compare with 93 Craig Larmann 225
compare with local history 92 create
comparing data objects 398 page template 494
comparison editor 398 static Web resources 508
compatibility 22 test case 1016
compilation target 1081 visual class 407
compile Web Project 487
EGL 683 Create Servlet wizard 520
compiler options 112 Credit class 270
preferences 112 Crystal Enterprise 10
component Crystal Reports integration 14
interface 726 Crystal Reports perspective 128
test 1002 Crystal Reports Web project 156
testing 1001 CSS
component interface 756 See Cascading Style Sheets
composer 733 CSS Designer 478
composition relationship 753 CSS File wizard 480
concatenation mapping 454 custom
concurrency 723 finders 762
Concurrent Versions System 1213 profile 967
condition custom finders 762
breakpoint 1054 Customer class 267
conflict 1216 CVS 1213
connection administrator 1222
database 358 annotations 1259
pooling 357 branch 1261
server 977 merging 1266
Connector project 157, 161 client configuration 1225
Console view 131 access CVS repository 1226
construction 175 enable CVS Team capability 1225
constructor 259 comparison 1256
contained objects 399 conflict 1216
container development scenario 1236
EJB 723 features 1214
container-managed introduction 1214
relationships 728 keyword substitution 1233
container-managed persistence 57, 725, 764 merge 1250
container-managed relationships 58 parallel development 1247
content area 610 patches 1270
content assist 109, 313 preferences
Ant 1082 CVS specific settings 1232
context root 468, 490 file content 1229
converter 733 ignored resources 1230
cookies 38 label decorations 1228
CORBA 59 Repositories view 1237
See Common Object Request Broker repository 1219
Index 1329
architecture 1104 Diff Merge tool 1210
common considerations 1104 disconnected data graphs 50
deploy the enterprise application Display view 1043, 1057
configure data source in the server 1128 distribution 720
descriptor 1107 document access definition extension 817
descriptors 1105 Document Type Definition 430
J2EE application components doGet 516
applets 1105 doPost 516
application clients 1105 DriverManager 357
EJBs 1105 drop to frame 1045
Web applications 1105 DTD 430
J2EE deployment modules DTD editor 432
application client module 1105 dynamic behavior diagrams 185
EJB module 1105 dynamic navigation 632
resource adapter module 1105 dynamic page template 477, 481, 599
J2EE packaging Dynamic Web project 158
EAR 1105 dynamic Web project 158, 160
WAR 1105 JSF and SDO 596
Java and WebSphere class loader 1116 Struts support 550
package an application 1123 Dynamic Web Project wizard 480
customize deployment descriptors 1125 dynamic Web resources 513
generate deploy code 1126
prepare for sample
deployment scenario 1120
E
EAR 1095, 1105
import sample code 1122
filtering 1128
install prerequisite software 1121
EAR file 467
scenario 1120
Eclipse
WebSphere deployment architecture 1108
3.2 framework 4
WebSphere Rapid Deployment 1114
CVS information 1277
Deployment Manager
Hyades 18, 1040
profile 967
IBM Rational SDP 12
Derby 357
Java Development Tools 17, 891
database 673
Modeling Framework (EMF) 18
ITSOBANK database 358
Platform 17
JDBC driver 405
Plug-in Development Environment 17
JDBC Provider (XA) 693, 985
Project 16
stored procedure 363
SDK 7, 17
derived
Software Developer Kit (SDK) 17
attribute 333
Test and Performance Tools Platform 1001
beans 749
Web Tools Platform 965
design time template 477
Editing JSP 521
Design view 433
editors 119
desktop applications 28
EGL 14, 665
developerWorks
(non-Web) project 671
EGL 717
batch program 671
Rational 224
build file 674
samples 167
code 680
diagrams
compile 683
external 221
Index 1331
See Enterprise Java Bean Enterprise Application project 157, 159
select method 729 Enterprise archive
server 722 See EAR
session bean 725 Enterprise Generation Language
session facade 771 installation 1295
specification 722 see EGL
timer 723 Enterprise Java Server 722
Timer Service 59, 724 Enterprise JavaBeans 55, 719
transaction 722 see EJB
types 727 types
entity beans 725 entity 57
message-driven beans 725 message-driven 57
session bean 725 session 56
UML class diagram 747 entity
Universal Test Client 781 EJBs 57
visualize 190 relationships 750
EJB application entity beans 725
develop the application create 743
add business logic 755 customize 755
association relationship 751 environment 1004
composition relationship 753 Error Log view 140
create custom finders 762 evaluate an expression 1057
create entity beans 743 event handling
create entity relationships 750 GUI 419
customize entity beans 755 example projects 168
implement session facade 771 exception breakpoints 1059
object-relational mapping 764 executable test 1035
prepare for development 733 Execution Flow view 1178
configure data source 740 Execution Statistics view 1175
create EJB project 733 execution time analysis 1157
import Web application project 736 views 1157
testing with UTC 781 exemplar analysis 327
EJB to RDB mapping exemplar authoring 326
DB2 1123 export
ejbCreate method 756 EAR 1127
ejb-jar.xml 1107 Java application 290
ejbPostCreate method 761 expression
EJS 722 debugging 1057
elaboration 175 evaluation 1056
embedded SQL 384 language 45
EMF project 157 Expression Builder wizard 368
enabling transcoding for development 906 Expressions view 1043
encapsulation 731 extends relationship 184, 265
encryption 874 Extensible Markup Language 35, 430
enhanced EAR 741, 983, 1110 Extensible Style Language 431
data source 985, 1126 extensions classloader 1118–1119
Enhanced EAR Editor 1110 external diagrams 221
enterprise application 468
Enterprise Application Archive 1105
Index 1333
indentation 105 export 290
Informix 358 methods 260
Informix Dynamic Server 9 overview 236
inheritance 728 packages 237
initialization target 1081 step-by-step development 239
inline mapping 453 UML class diagram 237
installation ITSOBank class 272
Application Developer 1283 ITSOBANK database 357
ClearCase 1304 setup 1312
CVS for NT 1219 ITSOBankException class 277
Enterprise Generation Language 1295 ITSOCVSGuide 1238
license 21
Rational Agent Controller 1304
Rational Application Developer 20
J
J2C
Rational Business Developer Extension 1295
authentication data 1131
WebSphere Portal 1296
J2EE
WebSphere Portal V5.0 Test Environment
Connector 15
1296
Deployment API 15
Installation Manager 21, 670, 1282
Management API 15
Installed JREs
Module Dependencies 165
preferences 113
perspective 134, 734
integrated
Request Profiling Agent 1161
development environment 118
specification 467
Integrated Agent Controller 1159
Web APIs 470
integration stream 1187
J2EE Application Client 60, 794
interaction
JAR 154
diagrams 185
project 159
operators 219
JAAC
use element 221
See Java Authorization Service Provider
Interface Definition Language 31
Contract for Containers
internal 35
JAAS
Internet
authentication 985
preferences 95
See Java Authentication and Authorization
Internet Inter-ORB Protocol 59
Service
Internet preferences 95
Jacl 993
proxy settings 95
JAF
Web Browser settings 94
See Java Activation Framework
Introduction
Jakarta 1031
application development challenges 7
Java
Rational Software Delivery Platform 4
application
version 6 terminology 7
debug 287
InvalidateSession 484
export 290
InvalidTransactionException class 277
build path 165
ITSO Bank
class loader 1116
export 290
classpath variables 96
Struts 548
code review 282
ITSO Bank application
debugging features 1042
Bank interface 256
development
classes 246
Index 1335
transformation 14 style (fonts, size) 609
JET Transform project 329 edit JSF page
JMS 69 add relational record 634
See Java Message Service add relational record list to page 639
JMX 1141 add reusable JavaBean 644
See Java Management Extensions add row action 642
JNDI add SDO to JSF page 626
namespace 723 add simple validation 623
resource 691 add static navigation to page 625
See Java Naming and Directory Interface add UI components 620
JNDI Explorer 782 add variables 622
JNI 1120 display relational record 637
See Java Native Interface format field 640
join 367 run sample application 647
JRE 113 JSP 43
JSF breakpoint 1059
application architecture 589 debugging 1060
Application Developer 591 include 580
benefits 588 Tag libraries 44
components 591 tag libraries 471
configuration file 590 variables 1061
deluxe pager 641 JSP Page Designer 546
EGL Web page 696 JSP Standard Tag Library 45
expression builder 592 JSR 101 851
features 588 JSR 109 823
overview> 588 Web Services view 829
patterns 593 JSR 14 30
portlet bridge 13 JSR 168 904
portlets 907 JSR 175 30, 889
Quick Edit view 593 JSR 181 889
resource bundles 593 JSR 201 29
See JavaServer Faces JSR 224 889
servlet 590 JSR 235 50, 594
specification 588 JSR 250 889
validators 590 JSTL 45, 471
variable 622 JTA
Web Diagram 598 See Java Transaction API
JSF and SDO Web application JUnit
add connection for action 618 Assert class 1011
add navigation rules 618 framework 1017
configure data source via enhanced EAR 599 introduction 1001
create connection between JSF pages 614 library 1014
create Dynamic Web Project 596 methods 1019
create Faces Action 615 run 1020
create Faces JSP 611 sample 1013
create page template 599 test
customize page template 607 case 1015
content area 610 test suite 1019
logo image and title 607 testing 1007
Index 1337
model-view-controller 47, 471 Page Data view 147, 474, 565
Struts Web application 542 Page Designer 474, 476
MTOM 865, 879 page template 477, 494
multiprotocol binding 841 create dynamic JSP 495
Multipurpose Internet Mail Extensions 44 create static 494
MVC customize 496
See model-view-controller PageCodeBase 601
Struts 543 Palette
MySQL 9, 358 view 474
visual editor 412
parallel development 1247
N patches 1270
namespace 723
pattern
naming 723
apply 348
navigate Java code 301
command 486
navigation
facade 351
bar 498
implementation 325
candidate 505
specification 326
dynamic 632
PDE
root 505
See Plug-in Development Environment
rule 615
performance
Navigator view 131
bottlenecks 1156
Network Deployment 967
test 1003
no natural unique identifier 748
PerformTransaction 484
persistence 720, 723–724
O personal digital assistant 54
OASIS 856 perspectives 118
object available 127
caching 721 Crystal Reports 128
pooling 721 customizing 122
Object Management Group 225 CVS Repository Exploring 128
Object References view 141, 1177 CVS Repository Exploring perspective 128
object-relational mapping 764 Data 130
bottom up 765 Debug 132
meet-in-the-middle 765 EGL 667
relationships 770 Generic Log Adapter 134
top down 765 J2EE 134
ObjectWeb Java Open Application Server 965 Java Browsing 137, 235
ODBC 356 Java perspective 136
online help 125 Java Type Hierarchy 138, 235
Oracle 10, 358, 965 layout 120
Organization for the Advancement of Structured In- Plug-in Development 139
formation Standards 856 preferences 93
Outline view 133, 230, 474, 1043 Profiling and Logging 141
owned element association 184 Report Design 142
Resource 142
Rule Builder 143
P
Package Explorer view 229 specify default 122
switching 121
Index 1339
Profile Management Tool 965, 969 Project Explorer view 134
profiling promote 745
agent types Property Compare view 398
J2EE Request Profiling Agent 1161 Proxy Settings 95
Java Profiling Agent 1161 public key 858
analyze data 1171 Python 1142
architecture 1159
agent 1160
Agent Controller 1160
Q
query condition 370
application process 1160
quick assist 312
deployment hosts 1161
Quick Edit view 474
development hosts 1161
quick fix 231, 310
test client 1160
example 1162
features R
code coverage 1158 RAD7Ant 1078
execution time analysis 1157 RAD7BankBasicEAR 488
memory analysis 1157 RAD7BankBasicWeb 487
introduction 1156 RAD7DataDesign 387
prepare for profiling sample RAD7DataDevelopment 364
enable Profiling and Logging capability RAD7EGLnonWeb 672
1163 RAD7EGLWeb 689
publish and run sample application 1165 RAD7EGLWebEAR 690
profile the sample application RAD7EJB 735
collect profile information 1170 RAD7EJBEAR 735
start server in profile mode 1165 RAD7EJBJava 737
Profiling and Logging perspective 1161 RAD7GUI 405
profiling sets 1156 RAD7ITSOExampleWeb 1199
Profiling and Logging capability 89, 1161 RAD7Java 240, 514
Profiling and Logging perspective 141, 1161 RAD7JavaImport 293
Profiling Monitor view 141, 1174 RAD7JSF 596
programming technologies 27 RAD7JSFEAR 596
desktop applications 28 RAD7JUnit 1013
dynamic Web applications 40 RAD7JUnitWebTest 1032
Enterprise JavaBeans 55 RAD7Jython 993, 1144
J2EE Application Clients 60 RAD7Patterns 328
messaging systems 68 RAD7PatternsClient 328
static Web sites 36 RAD7PatternsFacade 351
Web Services 64 RAD7PatternsFacadeTransform 351
project RAD7SQLJ 382
close 155 RAD7StrutsWeb 550
create a new 161 RAD7WebServiceAnt 849
directory structure 491 RAD7WebServiceJSFClient 835
disconnect from CVS 1271 RAD7WebServiceSDOFacade 852
EJB 733 RAD7WSFP 867
facets 162, 598 RAD7WSFPAnnotationWeb 890
interchange file 155, 1310 RAD7WSFPClient 868
properties 161, 165 RAD7XMLBank 433
version 1254 RAD7XMLBankJava 457
Index 1341
remote data graph 462
client view 773 data source 599
debugging 1048 facade 851
interface 727 See Service Data Objects
Remote Method Invocation 59 sorting 639
remove project from a server SDP 4
via Rational Application Developer 982 search dialog 306
Report Design perspective 142 security
Report project 156 EJB 722
request sequence 545 roles 193
RequestDispatcher 470 run-as 194
resource Workbench 992
synchronization 1272 Security Configuration wizard 991
resource adapter 1119 Security Constraint wizard 480
archive Security Editor 478
See RAR Security Role wizard 480
module 1105 select statement 365
Resource perspective 142 sequence diagrams 213
result set 368 preferences 223
reverse engineering 388 server
RMI 59, 723 add project 981
See Remote Method Invocation configuration
RMI-IIOP 59 export 980
RP directory 1118 connection type 977
rule customization 976
violation 284 remove project 982
Rule Builder perspective 143 resources 983, 989
Run Ant wizard 1092 Servers view 133, 474, 688
run configuration 285 service
runAnt.bat 1099 client 813
run-as security 194 provider 812
RUP requester 813
life cycle 175 service broker 812–813
Service Data Objects 16, 49–50, 594
see SDO
S XML 460
SAAJ 15, 815
service provider 812
See SOAP with Attachments API for Java
service requester 812
sample code 1307
service-oriented architecture 811–812
description by chapter 1309
service
locate 1308
requester 813
project interchange files 1310
service broker 813
samples gallery 166
service provider 812
scalability 721
servlet 41, 513
Scalable Vector Graphics 1029
add to Web Project 513, 515
schema validation 441
container 469
scrapbook 287
create 515
SDO
Servlet Application Programming Interface 41
access XML 461
Servlet Mapping wizard 480
Index 1343
Static Web Project wizard 480 prepare for sample 548
static Web sites 36 run sample
step run sample application 577
filter 1045 Struts enabled project 550
into 1044 Web application using Tiles 580
over 1045, 1056 Web Diagram editor 546
step over 1045 Struts-bean tags 563
step-by-step mode 1045 struts-config.xml 48, 544
stored procedure 372 Struts-html tags 563
call 377 Struts-logic tags 563
deployment 375 Struts-nested tags 563
run 376 Struts-template tags 563
Stored Procedure wizard 372 Struts-tiles tags 563
Structural Compare view 398 Struts-Tiles technology 620
structural diagrams 185 style sheets
Struts 16, 541 customize 501
action classes 544 Styles view 475
action form 544 substring mapping 455
architecture 542 summary
Component wizards 546 features
Configuration Editor 546 application modeling with UML 14
configuration file 544 Eclipse 12
configuration file editor 569 JavaServer Faces 12
controller 543 Rational Unified Process 14
create action 554 test server environments 13
create components 553 Web services 13
Struts Action 554 supported
Struts Form Bean 555 databases
Struts Web Connection 557 Cloudscape 9
create form bean 555 DB2 Universal Database 9
create Web connection 557 Oracle 10
create Web page 557 platforms
development 553 Microsoft Windows 2000 Professional 9
development capabilities 547 Microsoft Windows 2000 Server 9
errors tag 565 Microsoft Windows Server 2003 9
introduction 542 Microsoft Windows XP Professional 9
ITSO Bank 548 SUSE Linux Enterprise Server 9
model 543 suspend 1044–1045
model-view-controller 542 Swing 33, 404
MVC 543 SWT
Portlet framework 546 See Standard Widget Toolkit
portlets 907 Sybase 358
resource files 544 Sybase Adaptive Server Enterprise 10
tag libraries 564 synchronization
tag library 563 schedule 1276
validation framework 558, 561 Synchronize view 143, 1243, 1272
validators 547 system verification test 1003
view 543
Web application 543
Index 1345
unit test 1002 Display 1043, 1057
Universal Description, Discovery, and Integration Error Log 140
65 Execution Flow 1178
Universal Test Client 781 Execution Statistics 1175
EJB 781 Expressions 1043
Web services testing 818 Gallery 147, 474
UNIX 1075 Hierarchy 230
UpdateCustomer 484 History 1254
URL mapping 515 Javadoc 293
User Function Library 156 JUnit 1020
UTC 781 Links 474
Utility project 157 Log Navigator 141
Members 137
Memory Statistics 141, 1174
V Method Invocation Details 1176
variable
Navigator 131
change value 1056
Object References 141, 1177
variables
Outline 133, 474, 1043
debugging 1055
Page Data 147, 474
JSP 1061
Page Designer 474
Variables view 133, 1043
Palette 474
version
Plug-ins 140
project 1254
Problems 133
version 6 terminology 7
Profiling Monitor 141, 1174
version tree 1212
Project Explorer 134
versioned object base 1187
Quick Edit 474
versioning 1253
Servers 133, 474
view
Snippets 475
add and remove 123
Source 1043
views 119
Structural Compare 398
Analysis Results 234
Styles 475
Annotation 1259
Synchronize 143, 1243, 1272
Bookmarks 303
Tasks 131, 475
Breakpoints 133, 1043
TCP/IP Monitor 834
Call Hierarchy 233
Test Log 145
Colors 474
Thumbnails 475
Compare 1257
Types 137
Console 131
Variables 133, 1043
Coverage Statistics 1171
XSLT Context 1047
CVS Annotation 129
XSLT Transformation Output 1047
CVS Repositories 128, 1237, 1264
visual class 407
CVS Resource History view 129
visual editor 403–404
Data Definition view 131
add JavaBeans to visual class 414–415
Data Output 131, 361
binding 423
Data Project Explorer 131
change component properties 414
Database Explorer 131, 672
code synchronization 413
Debug 133, 1043
create visual class 407
Declaration 232
customize appearance 411
Design 433
launch 407
Index 1347
webservices.xml 863 preferences 76
WebSphere Wireless Markup Language 44, 905
admin commands 996 WML 905
administrative console 971 Workbench
administrative scripting tool 993 basics 74, 77
class loader 1118 preferences 84
Network Deployment 967 working set 309
profile workload optimization 721
sharing 979 workspace 77
test 971 World Wide Web Consortium 879
Profiles WS Security wizard 858
application server profile 967 ws.ext.dirs 1119
custom profile 968 WS-Addressing 865
deployment manager profile 968 wsadmin 993, 1141
profiles 966, 1109 WSDL 65, 814
sample applications 967 dynamic 894
scripting client 1141 editor 843
WebSphere Administration Command assist tool fault handling 856
996 messages
WebSphere Application Server 19, 964 UML 202
Base Edition 1103 UML class diagrams 198
deployment architecture 1108 WS-I 67
enable debug 1064 Attachments Profile 67
Express Edition 1103 Basic Profile 67, 815
installation 969 compliance 834
Network Deployment Edition 1103 Simple SOAP Binding Profile 67
profile creation 969 WS-RM 865
Profiles 966 WSRP 905
profiles 1109 WS-Security 816
WebSphere Business Modeler 6 configuration 863
WebSphere class loader WTP 965
application class loader 1119 WYSIWYG 407, 476
extensions to class loader 1118
handling JNI code 1120
hierarchy 1118
X
X/Open SQL 356
Web module class loader 1119
Xdoclet 1114
WebSphere enhanced EAR 1110
Xerces 440
WebSphere Integration Developer 6
XML 35, 430
WebSphere Portal 901
and relational data 432
installation 1296
binary Optimized Packaging 879
Toolkit 54
constraints 435
V5.0 test environment 1296
digital signature 857
WebSphere Profile wizard 969
editor 432, 443
WebSphere Rapid Deployment
encryption 857
annotation-based programming 1114
mapping editor 432, 448
modes 1115
namespaces 432
tools 1114
overview 430
WebSphere Studio Application Developer 6–7
path language 431
Welcome page 74
Index 1349
1350 Rational Application Developer V7 Programming Guide
Rational Application
Developer V7
Programming Guide
(2.5” spine)
2.5”<->nnn.n”
1315<-> nnnn pages
Back cover ®
Rational Application
Developer V7
Programming Guide ®
Develop Java, Web, IBM Rational Application Developer for WebSphere Software
XML, database, EJB, V7.0 (for short, Rational Application Developer) is the full INTERNATIONAL
Struts, JSF, SDO, function Eclipse 3.2 based development platform for TECHNICAL
EGL, Web services, developing Java 2 Platform Standard Edition (J2SE) and Java SUPPORT
and portal 2 Platform Enterprise Edition (J2EE) applications with a focus ORGANIZATION
on applications to be deployed to IBM WebSphere Application
applications
Server and IBM WebSphere Portal. Rational Application
Developer provides integrated development tools for all
Test, debug, and development roles, including Web developers, Java BUILDING TECHNICAL
profile with built-in developers, business analysts, architects, and enterprise INFORMATION BASED ON
and remote servers PRACTICAL EXPERIENCE
programmers.
Rational Application Developer is part of the IBM Rational
Deploy applications IBM Redbooks are developed by
Software Delivery Platform (SDP), which contains products in
to WebSphere the IBM International Technical
four life cycle categories: Architecture management (includes Support Organization. Experts
Application Server integrated development environments and Application from IBM, Customers and
and WebSphere Developer), change and release management, process and Partners from around the world
Portal portfolio management, and quality management. create timely technical
information based on realistic
This IBM Redbooks publication is a programming guide that scenarios. Specific
highlights the features and tooling included with Rational recommendations are provided
Application Developer V7.0. Many of the chapters provide to help you implement IT
working examples that demonstrate how to use the tooling to solutions more effectively in
your environment.
develop applications, as well as how to achieve the benefits
of visual and rapid application development.