Using VisualAge for Java To Develop Domino Applications

318
SG24-5424-00 International Technical Support Organization www.redbooks.ibm.com Using VisualAge for Java To Develop Domino Applications Christophe Toulemonde, Gianfranca Rastelli, John Toews, Christian Wegh

Transcript of Using VisualAge for Java To Develop Domino Applications

Page 1: Using VisualAge for Java To Develop Domino Applications

SG24-5424-00

International Technical Support Organization

www.redbooks.ibm.com

Using VisualAge for JavaTo Develop Domino Applications

Christophe Toulemonde, Gianfranca Rastelli, John Toews, Christian Wegh

Page 2: Using VisualAge for Java To Develop Domino Applications
Page 3: Using VisualAge for Java To Develop Domino Applications

Using VisualAge for JavaTo Develop Domino Applications

September 1999

SG24-5424-00

International Technical Support Organization

Page 4: Using VisualAge for Java To Develop Domino Applications

© Copyright International Business Machines Corporation 1999. All rights reservedNote to U.S Government Users – Documentation related to restricted rights – Use, duplication or disclosure issubject to restrictions set forth in GSA ADP Schedule Contract with IBM Corp.

First Edition (September 1999)

This edition applies to Domino Application Server R5 and VisualAge for Java Version 2.

Comments may be addressed to:IBM Corporation, International Technical Support OrganizationDept. QXXE Building 80-E2650 Harry RoadSan Jose, California 95120-6099

When you send information to IBM, you grant IBM a non-exclusive right to use or distribute theinformation in any way it believes appropriate without incurring any obligation to you.

Before using this information and the product it supports, be sure to read the general information inAppendix C, “Special Notices” on page 269.

Take Note!

Page 5: Using VisualAge for Java To Develop Domino Applications

Contents

Figures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ix

Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvThe Team That Wrote This Redbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviComments Welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii

Part 1. VisualAge for Java Meets Domino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 1. Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Java Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.3 Java Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

1.3.1 Java Applets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.3.2 Java Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.3.3 Java Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

1.4 Java Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141.5 Distributed Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

1.5.1 Java Database Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151.5.2 Common Object Request Broker Architecture. . . . . . . . . . . . . . . 181.5.3 Remote Method Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Chapter 2. Domino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272.1 Domino Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282.2 Domino and the Web . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322.3 Domino Database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332.4 Programming for Domino . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362.5 DECS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382.6 Domino and Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

2.6.1 Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392.6.2 CORBA Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392.6.3 CORBA Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412.6.4 Domino Java classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432.6.5 Domino Driver for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442.6.6 Lotus Connectors Java Classes . . . . . . . . . . . . . . . . . . . . . . . . . 472.6.7 Domino Java Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

2.7 Domino Java Program Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502.7.1 Java Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512.7.2 Java Agents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572.7.3 Java Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

iii

Page 6: Using VisualAge for Java To Develop Domino Applications

2.8 Lotus Domino Toolkit for Java/CORBA . . . . . . . . . . . . . . . . . . . . . . . . 67

Chapter 3. VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693.1 Integrated Development Environment. . . . . . . . . . . . . . . . . . . . . . . . . 69

3.1.1 Workspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713.1.2 Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733.1.3 Importing and Exporting Java Code . . . . . . . . . . . . . . . . . . . . . . 743.1.4 Scrapbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783.1.5 Debugger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

3.2 Visual Composition Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Chapter 4. Visualage for Java and Domino . . . . . . . . . . . . . . . . . . . . . . 854.1 Java Support for Domino - VisualAge for Java Makes It Easy . . . . . . 854.2 Applet. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

4.2.1 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874.2.2 Development Environment Initialization . . . . . . . . . . . . . . . . . . . 884.2.3 Support Methods Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894.2.4 Visual Composition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914.2.5 Debug and Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 964.2.6 Installing the Applet in Domino . . . . . . . . . . . . . . . . . . . . . . . . . . 97

4.3 Agents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 984.3.1 Domino Agent Runner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 994.3.2 Domino Agent Class Creation. . . . . . . . . . . . . . . . . . . . . . . . . . 1014.3.3 AgentContext Document. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1044.3.4 Debug and Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1054.3.5 Deploying the Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

4.4 Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1094.4.1 Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1104.4.2 Writing the Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1104.4.3 Debug and Test . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1114.4.4 Implementing the Servlet within Domino . . . . . . . . . . . . . . . . . . 114

Part 2. From Theory to Practice. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

Chapter 5. ACME Digital eTrade Vendor . . . . . . . . . . . . . . . . . . . . . . . 1175.1 Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1175.2 Java Network Communications . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1195.3 Domino Client Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

Chapter 6. Domino Development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1236.1 eTrade Vendor Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

6.1.1 Database Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1236.1.2 Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

iv Using VisualAge for Java to Develop Domino Applications

Page 7: Using VisualAge for Java To Develop Domino Applications

6.2 Initial Resources Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1256.2.1 companyName Shared Field. . . . . . . . . . . . . . . . . . . . . . . . . . . 1256.2.2 Header Subform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1266.2.3 Product Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1276.2.4 Product Documents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1296.2.5 Catalog View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1306.2.6 Catalog Interface Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1326.2.7 PurchaseOrder Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1336.2.8 Previous Orders View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1386.2.9 EditItemList Subform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1386.2.10 PreparedPO View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1406.2.11 DisplayItemList Subform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

6.3 Testing the Domino Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Chapter 7. Purchase Order Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . 1457.1 Design Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1457.2 POApplet Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1477.3 Project and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1487.4 POItem Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1507.5 PO Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1597.6 AddDialog Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1607.7 Catalog Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1647.8 Business Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1677.9 Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1687.10 BusinessRules Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1687.11 BusinessRulesServer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1697.12 DiscountRule Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1717.13 POApplet Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1727.14 BusinessRules Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1817.15 Testing the POApplet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

7.15.1 Domino Server Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1827.15.2 RMI and the Business Rules Server . . . . . . . . . . . . . . . . . . . . 1827.15.3 Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185

7.16 Debugging the POApplet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1887.17 Importing the POApplet in Domino . . . . . . . . . . . . . . . . . . . . . . . . . 193

7.17.1 Export the Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1937.17.2 Include the Applet in the Domino Component . . . . . . . . . . . . . 1947.17.3 Setting the Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1967.17.4 Defining the Applet Parameters . . . . . . . . . . . . . . . . . . . . . . . 1967.17.5 Hiding the Parameter Sources . . . . . . . . . . . . . . . . . . . . . . . . 1977.17.6 JavaScript Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1987.17.7 Testing the Purchase Order Form. . . . . . . . . . . . . . . . . . . . . . 199

v

Page 8: Using VisualAge for Java To Develop Domino Applications

Chapter 8. PreparePOforEvaluator Agent . . . . . . . . . . . . . . . . . . . . . . 2018.1 Design Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2018.2 PreparePOforEvaluator Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2028.3 PreparePOforEvaluator Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2048.4 Testing and Debugging the Agent . . . . . . . . . . . . . . . . . . . . . . . . . . 2078.5 Implementing the Business Rules Verification . . . . . . . . . . . . . . . . . 2108.6 Implementing the CheckCredit Rule . . . . . . . . . . . . . . . . . . . . . . . . . 2138.7 Implementing RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2158.8 Running the Agent Natively in Domino . . . . . . . . . . . . . . . . . . . . . . . 217

Chapter 9. StatusServlet Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2199.1 Design Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2199.2 Prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2199.3 StatusServlet Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2209.4 Testing the StatusServlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2269.5 Deploying the StatusServlet on a Domino Server . . . . . . . . . . . . . . . 2289.6 Integrating the StatusServlet in the Application . . . . . . . . . . . . . . . . 230

Chapter 10. Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23310.1 Domino Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23310.2 Domino Java Agents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23410.3 Domino Java Servlets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23410.4 Agents, Servlets, or CGI Programs?. . . . . . . . . . . . . . . . . . . . . . . . 23510.5 Domino Driver for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23710.6 VisualAge for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

Part 3. What’s Next? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Chapter 11. Domino Access Builder . . . . . . . . . . . . . . . . . . . . . . . . . . 24111.1 Main Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24211.2 Usage Scenarios . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24411.3 Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244

11.3.1 Model Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24411.3.2 Visual Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

11.4 Generated Access Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24611.5 Domino Java Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

Chapter 12. Using the Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24912.1 Verifying the Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24912.2 ProductList Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251

12.2.1 SmartGuide Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25112.2.2 Product List View Visual Composition. . . . . . . . . . . . . . . . . . . 25712.2.3 Product Dialog Visual Composition . . . . . . . . . . . . . . . . . . . . . 258

vi Using VisualAge for Java to Develop Domino Applications

Page 9: Using VisualAge for Java To Develop Domino Applications

12.2.4 Combining View and Form . . . . . . . . . . . . . . . . . . . . . . . . . . . 26012.2.5 Testing the Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262

Appendix A. The Sample Application . . . . . . . . . . . . . . . . . . . . . . . . . . . 265A.1 Download . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265A.2 Environment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

Appendix B. JDK Layout Managers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267

Appendix C. Special Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269

Appendix D. Related Publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273D.1 International Technical Support Organization Publications . . . . . . . . . . 273D.2 Redbooks on CD-ROMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274D.3 Other Publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274

How to Get ITSO Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275IBM Redbook Fax Order Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277

List of Abbreviations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283

ITSO Redbook Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297

vii

Page 10: Using VisualAge for Java To Develop Domino Applications

viii Using VisualAge for Java to Develop Domino Applications

Page 11: Using VisualAge for Java To Develop Domino Applications

Figures

1. Servlet Process Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112. JDBC Driver Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163. CORBA Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194. Remote Method Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225. Domino Application Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296. Domino Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327. Domino CORBA Architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418. Domino CORBA Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429. Domino Driver for JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4510. Domino Server Document Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4911. Configuration Settings for Domino ORB - Internet Ports . . . . . . . . . . . . . . 5012. Configuration Settings for Domino ORB - Internet Protocols. . . . . . . . . . . 5013. Notes Preferences Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5314. Create Java Applet Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5415. Locate Java Applet Files Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5416. Applet Parameters Programmer’s Pane . . . . . . . . . . . . . . . . . . . . . . . . . . 5517. Applet Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5618. Java Applet Security Options. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5719. Java Console Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5920. Domino R5 Create Agent Run Options . . . . . . . . . . . . . . . . . . . . . . . . . . . 6021. Define Java Agent Files Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6122. Reimport the Agent Class File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6123. Java Agent Programmer’s Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6224. Domino R5 Java Servlet Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . 6625. Workbench. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7226. Repository Explorer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7427. File - Import SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7528. Import from a directory - SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7629. Import from another repository - SmartGuide . . . . . . . . . . . . . . . . . . . . . . 7630. Export to a directory - SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7731. Export to another repository - SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . 7832. Debugger Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8033. Automatic Code Completion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8034. VisualAge for Java Visual Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . 8235. Create Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8836. Visual Composition Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9337. Event-to-Code Connection from SearchButton . . . . . . . . . . . . . . . . . . . . . 9438. Bean Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9539. Applet Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9640. Applet Debug Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

© Copyright IBM Corp. 1999 ix

Page 12: Using VisualAge for Java To Develop Domino Applications

41. Export to a Directory SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9842. Quick Start - Add Features Dialog Box . . . . . . . . . . . . . . . . . . . . . . . . . . 10043. Adding the Domino R5 Java Class Library . . . . . . . . . . . . . . . . . . . . . . . 10144. DominoAgent Class Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10245. Exporting the DominoAgent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10446. DominoTestAgent Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10447. Importing the DominoAgent Class within DominoTestAgent . . . . . . . . . . 10548. Domino Java Console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10549. AgentContext Document . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10650. Running TaskAgent with Domino Agent Runner . . . . . . . . . . . . . . . . . . . 10651. Debugging the Agent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10752. Domino Agent Runner Properties Dialog Box . . . . . . . . . . . . . . . . . . . . . 10853. Domino Agent Runner - Update AgentContext Dialog Box . . . . . . . . . . . 10854. Mail Sent by the DominoTestAgent Agent . . . . . . . . . . . . . . . . . . . . . . . . 10955. Create doGet Method SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11056. Attribute doGet Method SmartGuide . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11157. Classpath Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11258. Servlet Runner Console Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11359. eTrade Vendor Application Architecture . . . . . . . . . . . . . . . . . . . . . . . . . 11860. New Database Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12461. Shared Field Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12662. Subform Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12763. Table Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12864. Product Form Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12965. Product Document Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13066. View Creation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13067. View Column Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13168. Catalog Interface Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13369. Properties Box: Hide When Tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13670. PurchaseOrder Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13771. EditItemList Subform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14072. POApplet GUI Prototype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14673. Add Dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14674. Add Project Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14975. Add Package Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15076. Attributes Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15177. Project Browser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15278. Create Field Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15379. Create Method Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15580. Visual Composition Editor: AddDialog . . . . . . . . . . . . . . . . . . . . . . . . . . . 16281. AddDialog Layout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16382. Event to Code Window - Visual Composition Editor. . . . . . . . . . . . . . . . . 16483. Server Document: Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

x Using VisualAge for Java to Develop Domino Applications

Page 13: Using VisualAge for Java To Develop Domino Applications

84. RMI Registry Pane. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18485. POApplet Properties Pane: Applet Tab . . . . . . . . . . . . . . . . . . . . . . . . . . 18586. Inspector Pane. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18787. Applet Viewer: POApplet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18788. Debugger Panes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18989. Setting a Breakpoint. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19090. Configuring Breakpoint Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19291. Class Export Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19492. Create Java Applet Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19593. Locate Java Applet Files Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19594. Setting Applet Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19795. HTML Field Properties Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19896. PurchaseOrder Form: JSHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19997. Import Java Files dialog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20598. Agent Design Pane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20699. Test Run Agent Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207100.Agent Log . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208101.AgentContext View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208102.AgentRunner Properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209103.StatusServlet Servlet Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228104.Domino Access Builder Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242105.Domino Access Builder Project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250106.Connection Type Properties SmartGuide - Domino Access Builder . . . . 252107.Server Selection Properties SmartGuide - Domino Access Builder . . . . 252108.Database Browser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253109.Form Selection SmartGuide - Domino Access Builder . . . . . . . . . . . . . . 254110.Edit Form Generation Options - Domino Access Builder . . . . . . . . . . . . 254111.View Selection SmartGuide - Domino Access Builder . . . . . . . . . . . . . . 255112.Edit View Generation Options - Domino Access Builder . . . . . . . . . . . . . 255113.Package Selection SmartGuide - Domino Access Builder . . . . . . . . . . . 256114.Generated Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256115.Product List: Visual Composition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257116.Product Dialog: Visual Composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259117.Product View and Dialog: Visual Composition . . . . . . . . . . . . . . . . . . . . 261118.Product List Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262119.Product Dialog. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

xi

Page 14: Using VisualAge for Java To Develop Domino Applications

xii Using VisualAge for Java to Develop Domino Applications

Page 15: Using VisualAge for Java To Develop Domino Applications

Tables

1. SQL and Domino Mapping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472. PurchaseOrder Form Fields and Text (Part I) . . . . . . . . . . . . . . . . . . . . . 1343. PurchaseOrder Form Fields and Text (Part II). . . . . . . . . . . . . . . . . . . . . 1354. DisplayItemList Subform Fields and Text (Part I) . . . . . . . . . . . . . . . . . . 1425. DisplayItemList Subform Fields and Text (Part II) . . . . . . . . . . . . . . . . . . 1426. POItem Class Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1547. PO Class Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1598. DiscountRule Class Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1719. POApplet Class Fields . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17310. POApplet Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19611. Best Uses for Agent, Servlet and CGI Programs. . . . . . . . . . . . . . . . . . . 23512. ProductList Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25813. ProductDialog Connections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26014. ProductList and ProductDialog Connections . . . . . . . . . . . . . . . . . . . . . . 261

© Copyright IBM Corp. 1999 xiii

Page 16: Using VisualAge for Java To Develop Domino Applications

xiv Using VisualAge for Java to Develop Domino Applications

Page 17: Using VisualAge for Java To Develop Domino Applications

Preface

Domino is the most complete and powerful platform for building secure,collaborative Web applications. The Domino Application Server is an open,secure platform optimized to deliver collaborative Web applications thatintegrate your enterprise systems with rapidly changing business processes.

VisualAge for Java is IBM's award-winning Java development environmentthat allows you to build Web-enabled applications. VisualAge leads theindustry with proven support for building and testing Java applets, servlets,and Enterprise JavaBean components.

Using VisualAge for Java in a Domino environment is the best way to quicklyand easily develop and deploy Web applications to improve customerresponsiveness and streamline business processes.

This redbook explains how to use VisualAge for Java to develop Dominoapplications. First, we set the scene and present all the actors of thiscomputing environment: Java, with its capabilities to create state-of-the-artWeb applications; Domino and its Java support; and VisualAge for Java andits Domino support. Based on many examples, we explain how to createapplets, servlets, and agents.

Next, we put the theory into practice by showing how to develop a realisticDomino business application using VisualAge for Java. To help implement aclient/server architecture in your applications, the examples use manydistributed Java protocols such as CORBA, IIOP, JDBC, and RMI.

Finally, we introduce the Domino Access Builder feature of the new VisualAgefor Java Version 3 that creates customized Java beans to access Dominodatabases and services.

This book is written for managers and architects who want to understand theJava support of Domino, as well as developers who want to create Dominoapplications using VisualAge for Java.

© Copyright IBM Corp. 1999 xv

Page 18: Using VisualAge for Java To Develop Domino Applications

The Team That Wrote This Redbook

This redbook was produced by a team of specialists from around the worldworking at the International Technical Support Organization San Jose Center.

Christophe Toulemonde is a Senior ITSO Specialist for client/server andnetwork computing at the Application Development and Data ManagementITSO, San Jose Center. He writes extensively and teaches IBM classesworldwide on all areas of client/server and network computing. Before joiningthe ITSO, Christophe worked as a Technical Manager at an IBM subsidiary,Datablue, in France. You can reach him by e-mail at [email protected].

Gianfranca Rastelli is a Technical Specialist at IBM Milano, Italy. Sheprovides technical support for Lotus Notes/Domino application developmentfor internal and IBM customers, specializing in integrating workflow solutions.You can reach her by e-mail at [email protected].

John Toews is a Software Analyst/Developer at Onyx ComputersIncorporated in Toronto, Canada. He has 10 years of experience in thecomputing field and his areas of expertise include the design anddevelopment of Domino, Internet, and multimedia applications. Prior toworking at Onyx, he wrote technical and end-user documentation, andauthored edutainment titles. You can reach him by e-mail [email protected]

Christian Wegh is an IT specialist with IBM Germany. He has 3 years ofexperience in the design and development of Java applications. He holds adegree in computer science. You can reach him by e-mail [email protected].

Thanks to the following people for their invaluable contributions to thisproject:

John AkerleyInternational Technical Support Organization, San Jose Center

Isai ScheinbergIBM Toronto Lab

xvi Using VisualAge for Java to Develop Domino Applications

Page 19: Using VisualAge for Java To Develop Domino Applications

Comments Welcome

Your comments are important to us!

We want our redbooks to be as helpful as possible. Please send us yourcomments about this or other redbooks in one of the following ways:

• Fax the evaluation form found in “ITSO Redbook Evaluation” on page 297to the fax number shown on the form.

• Use the electronic evaluation form found on the Redbooks Web sites:

For Internet users http://www.redbooks.ibm.com/

For IBM Intranet users http://w3.itso.ibm.com

• Send us a note at the following address:

[email protected]

xvii

Page 20: Using VisualAge for Java To Develop Domino Applications

xviii Using VisualAge for Java to Develop Domino Applications

Page 21: Using VisualAge for Java To Develop Domino Applications

Part 1. VisualAge for Java Meets Domino

In this part, we set the scene and present all the actors of this computingenvironment to develop a Domino Java application using VisualAge for Java.

We first introduce Java as the programming environment that offerssignificant new opportunities for software development, interoperability andportable execution.

Then we present Domino, an integrated messaging and Web applicationsoftware platform for growing companies that need to improve customerresponsiveness and streamline business processes. Domino is a businessapplication server that delivers secure communication, collaboration over theintranet and the Internet.

Finally, we present VisualAge for Java, IBM's award-winning Javadevelopment environment, that allows you to build Web-enabled enterpriseapplications. VisualAge for Java supports the building and testing of Javaapplets, servlets, and Domino agents.

© Copyright IBM Corp. 1999 1

Page 22: Using VisualAge for Java To Develop Domino Applications

2 Using VisualAge for Java to Develop Domino Applications

Page 23: Using VisualAge for Java To Develop Domino Applications

Chapter 1. Java

In this chapter we give an overview of Java and an introduction to theprincipal concepts of the Java language. We focus our attention on Javaapplets and servlets.

We explain the protocols that you can use to implement a fully distributedarchitecture in which Java connects relational databases with JDBC,distributed Java objects with remote method invocation (RMI), or evendistributed non-Java objects with CORBA.

1.1 Overview

Java is not just a programming language; it is a platform that can be used tocreate and deliver information over any network.

"Write once, run everywhere"Java is portable and architecture-neutral for any system implementing theJava virtual machine (JVM). Programs written in Java can be distributed andexecuted on any client system that has a Java-enabled Web browser. You arefreed from having to write multiple versions for multiple platforms and evenfrom having to recompile for each platform. Because the applets run on theclient system, scalability and performance are no longer tightly tied to Webserver systems. High performance requirements are also addressed throughmultithreading, the ability to link native code, and the just-in-time compiler.

Object-oriented technologyJava applications are implementation-neutral. Because Java is trulyobject-oriented, you are free to distribute the application business logic in themanner that best fits your needs. Modifications are made easily andtransparently as business needs change.

Superior language characteristicsJava is an interpreted object-oriented language, similar to C++, which can beused to build programs that are platform independent in both source andobject form. Its unique operational characteristics, which span Web browserand network computers as well as servers, enable new client/server functionsin Internet applications while enforcing a discipline that makes softwaremanagement possible across almost any hardware platform.

To achieve platform independence, the Java language allows noplatform-dependent operations and it excludes some C++ functions such as apreprocessor, operator overloading, multiple inheritances, and pointers. All

© Copyright IBM Corp. 1999 3

Page 24: Using VisualAge for Java To Develop Domino Applications

Java programming is encapsulated within classes, and the developmenttoolkit includes an extensive set of class libraries that provide basic datatypes, system input and output capabilities, and other utility functions.

The Java compiler does not generate machine code. Instead, it generatesintermediate code called Java bytecode. This bytecode is interpreted by theJava interpreter, which executes the instructions on the particular hardwareplatform. The Java interpreter and run-time system are collectively called theJava Virtual Machine (JVM).

The interpreter also inspects the bytecode at execution time to ensure itsvalidity and safety to the machine environment. The isolation the Javainterpreter provides, coupled with the Java run-time systems provided byvendors, create a platform-independent virtual machine environment.

1.2 Java Definitions

When you write a program in an object-oriented language, you do not defineactual objects.You define classes of objects, where a class is a template formultiple objects with similar features. Classes embody all the features of aparticular set of objects. While a class is a generic template for a set ofobjects with similar features, an instance is the specific concreterepresentation of a class.

Every class in Java has two basic features:

• Attribute

Attributes are the individual things that differentiate one object fromanother and determine the appearance, state, or the other qualities of thatobject. Attributes of an object are defined in classes by variables. Aninstance variable defines the attributes of the object. The types and namesof instance variables are defined in the class, but their values are set andchanged in the object. Class variables, on the other hand, apply to theclass itself and to all instances (they are defined as static).

• Behavior

Class behavior determines how an instance of that class operates. Todefine an object’s behavior you create methods which are functionsdefined inside classes and that operate on instances of those classes.Class methods, on the other hand, apply to and operate on the class itself(they are defined as static).

4 Using VisualAge for Java to Develop Domino Applications

Page 25: Using VisualAge for Java To Develop Domino Applications

Every class in Java has to define a constructor which is used to build theclass with the proper parameters. A constructor has the same name as theclass.

Object-oriented programming also defines the following important concepts:

• Inheritance

Inheritance deals with the fact that all classes are arranged in a stricthierarchy. Each class in the hierarchy has one superclass (the uniqueclass above it in the hierarchy) and any number of subclasses (classesbelow it in the hierarchy). Subclasses inherit attributes and behavior fromtheir superclasses. At the top of the Java class hierarchy is the classObject; all classes inherit from this one superclass.

As far as inheritance is concerned, attributes can be divided into:

• Public: attributes which are accessible externally for reading andwriting.

• Private: attributes which are not absolutely accessible from outside,neither from other classes, nor from derived classes.

• Protected: attributes which are not accessible from outside, but onlyfrom the inherited classes and classes in the same package.

New objects have access to all the method names of their class and itssuperclasses, but method definitions are chosen dynamically when amethod is called. If you call a method of a class, Java first checks theobject's class for the definition of that method. If it is not defined, it looks inthe class's superclass and so on through the hierarchy tree until themethod definition is found.

When a subclass defines a method that has the same signature (samenumber and type of arguments) as a method defined in the superclass thenew method hides the superclass's method according to a process calledoverriding.

Attributes and methods which are defined as final cannot be overridden bythe derived classes.

• Interface

Although a single Java class can have only one superclass (due to singleinheritance) that class can also implement any number of interfaces. Aninterface is a collection of method names, without definitions, that can beadded to classes to provide additional behavior not included with thosemethods that the class defines itself, or has inherited from itssuperclasses.

Java 5

Page 26: Using VisualAge for Java To Develop Domino Applications

• Package

Packages in Java are a way of grouping together related classes andinterfaces in a single library or collection.

Java Class LibraryThe Java class library provides the set of classes that are guaranteed to beavailable in any commercial environment. Those classes are in the Javapackage and include among others the following basic packages:

• Language package (java.lang)

This package provides the elementary classes for strings, arrays andelementary data types.

• Utility package (java.util)

This package includes classes for the support of handling vectors, stacks,hash tables, encoding and decoding.

• I/O package (java.io)

This package includes classes for standard input and output, as well asfile I/O.

• Applet package (java.applet)

This package provides support for interacting with the browser.

• Abstract Window Toolkit (AWT) package (java.awt)

This package was used by us to build the GUI (graphical user interface). Itallows you to control the visual aspects of your application or applet.Objects such as buttons, scroll bars, text fields, lists and fonts areavailable in this class.

• Network package (java.net)

For communication with other applications, this package provides thebasic support needed to communicate with peer programs over thenetwork, as well as standard protocols such as TCP, FTP and URL access.

• JDBC package (java.sql)

This package provides support for accessing relational DBMS.

Java Development KitIf you want to develop Java applets or applications, you need to install theJava development kit (JDK) on your machine.

Each release of the JDK contains the following: the Java compiler, JVM, Javaclass libraries, Java applet viewer, Java debugger, and other tools. JDKVersion 2.1 is the latest set of Java technologies made available to licensed

6 Using VisualAge for Java to Develop Domino Applications

Page 27: Using VisualAge for Java To Develop Domino Applications

developers by Sun Microsystems. However, in this redbook we use the JDK1.1.6 since our tools and drivers support this version.

JDK is available on the Sun Web site for Windows platforms, and on the IBMJava Web site for IBM platforms (AIX, OS/2, OS/390 (UNIX Services),OS/400, and VM/ESA).

A number of third-party development environments (called integrateddevelopment environments, IDEs) are also available for developing in Java.To develop the sample application described in this book, we used IBMVisualAge for Java (see Chapter 3, “VisualAge for Java” on page 69 for adescription).

1.3 Java Programs

In this section we explain the different types of Java programs:

• Applet

• Application

• Servlet

• JavaBean

1.3.1 Java AppletsA Java applet is a small application program that is downloaded to andexecuted on a Web browser or network computer. A Java applet typicallyperforms the type of operations that client code would perform in aclient/server architecture. It edits input, controls the screen, andcommunicates transactions to a server, which in turn performs the data ordatabase operations.

Applets can edit screen input, generate screen output, and communicateback to the computer from which it was downloaded. Multiple applets canexecute concurrently.

The downloading of applets should not have a significant performance impacton response time because the applets are typically not very large. In fact,applets, by performing processing on the browser or network computer, canimprove the overall browser performance by eliminating iterations with theWeb server. Just as images are cached in Web browsers, so too are applets,thereby minimizing the frequency of applet downloading. A currentperformance consideration is the iterative compiling of the Java bytecode atthe time of execution.

Java 7

Page 28: Using VisualAge for Java To Develop Domino Applications

As Java applets can be downloaded from any site on the World Wide Weband run on a client’s system, Java-enabled browsers and tools put somerestrictions on what can be done by an applet. In particular:

• Applets cannot read or write the client’s file system.

• Applets cannot communicate with any other server other than the onewhich stores the applet.

• Applets cannot run any program on the client’s system.

• Applets cannot load programs native to the local platform, includingshared libraries such as DLLs.

All these rules are true for Java applets running Netscape or MicrosoftInternet Explorer. Other Java-enabled browsers or tools may allow you toconfigure the level of security you want. As an example the appletviewer toolin the JDK allows you to set an access control list for which directories anapplet can read or write. In addition to the applet restrictions listed, Javaitself, in its architecture, includes various forms of security and consistencychecking in the Java compiler and interpreter for all Java programs to preventdisallowed use of the language.

Writing an AppletAn applet is always a subclass of the Applet class. The Applet class, part ofthe java.applet package, provides much of the behavior needed to run theapplet inside a Java-enabled browser. Applets also take advantage of Java’sAWT, which provides behavior to create user interface-based applets andapplications. Although your applet may have additional classes to run, themain applet class actually triggers the execution of the applet. The mainapplet class always has the following syntax:

import java.applet.*;public class MyApplet extends java.applet.Applet {...}

Java requires that the applet subclass be defined as public; this is true for themain applet class, but not for the additional classes called by the applet mainclass.

An applet has a set of life-cycle methods that it must implement to provideinformation. These methods are the following:

• init() Method

8 Using VisualAge for Java to Develop Domino Applications

Page 29: Using VisualAge for Java To Develop Domino Applications

The init() method is executed when the applet is first loaded or reloaded.The initialization might include reading and parsing any parameters to theapplet, setting up an initial state, or loading images or fonts.

• start() Method

The start() method is executed every time the Web page is shown. Thismethod can be called many times during the life-cycle of the applet andalso every time the applet was previously stopped.

• stop() Method

The stop() method occurs when the reader leaves the page where theapplet is running.

• destroy() Method

The destroy() method enables the applet to clean up after itself just beforeit is freed or the browser exits.

• paint() Method

The paint() method enables the applet to draw something on the screen.You have to override the paint() method if your applet needs to have anactual appearance on the screen.

Applet SampleIn the following code example, the MyApplet applet prints a message on theWeb page.

import java.awt.*

public class MyApplet extends java.applet.Applet {Font f = new Font ("TimesRoman", Font.BOLD, 42);String user;

public void init(){user = getParameter("user");user = "Welcome " + user;}

public void paint(Graphics g){g.setFont(f);g.setColor(Color.red);g.drawString(user, 4, 36);}

}

In this example the init() method allows the use of parameters, while the realwork of the applet is done only in the paint() method. There is no need toimplement the methods start(), stop(), or destroy().

Java 9

Page 30: Using VisualAge for Java To Develop Domino Applications

To launch the applet, you can imbed it into an HTML page using the <applet>HTML tag. In the following HTML page, we define a title for the page and usethe <applet> tag to load the applet in the body of the page:

<html><head><title>My Applet</title></head><body><applet code="MyApplet.class" width=325 height=275><param name=user value="User"></applet><body><html>

The <applet> tag is used within HTML pages to indicate when applets are tohave control. It has the following attributes:

• code attribute indicates the name of the class file that contains the applet.In this case the class file must be in the same directory as the HTML file.To indicate that applets are in a specific directory use the codebaseattribute to indicate the pathname.

• width and height attributes are used to indicate the bounding box of theapplet.

• The param attribute indicates a parameter to pass to the applet whileloading.

• Other attributes can be inserted in the HTML page, among them one of themost useful is the archive attribute which is used to indicate a Javaarchive file, that is a collection of Java classes and other files packaged ina single file.

When a Java-enabled server is downloading a page and encounters the<applet> tag, it also downloads the applet bytecode in the same way itdownloads an image referenced by an HTML image tag. The Java-enabledbrowser, such as Netscape Communicator or Microsoft Internet Explorer,then interprets and executes the applet bytecode.

1.3.2 Java ApplicationsA Java application is a program written in Java that executes locally on acomputer. It allows programming operations in addition to those used inapplets which can make the code platform dependent. It can access localfiles, create and accept general network connections, and call native C orC++ functions in machine-specific libraries.

10 Using VisualAge for Java to Develop Domino Applications

Page 31: Using VisualAge for Java To Develop Domino Applications

1.3.3 Java ServletsA Java servlet is a protocol and platform-independent server-side softwarecomponent, written in Java. Servlets run on a Web server machine inside aJava-enabled server, that is, a server that can start the JVM to support theuse of Java servlets. Servlets dynamically extend the capabilities of theserver because they provide services over the Web, using therequest-response paradigm.

From a high-level perspective, the servlet process flow is:

1. The client sends a request to the server.

2. The server sends the request information to the servlet.

3. The servlet builds a response and passes it to the server. The response isdynamically built, and the contents of the response usually depend on theclient's request.

4. The server sends the response back to the client.

Figure 1 on page 11 shows the servlet process flow.

Figure 1. Servlet Process Flow

Because servlets are object bytecodes that can be dynamically loaded off theWeb, servlets are to the server what applets are to the client. However,servlets run inside servers, so they do not need a graphical user interface(GUI). In this sense servlets are also called faceless objects.

Writing a ServletThe Java Servlet API includes several Java interfaces and fully define the linkbetween a hosting server and servlets. You need to download the JSDK, fromthe JavaSoft Web site (http://java.sun.com), if you want to run or create your

Domino Server

Servlet

WebClient

request

response

Java 11

Page 32: Using VisualAge for Java To Develop Domino Applications

own servlets. The Servlet API is defined as an extension to the standard JDKand contains the following packages:

• javax.servlet

• javax.servlet.http

The Servlet interface provides for methods that manage the servlet and itscommunication with clients. When a servlet accepts a call from a client, itreceives two objects: one is a ServletRequest and the other is aServletResponse. The ServletRequest class encapsulates thecommunication from the client to the server, while the ServletResponse classencapsulates the communication from the servlet back to the client.

Because most servlets extend Web servers that use HTTP to interact withclients, the most common way to develop servlets is by specializing thejava.servlet.http.HttpServlet. This class implements the Servlet interface byextending the GenericServlet base class.

A servlet, like an applet, has a set of life-cycle methods that it must implementto provide information. The main life-cycle methods are:

• init () Method

The init() method executes only once when the Web server loads theservlet. Even though most servlets are run in multi-threaded servers, thereare no concurrency issues during servlet initialization, because the servercalls the init() method once, when it loads the servlet, and it will not call itagain unless it is reloading the servlet. A servlet continues to run until it isremoved from the server.

• service() Method

The service() method is called each time the servlet is requested.Typically most developers do not use the service methods, but they usethe doPost and doGet methods supplied by the HttpServlet class.

• doPost() Method

The doPost() method is invoked in response to a request from theserver through the POST method, typically from an HTML form. POSTmethods should be used whenever the request will modify someinformation on the server.

• doGet() Method

The doGet() method is invoked in response to a request from theserver through the GET, the conditional GET and HEAD methods,typically from a URL request or an HTML form. GET methods should

12 Using VisualAge for Java to Develop Domino Applications

Page 33: Using VisualAge for Java To Develop Domino Applications

be used whenever the request will not modify any information on theserver.

The Web server passes two parameters to the service() method.

• HttpServletRequest: encapsulates the data from the client, and inparticular contains an input stream for reading the browser’s requestand methods to retrieve methods from the request.

• HttpServletResponse: encapsulates the response to the client, and inparticular contains an output stream for writing information back to theWeb browser and methods to access the Hypertext Transfer Protocol(HTTP) header information.

• destroy() Method

The destroy() method is called when the servlet is removed from the Webserver.

Servlet SampleIn the following code example, the DemoServlet servlet prints a message onthe Web browser as a response to the GET method of the HTTP protocol.

The DemoServlet servlet defines only a doGet() method that sets the contenttype of the response header fields and writes a message back.

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class DemoServlet extends HttpServlet{

public void doGet (HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {

ServletOuputStream out;String Title = "Servlet Output";resp.setContentType("text/html");out = resp.getOutputStream();out.println("<HTML><HEAD><TITLE>");out.println(title);out.println("</TITLE></HEAD><BODY>");out.println("<H1>" + title + "</H1>");out.println("<P>This is the output from MyServlet.");out.println("</BODY></HTML>");out.close();}

}

Java 13

Page 34: Using VisualAge for Java To Develop Domino Applications

1.4 Java Beans

The JavaBeans specification is the standard component model for the Javalanguage. A Java object can be defined as a Java bean if all the object’s datafields are private and are only accessible through methods, known asaccessor methods. Beans can be visual components, such buttons or a list,or they can be nonvisual components that typically represent the businesslogic of the application.

A bean must be able to support all of the following:

• Properties: private data fields accessible through accessor methods: inparticular getter methods to get the value of a bean’s property and settermethods to set the value of a bean’s property.

• Events: the ability of beans to send event notifications of internal propertychanges to other beans, applications or scripting language. To implementthe communication between beans Java provides a so called delegationevent model which is built on three concepts: event sources, event objectsand event listeners. Event sources produce event objects; events areencapsulated in event objects and event listeners listen to receive andprocess event objects.

• Introspection: the ability of an object, external to a bean, to analyze howthe bean works.

• Customization: the ability of an object, external to a bean, to change theappearance and behavior of a bean.

• Persistence: the retention of a bean property until changed throughcustomization.

The JavaBeans specification is the component model used by VisualAge forJava (see 3.2, “Visual Composition Editor” on page 81) and because of thisspecification they can be used as black boxes—components whose internalstate is hidden—and, combined with other software components to build acomplete application.

1.5 Distributed Architecture

In this section we describe how to create a distributed application with Javausing technologies such as:

• JDBC

• CORBA

• RMI

14 Using VisualAge for Java to Develop Domino Applications

Page 35: Using VisualAge for Java To Develop Domino Applications

1.5.1 Java Database ConnectivityThe Java database connectivity (JDBC) is a Java API for executing SQLstatements. It consists of a set of classes and interfaces written in Java.JDBC provides you with a standard API to write database applications. UsingJDBC, you can send SQL statements to virtually any relational database.And, as the application is written using Java, you don't have to write differentapplications for different platforms.

The combination of Java and JDBC makes disseminating information easyand economical. Businesses can continue to use their installed databasesand access information easily even if it is stored on different databasemanagement systems.

Installation and version control are greatly simplified. A programmer can writean application or an update once, put it on the server, and everybody hasaccess to the latest version. And for businesses selling information services,Java and JDBC offer a better way of getting out information updates toexternal customers.

Two-tier and Three-tier ModelsThe JDBC API supports both two-tier and three-tier models for databaseaccess.

• In the two-tier model, a Java applet or application talks directly to thedatabase. This requires a JDBC driver that can communicate with theparticular database management system being accessed. A user's SQLstatements are delivered to the database, and the results of thosestatements are sent back to the user. The database may be located onanother machine to which the user is connected via a network. This isreferred to as a client/server configuration, with the user's machine as theclient, and the machine housing the database as the server. The networkcan be an intranet or the Internet.

• In the three-tier model, commands are sent to a "middle tier" of services,which then send SQL statements to the database. The databaseprocesses the SQL statements and sends the results back to the middletier, which then sends them to the user. The three-tier model makes itpossible to maintain control over access and the kinds of updates that canbe made to corporate data. Another advantage is that when there is amiddle tier, you can employ an easy-to-use higher-level API which istranslated by the middle tier into the appropriate low-level calls. Finally, inmany cases the three-tier architecture can provide performanceadvantages.

Java 15

Page 36: Using VisualAge for Java To Develop Domino Applications

Driver TypesJDBC drivers generally fit into one of four types:

• The JDBC-ODBC bridge provides JDBC access via ODBC drivers.NotesSQL (the Domino/Notes ODBC driver) may be used with theJDBC-ODBC bridge.

• A native-API partly-Java driver converts JDBC calls into calls on the clientAPI for the DBMS in question. This style of driver requires that somebinary code be loaded on the client machine. Domino Driver for JDBC is aType 2 driver.

• A net-protocol all-Java driver translates JDBC calls into aDBMS-independent net protocol which is then translated to a DBMSprotocol by a server. This net server middleware is able to connect itsall-Java clients to many different databases. This is the most flexible Javaalternative.

• A native-protocol all-Java driver converts JDBC calls into the networkprotocol used by DBMSs directly. This allows a direct call from the clientmachine to the DBMS server and is a practical solution for Internetaccess.

Figure 2 on page 16 shows all the types of JDBC drivers.

Figure 2. JDBC Driver Types

16 Using VisualAge for Java to Develop Domino Applications

Page 37: Using VisualAge for Java To Develop Domino Applications

IBM DB2 and Lotus Domino have built JDBC-based products. Othercompanies, such as Informix, Merant (previously Intersolv), Oracle, Sybase,Symantec, and WebLogic have endorsed the JDBC database access API.

Writing a JDBC ProgramJDBC was first introduced into the Java Development Kit (JDK) in Version 1.1and the classes and interfaces can be found in the java.sql package.

At a high level, JDBC allows:

• Establishing a connection with a database

• Sending SQL statements

• Processing the results

The following code fragment gives a basic example of these three steps. Ituses the Domino JDBC driver and connects to a Domino database. It selectsall the documents of the database using a view and prints the results back tothe Web.

public static void main(java.lang.String[] args) {Connection con;Statement stmt;ResultSet rs;

Class.forName("lotus.jdbc.domino.DominoDriver");con = DriverManager.getConnection(

"jdbc:domino/sg245424\\SG245424T.nsf/oxygen", "", "");stmt = con.createStatement();rs = stmt.executeQuery(

"SELECT LASTNAME, SALARY FROM \"Employee\\Last Name\"");while (rs.next()) {

String Name = rs.getString("LASTNAME");int Salary = rs.getInt("SALARY");System.out.println("Name "+ Name + ", Salary " + Salary);

}stmt.close();con.close();

} catch (Exception e) {System.out.println(e.getMessage());

}

A Connection object represents a connection with a database. A connectionsession includes the SQL statements that are executed and the results thatare returned over that connection. A single application can have one or moreconnections with a single database, or it can have connections with manydifferent databases.

Java 17

Page 38: Using VisualAge for Java To Develop Domino Applications

The standard way to establish a connection with a database is to call thegetConnection method:

DriverManager.getConnection

This method takes a string containing a URL.

The DriverManager class, referred to as the JDBC management layer,attempts to locate a driver that can connect to the database represented bythat URL. The DriverManager class maintains a list of registered Driverclasses, and when the method getConnection is called, it checks with eachdriver in the list until it finds one that can connect to the database specified inthe URL. The Driver method connect uses this URL to actually establish theconnection.

The JDBC URLs are built using a three-part name:

protocol:subprotocol:subname

The three parts of the JDBC URL are broken down as follows:

• The protocol in a JDBC URL is always jdbc.

• The subprotocol is the name of the driver or the name of a databaseconnectivity mechanism, which may be supported by one or more drivers.For example domino for a Domino database, db2 for a DB2 database.

• The subname represents a way to identify the database. It can vary,depending on the subprotocol. The point of a subname is to give enoughinformation to locate the database. If the database is to be accessed overthe Internet, for example, the network address should be included in theJDBC URL as part of the subname.

1.5.2 Common Object Request Broker ArchitectureCommon Object Request Broker Architecture (CORBA) is a specificationowned by a nonprofit group called Object Management Group (OMG).

CORBA provides a standard for a distributed computing environment in whichclient machines remotely invoke methods on objects residing on servermachines. This allows interconnection of objects and applications, regardlessof language, location or computer architecture.

We can summarize these concepts as follows:

• CORBA objects can be located anywhere on a network.

• CORBA objects can interoperate with objects on other platforms.

18 Using VisualAge for Java to Develop Domino Applications

Page 39: Using VisualAge for Java To Develop Domino Applications

• CORBA objects can be written in any programming language for whichthere is a mapping from OMG interface definition language (IDL) to thatlanguage. (Mappings currently specified include Java, C++, C, Smalltalk,COBOL and Ada.)

Figure 3 on page 19 shows the architecture of a CORBA-compliantapplication invoking multiple objects on multiple computers.

Figure 3. CORBA Architecture

CORBA defines components that communicate with each other:

• CORBA Client Components

The client is any application requiring remote services from CORBAenabled server.

• Client IDL Stubs

From the client's perspective, these local stub classes are the same asthe actual implementations. Internally these stub classes act as a localproxy for the remote server objects and define how clients invokecorresponding remote services on servers. Once a successful requesthas been made to instantiate a remote server object, a reference ID tothat object is returned. Future method requests on that remote objectare sent with the reference ID to the remote server and executed on

Java 19

Page 40: Using VisualAge for Java To Develop Domino Applications

the remote object via the CORBA server components with data beingreturned if required. This process is transparent to the programmer.

The client stubs are created by first defining your server interfacesusing the CORBA interface definition language (IDL). The CORBA IDLdefines the type of objects, their attributes, the methods they export,and the method parameters. The CORBA IDL is language neutral andtotally declarative, with no implementation details. There must be oneIDL definition per interface.

The client stubs also include code that encodes and decodes(marshalling) the requested operation and its parameters into aflattened message format that can be sent to the server. The generalinter-ORB protocol (GIOP) is a message and data format protocol forcommunications across the wire. GIOP defines message formats for allORB request/reply semantics. This message is passed to the clientORB.

• Client ORB

The object request broker (ORB) is the transportation bus for CORBAobject requests to and from remote objects.

The transport protocol between ORBs, Internet inter-ORB protocol(IIOP) specifies how GIOP messages are exchanged over a TCP/IPnetwork. Currently GIOP is only mapped to TCP/IP.

• CORBA Server Components

On retrieving IIOP requests, the server ORB uses the basic object adapter(BOA) in combination with the implementation repository to passparameters and method requests to the required server object using theserver stubs. The main server components are the following:

• Basic Object Adapter

The BOA is a run-time core ORB communication service forinstantiating server objects, passing requests, and assigning objectreferences.

• Server IDL Skeleton

The Server skeletons provide interfaces to each service provided bythe server and is created using an IDL compiler as described in theclient IDL stub section above.

• Implementation Repository

The implementation repository is a run-time storage of objectinformation such as the classes that a server supports, which objectsare instantiated, and their IDs.

20 Using VisualAge for Java to Develop Domino Applications

Page 41: Using VisualAge for Java To Develop Domino Applications

In 2.6.4, “Domino Java classes” on page 43 we discuss how the CORBAarchitecture is implemented within Domino R5.

1.5.3 Remote Method InvocationThe Java remote method invocation (RMI) allows an object running in oneJVM to invoke methods on an object running in another JVM. RMI providesfor remote communication between programs written in the Javaprogramming language.

RMI applications are often comprised of two separate programs: a server anda client.

• A typical server application creates some remote objects, makesreferences to them accessible, and waits for clients to invoke methods onthese remote objects.

• A typical client application gets a remote reference to one or more remoteobjects in the server and then invokes methods on them. RMI provides themechanism by which the server and the client communicate and passinformation back and forth. Such an application is sometimes referred toas a distributed object application.

Distributed object applications need to:

• Locate remote objects

Applications can use one of two mechanisms to obtain references toremote objects. An application can register its remote objects with RMI'ssimple naming facility, the RMI registry, or the application can pass andreturn remote object references as part of its normal operation.

• Communicate with remote objects

Details of communication between remote objects are handled by RMI; tothe programmer, remote communication looks like a standard Javamethod invocation.

• Load class bytecodes for objects that are passed around

Because RMI allows a caller to pass objects to remote objects, RMIprovides the necessary mechanisms for loading an object's code, as wellas for transmitting its data.

Figure 4 on page 22 shows an example of an RMI client/server application.

Java 21

Page 42: Using VisualAge for Java To Develop Domino Applications

Figure 4. Remote Method Invocation

The RMI distributed application uses the RMI registry to obtain a reference toa remote object. The server calls the registry to associate (or bind) a namewith a remote object. The client looks up the remote object by its name in theserver's registry and then invokes a method on it. Figure 4 also shows thatthe RMI system uses an existing Web server to load class bytecodes, fromserver to client and from client to server, for objects when needed.

Writing a RMI ProgramLike any other program, a distributed program built using RMI is made up ofinterfaces and classes.The interfaces define methods, and the classesimplement the methods defined in the interfaces and, perhaps, defineadditional methods as well. In a distributed application some of theimplementations are assumed to reside in different virtual machines. Objectswhich have methods that can be called across virtual machines are remoteobjects.

An object becomes remote by implementing a remote interface, which hasthe following characteristics:

• A remote interface extends the interface java.rmi.Remote.

• Each method of the interface declares java.rmi.RemoteException in itsthrows clause, in addition to any application-specific exceptions.

22 Using VisualAge for Java to Develop Domino Applications

Page 43: Using VisualAge for Java To Develop Domino Applications

RMI treats a remote object differently from a nonremote object when theobject is passed from one virtual machine to another. Rather than making acopy of the implementation object in the receiving virtual machine, RMIpasses a remote stub for a remote object. The stub acts as the localrepresentative, or proxy, for the remote object and basically is, to the caller,the remote reference. The caller invokes a method on the local stub, which isresponsible for carrying out the method call on the remote object.

On the server-side a skeleton is responsible for calling the server object.

To write an RMI program, follow these steps:

1. Design and implement the application components.

In this step you have to do the following:

• Create the remote interfaces which extend java.rmi.Remote andspecify the methods that can be invoked remotely by a client.

package demoimport java.rmi.Remote;import java.rmi.RemoteException;public interface ExampleInterface extends Remote {

...}

• Write the server program that extends java.rmi.UniCastRemoteObject.

import java.rmi.*;import java.rmi.server.*;import demo.*;public class ServerApplDemo extends UnicastRemoteObject

implements ExampleInterface {...}

• Write the client program which obtains a remote reference to the serverand performs the application functions. Clients that use remote objectscan be implemented at any time after the remote interfaces aredefined, including after the remote objects have been deployed.

2. Compile sources and generate stub and skeleton classes.

In this step, you have to:

• Compile the source files, which contain the implementation of theremote interfaces, the server classes, and the client classes.

You can use Sun’s Java compiler JDK or any Java IDE such asVisualAge for Java.

Java 23

Page 44: Using VisualAge for Java To Develop Domino Applications

• Generate the stubs and skeletons. RMI uses a remote object's stubclass as a proxy in clients so that clients can communicate with aparticular remote object.

You can use the rmic compiler provided with Sun’s JDK or any JavaIDE such as VisualAge for Java.

3. Run the distributed system.

To run the distributed system you need to:

• Instantiate the RMI server object on the server computer.

• The RMI object then:

• Sets a security manager

The security manager protects access to system resources fromuntrusted downloaded code running within the virtual machine. Thesecurity manager determines whether downloaded code has accessto the local file system or can perform any other privilegedoperations.

The security manager supplied as part of the RMI system is calledRMISecurityManager. This security manager enforces a securitypolicy similar to the typical security manager for applets. An RMIapplication could however define and use another SecurityManagerclass that gave more liberal access to system resources or, in JDK1.2, use a policy file that grants more permissions.

Here's an example of the code that creates and installs the securitymanager:

if (System.getSecurityManager() == null) {System.setSecurityManager(new RMISecurityManager());}

• Registers itself with the RMI Naming Registry on the server.

The system provides a particular remote object, the RMI registry, forfinding references to remote objects. The RMI registry is a remoteobject name service that allows remote clients to get a reference toa remote object by name. The registry is typically used only tolocate the first remote object an RMI client needs to use. That firstremote object then provides support for finding other objects. Thejava.rmi.Naming interface is used as a front-end API for binding, orregistering, and looking up remote objects in the registry. Once aremote object is registered with the RMI registry on the local host,callers on any host can look up the remote object by name, obtainits reference, and then invoke remote methods on the object. The

24 Using VisualAge for Java to Develop Domino Applications

Page 45: Using VisualAge for Java To Develop Domino Applications

registry may be shared by all servers running on a host, or anindividual server process may create and use its own registry, ifdesired.

• Invoke the client, which:

• Sets a security manager, if required

• Obtains a remote reference to the server object

For more information about the RMI architecture see the JDK documentation.

An example of using the RMI model is shown in “Purchase Order Applet” onpage 145).

RMI AdvantagesOne of the most important advantages of RMI is to allow dynamic codeloading. RMI is able to download the code of an object's class if the class isnot defined in the receiver's JVM. The type and the behavior of an object,previously available only in a single virtual machine, can be transmitted toanother, possibly remote, virtual machine. RMI passes objects by their truetype, so the behavior of those objects is not changed when they are sent toanother virtual machine. This allows new types to be introduced into a remotevirtual machine, thus extending the behavior of an application dynamically.

Java 25

Page 46: Using VisualAge for Java To Develop Domino Applications

26 Using VisualAge for Java to Develop Domino Applications

Page 47: Using VisualAge for Java To Develop Domino Applications

Chapter 2. Domino

Domino is a line of server software that supports your organization'smessaging and Web application needs. Domino helps you improve youreffectiveness by integrating all communication, collaboration and businessapplication needs. Domino servers are based on a single architecture, so youcan choose the one that meets your current needs knowing it has theflexibility and power to grow when you do.

Built on an open, unified architecture, Domino delivers securecommunication, collaboration and business applications. Domino R5 serversset a new standard for rich Internet messaging, ease of administration,integration with backend systems and reliability.

Domino Server FamilyThe Domino Server Family allows you to quickly and easily start with whatyou need today—whether that is messaging or applications—and extend yourDomino infrastructure investment whenever you are ready. The Dominoserver family is comprised of three core servers:

• Domino Mail Server

Domino Mail Server combines full support for the latest Internet mailstandards with Domino's industry-leading messaging capabilities— all inone manageable and reliable infrastructure. Its integrated, cross-platformservices include Web access, group scheduling, collaborativeworkspaces, and newsgroups—all accessible from a Web browser orother standards-based client.

Domino Mail Server is used for messaging only. Customers who want todeploy their own applications on the Domino server should considerDomino Application Server or Domino Enterprise Server.

• Domino Application Server

Domino Application Server is an open, secure platform optimized todeliver collaborative Web applications that integrate your enterprisesystems with rapidly changing business processes.

Domino Application Server combines integrated messaging andapplications server. It delivers best-of-breed messaging as well as anopen secure Web application platform. The server easily integratesback-end systems with front-end systems business processes.

• Domino Enterprise Server

© Copyright IBM Corp. 1999 27

Page 48: Using VisualAge for Java To Develop Domino Applications

Domino Enterprise Server delivers all the functionality of Domino Mail andApplication Servers, reinforced with clustering for the high availability andreliability required by mission-critical applications.

Clients for Domino R5.0Previous versions of Lotus Domino had one, all-purpose client that would beused by users, administrators, and application developers. With LotusDomino R4.6, a special client for developers called Lotus Notes Designer forDomino was introduced.

As a result of the strong focus on ease-of-use in the design of Lotus DominoR5.0, three individual clients are now available. They are:

• Notes R5: the user’s client

Notes R5 is state-of-the-art e-mail, calendaring, group scheduling, Webaccess and information management—all integrated in an easy-to-useand customizable environment.

• Domino Administrator R5: the administrator’s client

Domino Administrator is a new, integrated administration control panelthat provides simple, yet flexible administration for your Dominoenvironment.

• Domino Designer R5: the developer’s client

Domino Designer R5 is an integrated development environment. Itenables developers to rapidly build secure Web applications thatincorporate enterprise data and streamline business processes.

Most of the functionality in Lotus Domino can also be accessed from Webbrowsers.

In the following, we concentrate the description on the Domino ApplicationServer used for our tests.

2.1 Domino Application Server

Domino Application Server R5 allows you to integrate your Dominoapplications with the enterprise systems. It leverages current informationassets with built-in connection services for live access to relationaldatabases, transaction systems and ERP applications.

It is optimized for collaboration and provides comprehensive applicationservices like workflow and messaging, so you can easily build and manageintegrated, collaborative solutions.

28 Using VisualAge for Java to Develop Domino Applications

Page 49: Using VisualAge for Java To Develop Domino Applications

You can deploy and maintain the applications with its integrated developmenttools, standards support and unmatched server-to-server replication. ButDomino is also open as you can use your favorite HTML authoring tools, JavaIDEs and scripting tools to create Domino applications.

Domino Application Server is an open, secure platform optimized to supportrapid delivery of collaborative Web applications that integrate your enterprisesystems with dynamic business processes. Domino Enterprise ConnectionServices (DECS) provides rapid connectivity to enterprise data using a visualmapping interface.

Figure 5 on page 29 shows the different services of a Domino applicationserver available to Web applications.

Figure 5. Domino Application Services

CORBA/IIOP support lets you integrate Domino with your application’sarchitecture. This support extends Domino application services to Webclients allowing you to serve Lotus Notes clients and Web browsers with thesame application.

With its comprehensive development environment, the Domino ApplicationServer lets you move beyond static Web sites—to create high-value businesssolutions that include workflow, content management and highly flexible

Domino 29

Page 50: Using VisualAge for Java To Develop Domino Applications

security. With Domino, you can easily create self-service applications likee-commerce and customer care, and connect them to back-end systems.

The flexible security of Domino allows you to personalize access to data andapplications based on individual and group roles. It is also extended to HTMLfiles and other data, for pervasive security no matter how or where Webcontent is stored.

The Domino R5 HTTP engine delivers outstanding performance and Javaservlet support.

Domino Application Server offers the following services:

• Object store

Documents in a Domino database can contain any number of objects anddata types, including text, rich text, numerical data, structured data,images, graphics, sound, video, file attachments, embedded objects, andJava and ActiveX applets. The object store also lets your Dominoapplications dynamically present information based on variables such asuser identity, user preferences, user input, and time.

• Search engine

A built-in full text search engine makes it easy to index and searchdocuments stored in Domino and files in the file system.

• Security

Integrated X.509 support lets you register new users with Notes and/orX.509 certificates. S/MIME support ensures message integrity for all clienttypes; SSL V3 for IIOP and LDAP clients. Authentication via trustedthird-party directories reduces complexity and duplication of information.

• Directory

The directory supports a multi-enterprise infrastructure of any size andintegrates with other directories via full support for LDAP V3, the openstandard for directory access. Its extensible schema allow you to store anyinformation you choose.

• Workflow

With Domino workflow support, you can define processes to route andtrack documents, to coordinate activities both within and beyond yourorganization.

• Messaging

An advanced client/server messaging system with built-in calendaring andscheduling enables individuals and groups to send and share information

30 Using VisualAge for Java to Develop Domino Applications

Page 51: Using VisualAge for Java To Develop Domino Applications

easily. Message transfer agents (MTAs) seamlessly extend the system toSimple Mail Transfer Protocol (SMTP)/Multipurpose Internet MailExtension (MIME), X.400, and cc:Mail messaging environments. TheDomino messaging service provides a single server supporting a varietyof mail clients: Post Office Protocol V3 (POP3), Internet Message AccessProtocol V4 (IMAP4), Message Application Programming Interface(MAPI), and Lotus Notes clients.

• Development environment

Domino Designer is optimized to work with Domino, and features acomplete set of visual tools for rapid development and deployment ofsecure, e-business solutions. It supports your favorite tools for HTMLauthoring, Java development, and scripting.

• Domino objects

Domino offers a collection of software objects that expose Dominofunctionality to several language bindings including Java, JavaScriptLotusScript, and due in 1999, OLE and COM. This allows you to switchprogramming languages without having to learn new ways to program forDomino.

• Domino Enterprise Connection Services (DECS)

Domino Application Server includes DECS, for live access to enterprisesystems. DECS supports a wide range of enterprise systems, includingDB2, Oracle, Sybase, ODBC, EDA/SQL, SAP, PeopleSoft, JD Edwards,MQSeries, CICS, and more. Without programming, DECS allows you tocreate Web applications that access or update enterprise data inreal-time, via persistent, parallel, pooled connections.

Domino Application Server delivers reliability and manageability with:

• Transactional logging for Domino databases

• Backup support and APIs to allow tight integration with third-party backuptools on all Domino platforms, including NT, UNIX, AS/400 and S/390

• High availability services such as online indexing and databasecompaction, fast server restart and more

• Remote server management options

• Centralized control of Notes desktops

• Mail server capabilities

Domino 31

Page 52: Using VisualAge for Java To Develop Domino Applications

2.2 Domino and the Web

As shown in Figure 6 on page 32, Domino adds to the Lotus Notes server anHTTP task that allows Domino to serve both Notes clients and Web browsers.Domino automatically converts all Notes design elements and documents toWeb HTML pages, allowing users access to Notes databases either through aNotes client or a Web browser.

Figure 6. Domino Architecture

The Domino Web server examines the URL in the incoming request anddetermines if the request is for an item in a Domino database or if it is arequest for an HTML file in the file system.

• If the request is for an HTML file, Domino acts just like any other Webserver and serves the file to the Web client.

• When the request is for something in a Domino database, Dominointeracts with the database to serve the information to the Web client or toput information from the Web client into the database.

Domino supports URL extensions that expose functionality to the Web client.

Domino URL commands have the syntax:

http://your.web.server/DominoObject?Action&Arguments

32 Using VisualAge for Java to Develop Domino Applications

Page 53: Using VisualAge for Java To Develop Domino Applications

where:

• your.web.server is a Domain Name Server (DNS) entry or an IP address.• DominoObject is a Domino construct (a database, view, document, form,

navigator, agent, or other).

URL commands for accessing Domino objects use the following syntax:

http://your.web.server/Database/DominoObject?Action&Arguments,

where:

• Database is the database in which the Domino object resides.• Action is the desired operation on the specified Domino object, for

example: ?OpenDatabase, ?OpenView, ?OpenDocument,?EditDocument, ?OpenForm, and other.

• Arguments is a qualifier of the action, for example, Count = 10 combinedwith the ?OpenView action limits the number of rows displayed in a view to10.

2.3 Domino Database

With Domino, the Web site is organized through Notes databases designed inthe Notes Object store format. A Web database is something different from aNotes database if only for the viewing mechanism and for the fact that itresides on a server running the HTTP server task.

Domino databases manage documents, as opposed to relational databases,which manage tables. Unstructured or structured data as well as associatedprogramming logic are stored within the database. Documents can containany number of object data types including text, rich text, numerical text,structured data, images, graphics, sound, video, file attachments, embeddedobjects, Java and activeX applets.

A database contains three basic components: forms, fields and views. Inaddition, icons, help documents, navigators, agents, sections, actions,formulas and scripts play an important role in giving an applicationsophisticated automation and processing power. In Domino R5, Lotus addedsome new features such as outline, pages, and frameset.

DatabaseEvery database is essentially a complete application with its associated data.Databases can reside on a Domino server or on a Lotus Notes workstation.

Domino 33

Page 54: Using VisualAge for Java To Develop Domino Applications

DocumentsA Domino document is a container for data. Each document is effectively acollection of completed fields. A unique identifier is given to each documentupon its creation, and is used by the Domino database as a primary key.

A document’s design is held within a Domino form which specifies what adocument can contain in each field, for example, a number, a date, text, orrich text.

In Web applications, documents are individual Web pages that store the data.Documents can contain text, graphics, fields, applets, HTML, embeddednavigators and embedded views.

FieldsA field in a document contains one piece of information. In Web applications,fields can also contain Web pages, multimedia objects, graphics and files.

FormForms are design elements that give users a framework for entering newinformation in a database and for viewing existing information. It is possiblealso to associate forms with other design elements, such as views andnavigators, to create special Web effects.

NavigatorsNavigators provide a graphical way for users to find documents or takeactions in an open database without opening views. Domino convertsnavigators to HTML image maps on the Web. A navigator can be an entrypoint for a database if you design it to open automatically when a databaseopens.

ViewsViews are used to sort, list, filter and categorize documents. Applicationdevelopers design views with particular selection criteria so that they willdisplay lists of pertinent documents in a given order. Views allow users tonavigate multiple documents. Documents are accessed and opened fromwithin views. Views also contain other design elements, such as columns,buttons, and programming code which allow users to manipulate or changemultiple documents.

TemplatesA template is a pre-designed database that you can use to create newdatabases quickly. When creating a database from a template, you receive anumber of forms, views, and navigators that determine how the databaselooks and functions.

34 Using VisualAge for Java to Develop Domino Applications

Page 55: Using VisualAge for Java To Develop Domino Applications

AgentsAgents allow you to automate many tasks within Notes. For example, theycan be used for changing field values, sending mail messages, deletingdocuments or interacting with external applications. They can be run by usersin the foreground or automatically in the background. Agents can call otheragents, run on servers, or on workstations. Therefore, the user can use themto easily access, process, and manage data on other servers or in otherdatabases. They can be easily distributed because they can be replicated.

The following features are new in Domino R5:

OutlineAll applications created in Designer come with a default navigation structurecalled a folder pane. The folder pane, in a Notes client, displays the list ofshared views and shared folders in the left pane. In a Web browser, the folderpane displays as a list of shared views and folders at the top left of thebrowser window. You can customize the navigation structure of yourapplication by creating one or more outlines. An outline is the skeleton of yourapplication, where each entry represents a key piece of the application. Whenthe outline is embedded on a page or form, users can click on the outlineentries to take them where you want them to go.

You can completely customize an outline, reordering how items appear in thenavigation pane as well as including links to elements outside of yourapplication. You can control how the outline appears to users by changingtext and button styles.

Outline entries are fully programmable. You can add logic that controls howentries are rendered by the Notes client or Web browser.

By combining the outline with framesets, you can easily create a powerfulapplication interface for navigating your site. Your application can includemultiple outlines which launch links in target frames.

PagesA page is a database design element that structures and displaysinformation, including text, graphics, applets, and links. A page might includeHTML that you copy and paste or import, or it might be entirely composedusing the tools available through Designer, such as the text editor that letsyou enter and style text without entering HTML.

For example, a home page for a Web site typically displays information aboutthe site and provides a navigational structure for accessing other parts of thesite. A page can contain text, tables, graphics, imagemaps, applets, links,

Domino 35

Page 56: Using VisualAge for Java To Develop Domino Applications

embedded controls, such as an outline control, navigators, views, or folders,OLE objects and custom controls.

A page can contain anything a form contains with the exception of fields,subforms, layout regions, and some embedded controls. Because a pagecontains no fields, users cannot create a page as they would create adocument from a form, and users cannot enter data into a page. To make apage available to an end user, you can provide a document link to a page, oryou can display a page in a frameset. A page is best suited for displayinginformation, while a form is more suitable for gathering or processinginformation.

Pages are part of an application's design, and can be inherited from atemplate. Pages can be included in a full-text index, but they do not display inviews. You must explicitly display a page using a link or a programmedaction.

FramesetA frameset is a collection of multiple frames. A frame is one section, or pane,of the larger frameset window and is independently scrollable. By usingframesets, designers can create links and relationships between frames.Framesets provide the ability to leave one page displayed as users scroll orlink to other pages or databases.

2.4 Programming for Domino

Domino provides a variety of development alternatives for creatingapplications, thus enabling you to choose the most appropriate product. TheLotus Notes Designer client is the native development environment forDomino using LotusScript and LotusScript extensions (LSXs) as thedevelopment language. However, Lotus has also developed a set of APIs forC, C++, and Visual Basic. Third-party vendors (PowerBuilder, GuptaSQLWindows) have worked together with Lotus to integrate their owndevelopment tools.

FormulasYou can use the Lotus Notes formula language to develop applications. Theformulas are attached to certain objects in Domino, such as selectionformulas for views.

The formula language contains a set of built-in macros, functions, andcommands. The functions, referenced as @Functions in Lotusdocumentation, are prepackaged formulas. Domino has more than 100functions.

36 Using VisualAge for Java to Develop Domino Applications

Page 57: Using VisualAge for Java To Develop Domino Applications

The @Commands are built-in functions that enable you to programmaticallysimulate menu sequences.

The example below shows a formula to check whether or not the subject fieldcontains a value. It is a typical example of an input validation formula. If thefield is empty, you are prompted to enter a subject.

@If(Subject="";@Failure("Enter a subject for your document");@Success)

The formula language has no formal debugging mechanism. You can use the@Prompt function to check the value of the variables of interest.

The following example shows how you can check the LastName variable thatis calculated by using several nested commands:

LastName := @RightBack(@Left(@UserName; "/"); " ");@Prompt([Ok]; "Debugging: Value of LastName:", LastName)

The formula language does not provide enhanced program logic, such asfor-to and do-while clauses, or triggering mechanisms.

LotusScriptLotusScript is an embedded, BASIC scripting language with a powerful set oflanguage extensions that enable object-oriented application developmentwithin and across Lotus products. Its interface to Notes is through predefinedobject classes. Notes oversees the compilation and loading of user scriptsand automatically includes the Notes class definition. Two types of Notesobject classes are provided:

• Front-end user interface classes

UI classes provide features to emulate user actions. They also provideaccess to objects such as workspace, database window, field and rich-textfield.

• Back-end classes

Back-end classes represent Notes objects such as database, view, agent,document, and item. You can use these classes to manipulate Noteselements directly in LotusScript.

LotusScript extends the development capabilities of Domino by providing:

• A powerful, object-oriented programming language that leverages theknowledge of BASIC and Visual Basic. The LotusScript language also hasa set of extensions beyond Visual Basic that provide additional power andutility when writing applications with Domino.

Domino 37

Page 58: Using VisualAge for Java To Develop Domino Applications

• A complete integrated development environment (IDE) that you can use toenter, format and debug LotusScript programs. Because the IDE includesa fully capable debugger, with the ability to single step source lines, viewand modify the value of variables and of Notes object instances, setexecution breakpoints and so on, you can easily debug the mostcomplicated LotusScript program.

• Access to a broad range of Domino functions through Lotus Notesclasses.

• Access to external class libraries defined with the LSX toolkit. With theLSX toolkit, you can extend the function of LotusScript by creating yourown classes. Examples of extensions are the ODBC implementation andMQSeries. The classes can be used by any Lotus product that hostsLotusScript.

LotusScript cannot be used to build stand-alone applications. It always has torun in the context of the host application. This is also true for compilation anddebugging.

Events in Domino applications are used to trigger LotusScript programs. Thefollowing are examples of such events:

• Click a button.

• Enter editable fields.

• Initialize a form, agent, field, action, or button.

• Terminate a form, field, action, or button.

2.5 DECS

Domino R5 also includes the Domino Enterprise Connection Services(DECS) for building live connections between Domino pages and forms, todata from relational databases. To set up the connections, you simply use theDECS template application to identify your forms and fields that will containexternal source data, and to define the real-time connection settings. You canset up native connections for DB2, Oracle, Sybase, EDA/SQL, and more. ADomino server add-in task passes the real-time connection instructions to theDomino Extension Manager, which monitors the server for your user-initiatedevents. When events are intercepted (such as opening a form), the extensionmanager transfers the appropriate query to the external source, whichperforms the query on behalf of the end user. Results are presented to theuser in real time, as if the data were stored natively in Domino. No coding isrequired when using DECS.

38 Using VisualAge for Java to Develop Domino Applications

Page 59: Using VisualAge for Java To Develop Domino Applications

2.6 Domino and Java

Domino is a complete Web application server which fully supports the Javaenvironment. Domino applications can be written in Java as you can callDomino objects from a Java program. Domino supports JDBC calls to allowJava programs access to Domino data. Domino R5 also supports CORBA tobuild distributed Domino applications.

2.6.1 Programming LanguageDomino R5 supports many Internet-models of programming, so you canchoose your favorite language when designing Web applications—whetherthat language is JavaScript, Java, HTML 4.0, or LotusScript.

Java and JavaScript support are now both available within Designer. TheDomino Designer R5 includes a Java editor and Virtual Machine (JVM) fordeveloping the application. This allows you to create and compile Javaagents, and edit all scripts and formulas, all from within Designer.

With native support for JavaScript and HTML in the Notes client, you can nowdesign applications that run the same on the Web as they do within Notes. Inaddition, Domino R5 allows you to use third-party design tools, such asNetObjects Fusion, NetObjects ScriptBuilder, and IBM VisualAge for Java.

From a Java program coded as an application, a Domino agent, an applet, ora servlet, you can call into the Domino object interface. In Domino R5, youneed to import the lotus.domino package. The lotus.domino package has thesame content as the R4.6 lotus.notes package, and supports the classes,methods, and enhancements of the new release.

The lotus.domino classes allow you to access named databases(lotus.notes.Database class), views and folders (lotus.notes.View class), anddocuments (lotus.notes.Document class) within a database, and items withina document (lotus.notes.Item and lotus.notes.RichTextItem classes). Thesession class (lotus.notes.Session class) is the root of the Domino objecthierarchy, providing access to the other Domino objects, and represents theDomino environment of your Java program.

2.6.2 CORBA SupportDomino R5 unveils support for CORBA, so you can build robust, distributedapplications. The ORB technology and Java allow you to create clientapplications that are dynamically loaded from the server with transparentaccess to the server-side Domino objects. While Notes client applicationshave been able to access Domino objects for quite some time, CORBA and

Domino 39

Page 60: Using VisualAge for Java To Develop Domino Applications

IIOP support in Domino R5 expand this access to Web clients. Your primaryaccess to this ORB is through Java applets or applications. For example, youcan place a custom Java applet on a form and have that applet accessobjects in either the Notes client or a Web browser. For the Notes client, youare actually using the local Java interfaces. For the browser, you are using theCORBA-remote objects; that is, the applet uses IIOP to connect back to theORB on the server.

CORBA allows you to create client-side objects that "talk" IIOP across thewire to the server-side ORB, which is hard-wired to Domino’s back-endclasses for better performance. The main purpose is to offload the server byprojecting its services to the client. Browser applications can then executelocally with the context of the Domino server, so for instance, you can interactwith your server-based mail locally, without involving the server in each usertransaction.

With support for CORBA and IIOP, Domino allows you to now createclient/server Web applications that take advantage of the Domino objects andapplication services. In addition, you can now access back-end relationaldatabases for enhanced data integration using DECS. In previous releases,when you designed a Web application, the Domino objects classes (formerlyknown as the remote back-end classes, or the Notes Object Interfaces orNOI) allowed you to access data that was not on display in the browser.These back-end classes were LotusScript or Java objects. In R5, theseobjects are available to the browser using CORBA (see Figure 7 on page 41).

40 Using VisualAge for Java to Develop Domino Applications

Page 61: Using VisualAge for Java To Develop Domino Applications

Figure 7. Domino CORBA Architecture

What this means is that now your Web application is similar to your Notesapplication in terms of programmability. In a Notes application, you couldalways manipulate data that was on display and data in other databases. In aWeb application, you had to wait for a user to open or save a Web page toaccess this same data. CORBA allows you to access the data without theuser opening or saving the document; instead, you can use Java orJavaScript on a W3C event.

You can also embed a CORBA applet in a document or a form using the sameprocedure as for any other applet. You can use a browser to view embeddedCORBA applets on a Domino server. It is no longer necessary to set alternateHTML. A CORBA property box setting tells Domino to provide the HTMLsource that the applet needs to make an IIOP connection back to the server.

2.6.3 CORBA ImplementationDomino R5 uses CORBA to access Java programs on remote clients such asapplets in browsers and stand-alone Java applications to access the Dominoobjects on the Domino server. From an implementation standpoint, a remoteclient instantiates and references Domino objects as if they were resident at theclient. In fact these objects are instantiated at the Domino server. When the client

Domino 41

Page 62: Using VisualAge for Java To Develop Domino Applications

is referencing these objects it is actually communicating with the objects on theserver. This is seamless to the programmer (see Figure 8 on page 42).

Figure 8. Domino CORBA Implementation

Java Client IDLThere is one IDL definition file per Domino object C++ class that is exposedto CORBA. IDL files are published for developers to create their own stubs.The Java Client IDL stubs are contained in the lotus.domino package in theNCSO.jar file. This jar file also contains the Java Client ORB classes.

The jar file is automatically loaded down to a browser client if it is designatedas a CORBA applet via the properties box.

Domino R5 Java Client ORBThe Domino R5 Java Client ORB is essentially a complete Server ORB buthas been stripped down and compressed. It also has enhanced security,allowing clients to use SSL to create authenticated sessions with the server.

The Java Client ORB classes are contained in the NCSO.jar file. Currently,the ORB is instantiated once per getSession() method invocation. Twoapplets could have more than one instantiation of the ORB per HTML page.Technologies like the InfoBus could fix this situation by sharing the sameSession object reference.

42 Using VisualAge for Java to Develop Domino Applications

Page 63: Using VisualAge for Java To Develop Domino Applications

Domino R5 Server ORB ImplementationThe Server ORB is the "broker" which receives requests from objects toaccess other objects. It functions as a sophisticated router which passes therequested information to the requested object. It also passes informationback to the requester, as necessary.

The R5 ORB allows Domino objects to load and respond to client IIOPrequests. Its primary use is for doing client-side processing in Domino Webapplications. The R5 ORB is a modified version of IBM's ORB. A significantportion of the original IBM ORB has been stripped out, including the InterfaceRepository. Improvements have also been made to address issues such asscalability. Other customer created ORBs may also run on the Domino server.

On Windows NT, this ORB is released as a DLL. The two things Lotuseliminated from the ORB (by hard-wiring) are the Location Service and theName Service. Other than that it is a standard CORBA object server.

This Server ORB process can be loaded at server startup by placing it in thenotes.ini file:

ServerTasks =<other tasks>,http,diiop

The Server ORB listens to IIOP requests via a different port than HTTP. Thisport can be changed via the Server Document.

2.6.4 Domino Java classesYou can access Domino objects using Java programs since Release 4.6 ofDomino. However, support has changed with Domino R5. In the following weexplain what can be done with both releases.

Domino R4.6In R4.6 the Domino Java library is provided with the Notes.jar file whichcontains the lotus.notes classes—the notes object interface (NOI) in R4.6terminology. Using the NOI classes, you can create Java programs thataccess named databases, views, documents, and other back-end Dominoobjects. However, you need to run these Java programs on a machine wherethe NOI classes and a Domino client are installed.

The Java library allows the same functionality as the LotusScript interface,but you can have some additional advantages provided by using Java like:

• Multithreading

• Stand-alone application development

• Easy network access

Domino 43

Page 64: Using VisualAge for Java To Develop Domino Applications

The Domino R4.6 NOI classes:

• Can support only back-end classes

• Include properties that are accessed through methods

Domino R5In Domino R5, the NOI have been renamed to Domino Objects. Domino R5uses CORBA to allow remote Java programs to access remote Dominoobjects on a Domino server. The client Java program (a stand-aloneapplication or an applet) through IIOP talks over the network to a Dominoserver automatically using the same DOM objects.

In R5 the Domino Java Library is provided with the following packages:

• Notes.jar

Notes.jar contains the high-level lotus.domino package, thelotus.domino.local package for local calls, and the R4.6 lotus.notespackage to provide backward compatibility with applications written withDomino R4.6.

• NCSO.jar

NCSO.jar contains the lotus.domino package for CORBA. The package,used by remote Java applications and applets only, contains the high-levellotus.domino package and the lotus.domino.corba package for remotecalls.

With reference to the CORBA architecture, the Domino Java library containsthe Java client IDL stubs and the Java client ORB classes.

The server ORB is the broker which receives requests from objects to accessother objects. It functions as a sophisticated router which passes therequested information to the requested object. It also passes informationback to the requester, as necessary.

The Domino R5 ORB allows DOM objects to load and respond to client IIOPrequests. Its primary use will be for doing client-side processing in DominoWeb applications. This ORB is released as a DLL (NORB.DLL).

2.6.5 Domino Driver for JDBCThe Domino Driver for JDBC allows Java programmers to use any JDBCstandard enabled application tool to access Lotus Domino databases aseasily as any relational database.

44 Using VisualAge for Java to Develop Domino Applications

Page 65: Using VisualAge for Java To Develop Domino Applications

Domino Driver for JDBC makes Domino databases "look" like other relationalback-end source to the SQL tool or application interface by producing resultsets that mirror the relational model. An application can also perform a "SQLJoin" of data from Domino with data from a relational database such asOracle, Sybase, or DB2 (see Figure 9 on page 45).

Figure 9. Domino Driver for JDBC

JDBC provides Java programmers with a uniform interface to a wide range ofrelational databases, and provides a common base on which higher leveltools and interfaces can be built. JDBC is now a standard part of Java.

The Domino Driver for JDBC is another step in the Lotus commitment to openstandards and accessibility to Domino databases and services so thatcustomers can integrate Domino into any corporate system regardless oftheir enterprise configuration or tools selection.

Product features include:

• Java standard access to Domino 4.5x and 4.6x databases

• Compatible with Netscape Communicator 4.05

• Compatible with Microsoft Internet Explorer 4.01 with service pack 1

Domino 45

Page 66: Using VisualAge for Java To Develop Domino Applications

• Includes signed and unsigned version for maximum flexibility whencreating Java applets which use JDBC

• Year 2000 ready so correctly reads and interprets dates in 2-digit(mm/dd/yy) and 4-digit (mm/dd/yyyy) format

• Tested with IBM's Visual Age for Java, IBM's WebSphere, Lotus eSuiteDevPack, Borland's JBuilder and Symantec's Visual Cafe Web applicationdevelopment tools

• Multithreaded for Web use

ClassesThe Domino Driver for JDBC implements JDBC interfaces as the followingmain classes:

• lotus.jdbc.domino.DominoDriver class

Domino implements the java.sql.Driver interface in its DominoDriver class.

• lotus.jdbc.domino.DominoConnection class

A connection represents a session with the Domino driver for JDBC. Youneed a connection to execute SQL statements and get the results.

• lotus.jdbc.domino.DominoStatement andlotus.jdbc.domino.DominoPreparedStatement Classes

You use a statement object to execute an SQL statement and obtain aresult set.

A prepared statement is a compiled SQL statement that may handleparameters.

• lotus.jdbc.domino.DominoResultSet class

Using the ResultSet object, you have access to a table of data generatedby executing an SQL statement. The table rows are retrieved in sequence,but columns within a row can be accessed in any order.

• lotus.jdbc.domino.DominoResultSetMetaData class

You use this class to find out the types and properties of the columns in aresult set.

• lotus.jdbc.domino.DominoDatabaseMetaData class

The DatabaseMetaData class provides information about the database asa whole.

46 Using VisualAge for Java to Develop Domino Applications

Page 67: Using VisualAge for Java To Develop Domino Applications

Universal RelationThe Domino Driver for JDBC recognizes both Domino forms and views astables. Table 1 on page 47 shows how SQL components map to Dominocomponents.

Table 1. SQL and Domino Mapping

In addition to forms and views, the Domino database contains a table that hasthe same name as the database. This table is called the Universal Relation.The Universal Relation contains all fields defined in all forms in the Dominodatabase. The Universal Relation is the only true table in a Domino database.As a result, SQL tables created with the Domino Driver for JDBC behavemore like SQL views than traditional relational database tables.

For example, with the JDBC driver, you can create a Domino form with theCREATE TABLE statement. However, the DROP TABLE statement deletesthe Domino form, but it does not delete any data from the database. UsingDROP TABLE with the Domino Driver for JDBC is like deleting an SQL view.The data remains in the database. You can view the data through other formsor views that use the same field names, or by referencing the UniversalRelation table.

2.6.6 Lotus Connectors Java ClassesThe Lotus connector Java classes provide programmatic access to enterprisedata through a common set of classes. The programmer uses a single modelno matter the enterprise source. Programming provides more control andadditional capabilities over DECS and LEI.

SQL Component Domino Component Comments

Table Form,View,orUniversal Relation

Domino forms and views are recognizedas tables. However, a Domino databasecontains only one real table, referred toas the Universal Relation. This table hasthe same name as the database.

Column Form FieldorView Column

Avoid the use of column names that areJDBC/ODBC or SQL reserved words orthat contain characters other thanalphabetics, numeric, dollar sign ($), orunderscore.

Index View All sorted columns refer directly to fieldsin a single form.

View View Except for private view, all Domino viewsare reported as SQL views.

Domino 47

Page 68: Using VisualAge for Java To Develop Domino Applications

The classes use the same connectors as DECS and LEI to access theenterprise data.

ClassesThe Lotus Connectors classes are imported in the Java program using thefollowing statement:

import lotus.lcjava.*;

The LC classes become available:

• lotus.lcjava.LCSession class

You must create an LCSession object before using any other LC Javafacilities. The LCSession object contains global state information and errorinformation.

• lotus.lcjava.LCConnection class

The LCConnection class represents an instance of a connector to provideaccess to an enterprise system. Multiple connections can be allocated to asingle connector.

• lotus.lcjava.LCFieldList class

The LCField class is the primary class for manipulating data through aconnection. It binds fields together with names and an implied order.

• lotus.lcjava.LCStream class

The LCStream class is a general class for text and binary data.

• lotus.lcjava.LCCurrency class

The LCCurrency class represents fixed point data.

• lotus.lcjava.LCDatetime class

The LCDatetime represents date and time data.

• lotus.lcjava.LCDatetimeParts class

The LCDatetimeParts class supports LCDatetime and consists of publicvariables to access date and time data.

2.6.7 Domino Java ConfigurationYou can set the configuration settings for the Domino Web server:

• With R4.6, using the HTTP section of the Server document included in theserver’s Address Book.

48 Using VisualAge for Java to Develop Domino Applications

Page 69: Using VisualAge for Java To Develop Domino Applications

• With R5, using the HTTP tab of the Internet Protocol section in the Serverdocument (Figure 10 on page 49) included in the server’s DominoDirectory.

For more detailed information see Domino Administration documentation.

Figure 10. Domino Server Document Setup

Domino Initialization FileIn both releases, to load the HTTP task at server startup, use the followingcommand in the Domino initialization file (notes.ini):

ServerTasks = <other tasks>,HTTP

In R5 only, you have to load the server ORB into memory on the Dominoserver using the DIIOP server task. To load the HTTP task and the DIIOPserver task at server startup use the following command in the Dominoinitialization file (notes.ini):

ServerTasks = <other tasks>,HTTP,DIIOP

IIOP ConfigurationThe server ORB listens to IIOP requests using a different port than HTTP.Configuration settings for the Domino ORB are stored in:

• The Ports - Internet Ports - IIOP Server tab in the Server documentincluded in the server’s Domino Directory (see Figure 11 on page 50). Inthis panel, you have to set up the TCP/IP port number on which the DIIOPtask will listen on.

Domino 49

Page 70: Using VisualAge for Java To Develop Domino Applications

Figure 11. Configuration Settings for Domino ORB - Internet Ports

• The Internet Protocols - IIOP tab in the Server document included in theserver’s Domino Director (see Figure 12 on page 50) where you specifythe number of threads the DIIOP server tasks can process at the sametime.

Figure 12. Configuration Settings for Domino ORB - Internet Protocols

2.7 Domino Java Program Types

You can access Domino objects from different types of Java programs:

• Java Applet

• Java Agent

• Java Servlet

• Java Application

50 Using VisualAge for Java to Develop Domino Applications

Page 71: Using VisualAge for Java To Develop Domino Applications

2.7.1 Java AppletYou can include a Java applet in the rich text field of the following elements ofa Domino application:

• Form: the applet is included in each document created with that form.

• Document: the applet is available only in the document.

• Page: the applet is available only in the page (only in R5).

Some requirements and restrictions have to be taken in consideration whenusing Java applets in Domino applications:

• To include Java applets in an application, you have to install DominoDesigner.

• Supported browsers include Internet Explorer 3.0 or 4.0 and Netscape 3.0or 4.0.

• Java applets created with Notes 4.6 and 5.0 do not work with previousreleases of Notes, unless the applet is stored on the Web and it has noparameters.

• Java applets created with Notes 4.5 work with Notes 5.0. If you use Notes5.0 to change the applet parameters, the applet is saved as a 5.0 appletand will no longer work in 4.5.

Writing the AppletIn 1.3.1, “Java Applets” on page 7 we showed how to write an applet whichmust extend the Applet class and implements the standard init(), start(), end()and stop() applet methods.

In Domino R5, using the Domino Java classes, you can create applets thatperform Domino tasks, such as opening a session and retrieving informationfrom a database access control list. The Domino server can host the appletand when a client requests it, download the applet to the browser. The appletmust extend AppletBase. This class already implements the standard init(),start(), end() and stop() applet methods, therefore you cannot create (oroverride) these in your applet. Instead call the notesAppletInit(),notesAppletStart(), notesAppletEnd(), notesAppletStop() methods. You donot have to distinguish between local and remote access, because theAppletBase class makes local calls if the applet is running through the Notesclient and remote CORBA calls if it is running through a Web browser.

To access a Session object within your applet, use the getSession() methodof the AppletBase class. The getSession() method instantiates and initializesthe client-side ORB as well as requests a remote session object referencefrom the Domino server.

Domino 51

Page 72: Using VisualAge for Java To Develop Domino Applications

Each applet on a HTML page invoking the getSession() method instantiatesanother client ORB. As this situation has to be avoided, methods forinter-applet communication such as the InfoBus technology may be used toovercome this problem.

The following example shows how you can create an applet that accessesDomino objects and prints the name of the platform on a text area.

import lotus.domino.*;public class platform extends AppletBase {

java.awt.TextArea ta;

public void notesAppletInit() {setLayout(null);setSize(500,200);ta = new java.awt.TextArea();ta.setBounds(0,0,250,100);add(ta);ta.setEditable(false);setVisible(true);}

public void notesAppletStart() {Session s;try {

s = this.openSession();if (s == null) {

ta.append("Unable to create a session with the server");return;

}String p = s.getPlatform();String v = s.getNotesVersion();String u = s.getCommonUserName();ta.append("Platform = " + p + "\n");ta.append("Notes Version = " + v+ "\n");ta.append("User = " + u+ "\n");

} catch (Exception e) {e.printStackTrace();

}}

Installing Applets In DominoTo install a Java applet in a Domino application, you have to do the following:

1. Enable Java applets on the workstation.

52 Using VisualAge for Java to Develop Domino Applications

Page 73: Using VisualAge for Java To Develop Domino Applications

Before you can use a Java applet in a Domino application from a LotusNotes client, you must set up your workstation to enable Java applets.

Launch Lotus Notes client, choose File - Preferences - NotesPreferences. In the Basics tab, scroll down the Advanced Options list andselect Enable Java applets (see Figure 13 on page 53).

Figure 13. Notes Preferences Window

If you want to link to applets on the Web, make sure your Locationdocument specifies a valid Web proxy.

2. Create the applet in Domino.

To create an applet in Domino, you can either import the required appletfrom your workstation or a file server, or link to an applet on the Web. Youcan create the applet in a Domino form, a page, or a rich text field of adocument.

Launch Domino Designer, open the form, page, or rich text field where youwant to create the applet, and choose Create - Java Applet.

In the Create Java Applet dialog box (see Figure 14 on page 54), youhave to select between two options:

• Import the applet from the file system giving the path for the appletfiles in Base Directory and the name of the main class in ClassName.

• Link to an applet on a Web browser, giving the URL where theapplet files are stored in Base URL and the name of the main classin Class Name.

Domino 53

Page 74: Using VisualAge for Java To Develop Domino Applications

Figure 14. Create Java Applet Dialog Box

When you import an applet, the files are attached as hidden files to theform, document, or page where you include the Java applet. When youlink to an applet, files are stored on the Web and a URL reference to thosefiles is stored in the form, document, or page where you include the Javaapplet.

The Locate button allows you to select all related files for the applet. Formost applets, you have to select all class and resource files. Source filesare required only if you plan to send the applet to another user who wantsto export them and change the applet.

Figure 15. Locate Java Applet Files Window

54 Using VisualAge for Java to Develop Domino Applications

Page 75: Using VisualAge for Java To Develop Domino Applications

Browsing for the .jar file inserts the filename with a .CLASS extension inthe Class Name field. In some cases, the file name and the main classname are the same; in case they are different you have to edit whatappears in the Class Name field to be the correct main class name.

If you import an applet that is packaged as an archive file you have toconsider the browsers the application users have:

• For Microsoft Internet Explorer clients, include the .CAB file.

• For Netscape Navigator clients, include the .ZIP and .JAR files.

If Web clients are likely to use either or both browsers, include .CAB,.JAR, and .ZIP files. Domino creates the appropriate parts of the APPLETtag for these files. Navigator ignores the CABBASE (or CABINETS)parameter and Internet Explorer ignores the ARCHIVE attribute.

3. Set up applet parameters, attributes, and properties.

Using the Programmer's pane and the Properties box you can set upapplet parameters, attributes, and properties. Some applets require thatyou set parameters or attributes before you can run them.

Figure 16 on page 55 shows how to specify the applet parameter namesand values. If you are running an applet through a browser, you can addJavaScript to a form or document to interact with the applet by calling itspublic methods or setting/getting its public properties.

Figure 16. Applet Parameters Programmer’s Pane

CORBA AppletsApplets that access Domino objects from the Web require some additionalsteps to secure access.

If you choose to link to an applet on a Web server, you have to specify thebase URL and the applet class name. The NCSO jar and cab files must beloacted in the HTML directory on the Domino server.

If you choose the import option, you have to specify that the applet usesDomino CORBA classes using its properties box (see Figure 17 on page 56).

Domino 55

Page 76: Using VisualAge for Java To Develop Domino Applications

Figure 17. Applet Parameters

When this option is selected, Domino automatically includes the NCSO.jar fileand adds applet parameters to the applet HTML tag before serving thedocument to the Web browser:

<APPLET WIDTH="300" HEIGHT="500"CODEBASE="/sg245425.nsf/cb77cc059215d0488825673c006c4a9d/$FILE"CODE="itso.sg245425.applet.Db2DominoApplet.class"ARCHIVE="Db2DominoApplet.jar,db2java.zip,NCSOC.jar">

<PARAM NAME="NOI_IOR"VALUE="IOR:01ffffff2900000049444c3a6c6f7475732f646f6...........ffffff00000000"><PARAM NAME="NOI_COOKIE_URL" VALUE="/sg245425.nsf?GetOrbCookie"></APPLET>

The NOI_IOR parameter is the object reference to the Domino server. This isthe object on which you call the getSession() method.

56 Using VisualAge for Java to Develop Domino Applications

Page 77: Using VisualAge for Java To Develop Domino Applications

The NOI_COOKIE parameter ensures single user login; that is, the CORBAapplet is not challenged for a user name and password again. The cookiecomes from the server when the client logs on.

If the applet is running within a Lotus Notes client, this checkbox option isignored, the two extra parameters are not added, and the applet can accessthe local Domino APIs.

To avoid security risk you have to enforce the applet security using theSecurity Options button on the Basic tab of the File - Notes -NotesPreferences window (Figure 18 on page 57).

Figure 18. Java Applet Security Options

2.7.2 Java AgentsDomino agents are discrete, embedded programs that perform a specific task ina database. They are not tied to a specific Domino view or form. This agentconcept is almost unique to Domino as an application server and its Notesclients.

Since R4.6, Domino agents have full access to the standard Java run-timeservices. They can access Notes databases directly, using Domino Javaclasses and any other resources (database, URLs, and network) using otherJava libraries (with the appropriate import statement, for example JDBC).Domino agents do not have a user interface, but rely on the Notes userinterface.

Domino agents written in Java can be multithreaded, making use of thejava.lang.Thread class. This gives agents written in Java an advantage overthose written in LotusScript.

There are no software prerequisites for invoking an agent from a Webbrowser. The agent will always run on the Domino server and it is the Dominoserver that must meet any software prerequisites.

Domino 57

Page 78: Using VisualAge for Java To Develop Domino Applications

Writing an AgentAn agent extends the AgentBase class, which extends the NotesThreadclass. The class that contains the agent code must be public.

To access Domino, it imports the Domino Java classes (lotus.notes.* inDomino R4.6 or lotus.domino.* in Domino R5).

The entry point for the Java Domino agent is the NotesMain() method. Othermethods can be called from NotesMain(), but NotesMain() is where theexecution of functional code starts.

For output to browsers, assign a PrintWriter object using the getAgentOutputmethod of the AgentBase class. If the agent is never run from a browser, youcan use System.out as usual although the PrintWriter object also works.

Contain Domino Java classes in a try/catch block for exception handling,because many of them throw a NotesException.

The following example shows a simple Java class (JavaAgent) that runs as aDomino agent (DemoAgent). The agent retrieves the platform, the database,and the agent name and prints a message.

import lotus.domino.*;public class JavaAgent extends AgentBase {

public void NotesMain() {try {

Session session = getSession();AgentContext agentContext = session.getAgentContext();String p = session.getPlatform();Database db = agentContext.getCurrentDatabase();Agent agent = agentContext.getCurrentAgent();String name = agent.getName();System.out.println("Platform = " + p);System.out.println("Database = " + db);System.out.println("Current agent = " + name);

} catch(Exception e) {e.printStackTrace();

}}

}

Figure 19 on page 59 shows the output in the Java console after running theDemoAgent agent in foreground.

58 Using VisualAge for Java to Develop Domino Applications

Page 79: Using VisualAge for Java To Develop Domino Applications

Figure 19. Java Console Output

Domino R4.6 does not provide native Java development or debugging tools.You have to develop the Java agent in a standard Java developmentenvironment such as VisualAge for Java and import it into a Domino page orform.

In Domino R5 you can still import the classes or enter the Java code directlyin the agent and compile it (Figure 23 on page 62). You can also find in theProgrammer’s pane in the Reference tab the content of the Domino JavaLibrary and of the core Java Library.

Domino Designer provides limited Java debugging functions. You can haveyour Java agent print on the standard output. Foreground agents can use theJava Debug Console. To see the console, choose File - Tools - Java DebugConsole (Figure 19 on page 59). Output from scheduled agents are written tothe Notes log. Background agents can use the Domino server console tooutput messages.

In 4.3.1, “Domino Agent Runner” on page 99 we explain how VisualAge forJava 2.0 with Domino AgentRunner can provide a powerful tool in writing,debugging and testing Domino Java agents directly within the Java IDE.

Creating Domino Java AgentsIn Domino R4.6 you have to import the required Java files in Domino. Selectthe Java option in the What should this agent run? section of the CreateAgent window.

Using Domino Designer R5 (see Figure 20 on page 60) you can either importthe required Java files in Domino or write the Java code directly using DominoDesigner R5.

• To import the required Java files in Domino, select Imported Java in theRun pull-down list of the Create Agent window.

• To write the Java code directly using the script area of the Programmer’spane, select Java in the Run pull-down list of the Create Agent window.

Domino 59

Page 80: Using VisualAge for Java To Develop Domino Applications

Figure 20. Domino R5 Create Agent Run Options

Importing Java FilesTo import the Java packages, click Import Class Files. The Define JavaAgent Files dialog box is displayed (Figure 21 on page 61) where you enterthe location of the Java files (Base directory) and the name of the main class(Base class) that is executed when the agent is launched.

60 Using VisualAge for Java to Develop Domino Applications

Page 81: Using VisualAge for Java To Develop Domino Applications

Figure 21. Define Java Agent Files Window

Once the Java agent is imported, the screen below offers you the opportunityto re-import and reorganize an existing agent by clicking the Reimport ClassFiles button (Figure 22 on page 61).

Figure 22. Reimport the Agent Class File

Entering Java CodeDomino Designer R5 allows you to enter Java code directly in the script areaof the Programmer’s pane (Figure 23 on page 62). You can create a newagent, edit an existing one, add new classes to an agent, compile the currentclass or the entire agent, and export the class to a project directory.

Domino 61

Page 82: Using VisualAge for Java To Develop Domino Applications

Figure 23. Java Agent Programmer’s Pane

2.7.3 Java ServletsServlets are Java-written programs that run on your Web server. Theseprograms when triggered, usually through a URL, perform a task for you, forexample fetch some data from an enterprise system, and typically return witha page of HTML. Parameters can be passed to your servlet through the URL.

Servlets are server-side Java components that offer an alternative to CGI andPERL programming for building Web applications. Servlets generally performbetter and are more easily extensible than CGI programs.

Writing a ServletA servlet requires the JSDK. Domino Server R5 and Domino Designer R5provide a copy of the JDK 1.1.6 and JSDK 2.0.

To write and compile your servlet you have to use a Java IDE external toDomino such as VisualAge for Java.

To write a servlet you extend the Servlet class and override the init(),destroy(), and service() methods. Servlets offer valuable features such asthread-safe code, automatic memory management, and built-in networkingsupport.

To access the local Domino server, a servlet must extend NotesThread,implement the Runnable interface, or use the static NotesThread methodssinitThread() and stermThread(). You can then use the createSession()

62 Using VisualAge for Java to Develop Domino Applications

Page 83: Using VisualAge for Java To Develop Domino Applications

method of the Domino R5 NotesFactory class, or the newInstance() methodof the Domino R4.6 Session class to create a session to the Domino server.

To access a remote Domino server, a Domino R5 servlet creates a sessionusing the IOR. The IOR is a string that uniquely identifies a remote computerwhich is acting as an IIOP server. The getIOR() method of the NotesFactoryclass uses the name (or IP address) of the remote Domino server and returnsthe string IOR. You can create a session to the Domino server using thecreateSessionWithIOR() of the NotesFactory class.

The following example shows how you can create a servlet that accesses adatabase on a remote Domino server and lists all views with relative numberof documents. The name of the Domino server, as well as the user ID and itspassword are passed to the servlet as initialization parameters. The name ofthe database is passed to the servlet as a parameter when it is being called.

package test;import javax.servlet.* ;import javax.servlet.http.*;import lotus.domino.*;import lotus.domino.corba.* ;import java.util.* ;public class PrintInfo extends javax.servlet.http.HttpServlet {

Session s ;public void doGet(HttpServletRequest req, HttpServletResponse res) throwsjavax.servlet.ServletException, java.io.IOException {

String title = null;String dbName = null;String dbNameValue = null;Enumeration e = req.getParameterNames();if (e.hasMoreElements()) {

dbName = (String) e.nextElement();dbNameValue = (String) req.getParameter(dbName);

}try {

System.out.println("Session OK" ) ;Database db = s.getDatabase(null, dbNameValue);title = db.getTitle();Vector views = db.getViews();int size = views.size();res.setContentType("text/html");ServletOutputStream out = res.getOutputStream();out.println("<html>");out.println("<head><title>Print Info Servlet</title></head>");out.println("<body>");out.println("<h1> The title of " + dbNameValue + "is \""

Domino 63

Page 84: Using VisualAge for Java To Develop Domino Applications

+ title + "\" </h1>");out.println("<b><font size =5> List All Views in "

+ title + " </font>");out.println("<br><br>");for (int i = 0; i < size; i++) {

String name = ((View) views.elementAt(i)).getName();View v = (View) views.elementAt(i);int numdoc = 0;Document doc = v.getFirstDocument();while (doc != null) {

numdoc++;doc = v.getNextDocument(doc);

}out.println("<hr><b> View #" + (i + 1) + ": " + name

+ " contains " + numdoc + " documents");}out.println("</body></html>");

} catch (NotesException ex) {System.out.println(ex.id + " " + ex.text);ex.printStackTrace();

}}public void init(ServletConfig conf) throws ServletException {

try {super.init(conf);String ipName = getInitParameter("ipName");String user = getInitParameter("user") ;String pwd = getInitParameter("password") ;String ior = NotesFactory.getIOR(ipName);s = NotesFactory.createSessionWithIOR(ior,user, pwd) ;

} catch (NotesException ex) {System.out.println(ex.id + " " + ex.text);ex.printStackTrace();

}}

Domino R4.6 Servlet ManagerTo allow Domino R4.6 to manage servlets, perform the following steps:

1. Enable Java servlet support.

Servlets are loaded and called by the Domino Java Servlet Manager, apart of the HTTP server task. The runtime Java support for servlets isprovided by the Domino JVM. When the HTTP task is started, it loads theJVM and starts the servlet manager. In Domino R4.6, servlet support isdisabled by default. To enable servlet support, edit the server’sinitialization file (notes.ini) adding the following line:

64 Using VisualAge for Java to Develop Domino Applications

Page 85: Using VisualAge for Java To Develop Domino Applications

DominoEnableJavaServlets = 1

When Domino starts, it writes the following messages on the console:

05/02/98 11:34:36 AM HTTP Web Server started05/02/98 11:38:38 AM JVM: Java Virtual Machine initialized05/02/98 11:38:38 AM Java Servlet Manager initialized

2. Install the servlet.

Create the servlets subdirectory and copy the required class files for theservlet into this directory.

In the server’s initialization file (notes.ini), include a path to the servletsdirectory in the JavaUserClasses command.

JavaUserClasses=<other paths>;c:\lotus\notes\data\domino\servlets

3. Register the servlet.

The servlet must be registered in the Domino servlet configuration file(servlet.cnf) in the Domino data directory. When the server starts up, itchecks this configuration file to see if there are any servlets to load.

In the servlet configuration file, specify each servlet giving its name, itsinitialization parameters, the servlet class for URL mapping, andinstructions for loading the servlet at startup time.

The following lines show the servlet.cnf configuration file that registers thePrintInfo servlet.

#Servlet test.PrintInfo RegistrationServlet test.PrintInfo {ipName=9.1.150.175user=Administratorpassword=passwordGO_LOAD_STARTUP=NO}#URL to trigger the ServletService test.PrintInfo /servlet/PrintInfo

4. Call the servlet.

Use the following URL from a Web browser to call the servlet to displaythe SG245424.nsf database:

http://your.web.server/Servlets/PrintInfo?sg245424.nsf

Domino R5.0 Servlet ManagerIn Domino 5.0 the servlet manager is controlled by settings in the DominoDirectory Server document. The settings are located on the InternetProtocols - Domino Web Engine tab of the Server document (Figure 24 onpage 66).

Domino 65

Page 86: Using VisualAge for Java To Develop Domino Applications

Figure 24. Domino R5 Java Servlet Configuration

To support servlets in Domino R5, you have to:

1. Enable the servlet manager.

Select one of the following options in the Java servlet support field of theservlet configuration parameters panel:

Domino Servlet ManagerThe Domino HTTP task loads both the JVM and thenative servlet manager.

Third Party Servlet SupportThe HTTP task loads the JVM, but not the Dominoservlet manager. This allows the use of third-partyservlet managers such as IBM's WebSphereApplication Server.

In this panel, you can also specify the path in a URL that signals Dominothat the URL refers to a servlet (Servlet URL path), the list of paths whichthe servlet manager class loader searches to find servlets and theirdependent classes (Class path), the list of URL file extensions that signalDomino that a URL refers to a servlet (Servlet file extensions). Refer to theDomino Designer help file for additional information on these options.

2. Set the servlet properties.

Special properties for individual servlets can be specified in a text filecalled servlets.properties located in the Domino data directory. Thefollowing properties can be specified:

• Alias

• Initialization arguments

• URL extension mapping

• Load at servlet manager startup

The following example registers the PrintInfo servlet that requires threestartup parameters (ipName, user, and password), assigns an alias, and isloaded automatically when the servlet manager starts:

66 Using VisualAge for Java to Develop Domino Applications

Page 87: Using VisualAge for Java To Develop Domino Applications

#Servlet PrintInfo RegistrationServlet.PrintInfo.initArgs=ipName=9.1.150.175,user=Administrator,

password=passwordservlet.PrintInfo.code=test.PrintInfoservlet.startup=test.PrintInfo

3. Configure additional parameters.

You can configure any of the other servlet configuration parameters in theserver document. Refer to the Domino Designer help file for moreinformation.

4. Call the servlet

Use the following URL from a Web browser to call the servlet to displaythe SG245424.nsf database:

http://your.web.server/Servlets/PrintInfo?sg245424.nsf

2.8 Lotus Domino Toolkit for Java/CORBA

The Lotus Domino Toolkit for Java/CORBA (Domino Java Toolkit) is acomprehensive source of samples, documentation, and software that helpsyou create Java applets, applications, servlets, and agents for local andremote (CORBA) access to Domino data.

The overall goal of the Domino Java toolkit is to help you leverage the powerof Java and Domino, whether or not your user audience is primarilyNotes-based. Here are some key benefits of the toolkit:

• It includes the Domino Objects for Java libraries so you can develop localand remote Java programs. You can develop remote Java applets andapplications without necessarily having Domino or Notes installed.

• It provides sample code for Domino agents, applets, applications, andservlets you can use to create your own Java programs.

• It integrates Domino Java documentation from a variety of sources, inconvenient HTML format.

Domino Java Toolkit R1.1 supports Domino R4.6. It contains AgentRunner,the Java Programmer's Guide, and Java samples. AgentRunner providesNotes agent context to a Java IDE such as VisualAge for Java. Once thecontext is set up, you can build, run, and debug without leaving the IDE. Thecode executes as it would in the Notes agent. This tool was developed andtested on Sun JDK, VisualAge for Java, and Symantec Visual Cafe. It shouldwork with other Java IDEs but was not tested in other environments.

Domino 67

Page 88: Using VisualAge for Java To Develop Domino Applications

Domino Java Toolkit R2.0 supports Domino and Notes 5.0 with enhancedsamples, tools and documentation. It contains the following enhancements toR1.1:

• A new, easier-to-use HTML documentation.

• Java .jar files for Notes and Domino R5 to support building and deployingR5 Java programs.

• A helper class, NotesAppletContext, that provides an applet withinformation about the context in which it is running, that is, the server,database, and document that contain the applet. Using this class can helpmake programs more portable from one database to another.

• The AgentRunner debugging tool is now included with Notes and DominoR5. This toolkit still contains samples that help step you through usingAgentRunner to debug your agents. This toolkit also includes two helperclasses, AgentMain and Agent46Main.

• Sample directories and names have been reorganized to make themeasier to find.

• Many new samples.

68 Using VisualAge for Java to Develop Domino Applications

Page 89: Using VisualAge for Java To Develop Domino Applications

Chapter 3. VisualAge for Java

IBM VisualAge for Java is an award-winning Java application developmentenvironment for building Java applications, applets, servlets and JavaBeancomponents. By automatically connecting Java clients to existing server data,transactions, and applications, VisualAge for Java exploits your existingbusiness applications today and enables you to extend your business to theWeb. Don't code to low-level interfaces; connect with VisualAge for Java toreach more people, deliver more content, and drive new businessopportunities.

VisualAge for Java can be used to create, customize, extend and maintainJava elements connected to Domino. While developing these elements,developers can benefit from the VisualAge for Java visual programminginterface, enterprise access builders, version control system, incrementalcompilation and integrated debugger.

In this chapter we present VisualAge for Java Version 2.

3.1 Integrated Development Environment

VisualAge for Java is available in three different editions. All editions providevisual development through the visual composition editor, an integrateddevelopment environment, version control, and data access.

• VisualAge for Java, Entry Edition provides an edition of VisualAge suitablefor learning and building small projects of 500 classes or less. It isavailable as a no-charge download from VisualAge for Java andVisualAge Developer Domain Web sites.

• VisualAge for Java, Professional Edition is a complete Java developmentenvironment, including easy access to JDBC-enabled databases forbuilding Java applications.

• VisualAge for Java, Enterprise Edition, designed for building enterpriseJava applications, has all of the Professional Edition features plus supportfor developers working in large teams, developing high-performance orheterogeneous applications, or needing to connect Java programs toexisting enterprise systems.

In this book, we concentrate on the features of VisualAge for JavaProfessional Edition.

VisualAge for Java Professional provides an integrated developmentenvironment (IDE) which enables you to perform the following tasks:

© Copyright IBM Corp. 1999 69

Page 90: Using VisualAge for Java To Develop Domino Applications

• Build Java programs interactively.

• Run Java programs.

• Run fragments of Java code before you include them in classes.

• Debug Java programs, changing them as you run the code.

• Manage multiple editions of Java code.

• Import Java source and binary code from the file system.

• Export Java source and binary code to the file system.

• Build, modify, and use beans.

VisualAge for Java IDE includes:

• Incremental compilation

VisualAge for Java compiles source code incrementally. That is, itcompiles only those parts of the source code that you change (and othercode that is directly dependent on it) and therefore significantly reducesthe overall compilation time. Any errors are flagged and listed in theProblems page of program element browsers and the Workbench. Otherchanges, such as deleting, moving, copying, or renaming programelements, also initiate a compilation of affected program elements, to flagany new problems.

• Advanced coding tools such as formatting, automatic code completion andfix-on-save

• Repository-based environment

All of the code in the development environment is stored in a repository.This repository enables incremental compilation and provides for verypowerful search capabilities. The code that you are working with is storedin a workspace. Version management is built into the repository, andversions or editions of code are automatically stored when you changeany program element (method, class, package or project) in yourworkspace.

• Project-based development

VisualAge for Java provides projects. The basic Java environmentsprovide only the concept of a package to organize your work. In VisualAgefor Java the packages are organized into projects.

• Source code editor

A full-featured syntax editor, which helps you write error-free source code.

• An integrated debugger

70 Using VisualAge for Java to Develop Domino Applications

Page 91: Using VisualAge for Java To Develop Domino Applications

• A Visual Composition Editor, which enables you to develop yourapplications visually

• A JavaBean creation tool to create 100% pure Java beans that can beused with the Visual Composition Editor

New powerful features that come with Version 2.0 of VisualAge for JavaProfessional include:

• Java Virtual Machine and JDK Release 1.1.6

• Visual Composition Editor support for the JFC Release 1.0.2 (Swing)

• Inner class support

• National language support

• Tool integration API

• Database access beans

• Notes Domino access

• Interface to external software configuration management tools

In the following sections, some of these features are described in more detail.For more information on programming with VisualAge for Java 2.0 seeProgramming with VisualAge for Java Version 2, SG24-5264.

3.1.1 WorkspaceAll activity in VisualAge for Java is organized around a workspace, whichcontains the Java programs that you are developing.

The workspace also contains all the packages, classes, and interfaces thatare found in the standard Java class libraries, and other libraries that yourclasses may need.

You can have only one edition of any program element in the workspace atany time. To view, manipulate, create, modify, and manage program elementsthat are in the workspace you use the Workbench window (Figure 25 on page72).

VisualAge for Java 71

Page 92: Using VisualAge for Java To Develop Domino Applications

Figure 25. Workbench

You can add program elements from the repository to the workspace, replacethe edition that is in the workspace with a different edition from the repository,or delete program elements from the workspace. You can maintain differentversions of the workspace, customized for different projects or releases.

Projects and Other Program ElementsThe starting point for development work in the VisualAge for Java IDE is aproject. Projects are units of organization used to group packages. They canbe used, for example, to group packages from a certain provider, to grouppackages related to one application or customer, or to group frequently usedclasses that provide interrelated function. You can use them as best suitsyour development situation.

Packages and classes have the same meaning as in other Java developmentenvironments. They are Java constructs.

Projects contain packages, packages contain classes and interfaces, andclasses contain methods. We can refer to these constructs collectively as"program elements".

72 Using VisualAge for Java to Develop Domino Applications

Page 93: Using VisualAge for Java To Develop Domino Applications

The Workbench organizes all the program elements that are in theworkspace. From the Workbench, you can view, create, modify, and manageprogram elements. You can also open browsers and other windows that helpyou perform specialized tasks on program elements.

VisualAge for Java uses SmartGuides to help you create all the programelements and to set their attributes. In Figure 35 on page 88 you can see anexample of the SmartGuide called to create a new class.

VisualAge for Java provides some standard projects. The following projectsare loaded into the workspace by default when you first install the IDE:

• IBM Java implementation

• Java class libraries

• JFC (Java Foundation Classes) class libraries

• Sun class libraries

Others that are shipped with VisualAge for Java are stored in the repository,but not initially loaded into the workspace. You can add them as you needthem.

3.1.2 RepositoryIn the VisualAge for Java IDE, the repository is a source control mechanismthat allows you to track changes made to program elements. When you startthe IDE, it connects to a repository. As you create and modify programelements in the workspace, your changes are automatically stored in therepository. You can undo changes by retrieving previous editions from therepository.

Unlike the workspace, the repository contains all editions of all programelements. When you remove program elements from the workspace, theyremain in the repository. Over time, the repository will grow. You shouldperiodically purge program elements that are no longer required, and thencompact the repository to reduce its size.

The default repository is contained in a file called ivj.dat which resides in theIBMVJava\IDE\repository directory.

The Repository Explorer is the visual interface to the repository (Figure 26 onpage 74). You can access it by clicking on Window - Repository Explorer.With the Repository Explorer you can for example perform the following tasks:

• Browse editions of projects, packages, classes, interfaces, and methods.

VisualAge for Java 73

Page 94: Using VisualAge for Java To Develop Domino Applications

• Compare different editions of program elements.

• Add program elements to the workspace.

• Change to another repository.

Figure 26. Repository Explorer

Although the VisualAge for Java repository manages your code, it does notmanage resource files, such as images and sound clips. Resource files arestored in the file system, and you are responsible for managing them.

3.1.3 Importing and Exporting Java CodeIn VisualAge for Java you can import and export Java code in differentformats.

Importing Java CodeTo import Java code in the Workspace, click on File - Import from the menubar on any page to open the SmartGuide Import window (see Figure 27 onpage 75).

74 Using VisualAge for Java to Develop Domino Applications

Page 95: Using VisualAge for Java To Develop Domino Applications

Figure 27. File - Import SmartGuide

You can choose between three different sources of import: Directory, Jar file,or Repository.

For Directory or Jar file imports, click on Next to display the SmartGuideImport from a directory or Import from a jar/zip file window (see Figure 28 onpage 76). Specify the type of files to import (.class, .java, resources), theproject name in which to import the classes, and whether or not to overwriteexisting resources.

VisualAge for Java 75

Page 96: Using VisualAge for Java To Develop Domino Applications

Figure 28. Import from a directory - SmartGuide

For Repository imports, click on Next to display the SmartGuide Import fromanother repository window (see Figure 29 on page 76). Specify the name ofthe repository from which to import and the specific packages or projects tobe imported.

Figure 29. Import from another repository - SmartGuide

76 Using VisualAge for Java to Develop Domino Applications

Page 97: Using VisualAge for Java To Develop Domino Applications

Exporting JavaCodeTo export Java code optionally you can select one or more projects,packages, classes or interfaces.

• Upon selecting the package, all classes and interfaces in the package areexported.

• Upon selecting the project, all classes within the project are exported.

To select the export option you can click on File - Export from the menu baron any page to open a SmartGuide which is the same as that shown in Figure27 on page 75.

You can choose between three export destinations: Directory, Jar file orRepository.

For Directory exports, click on Next to display the SmartGuide Export to adirectory window (see Figure 30) and specify the type of files to export(.class, .java, resources) and several options on export modality.

Figure 30. Export to a directory - SmartGuide

VisualAge for Java 77

Page 98: Using VisualAge for Java To Develop Domino Applications

For Jar exports, specify the type of files to export (.class, .java, resources,beans) and several options on export modality.

For Repository exports, click on Next to display the SmartGuide Export toanother repository window (see Figure 31). Specify the name of therepository to export, and specific packages or projects to be exported.

Figure 31. Export to another repository - SmartGuide

3.1.4 ScrapbookThe Scrapbook is a window that helps you organize, develop, and test ideasfor your Java programs. In the Scrapbook, you can experiment with Javacode fragments without specifying a containing class. The Scrapbook canhave several pages. To open the Scrapbook page selectWindow-Scrapbook. In Scrapbook you have to define the compilationcontext which is the class you choose to contain the Java code fragmentwhen you compile and run it. When you evaluate code in the Scrapbook, it istreated as though it were part of the compilation context, so the code inheritsany imports from the selected class. It can also refer to protected or privatefields and methods in the class and nonpublic classes in the same package.

78 Using VisualAge for Java to Develop Domino Applications

Page 99: Using VisualAge for Java To Develop Domino Applications

Each Scrapbook page has its own compilation context, and does not interferewith other pages, so you can do things such as test the client and serverparts of a program. The default compilation context is java.lang.Object.

The Scrapbook can open, read, and save to text-based files, including .javafiles, from the file system. It supports a variety of formats and origins,including NT, OS/2, UNIX-based, Solaris, and Macintosh. You can run Javacode that is in any of these types of files.

You can import Java code from these files into a class, interface, or method inthe workspace.

3.1.5 DebuggerYou use the debugger to step through and fix the Java code. With theInspector utility you can also inspect and change the state of the objects. Thechanges made in the debugger are reflected in the workspace. The debuggerpage (Figure 32 on page 80) consists of two panes:

• Debug

The debug pane shows all currently running threads, the variables, valuesand source relating to a selected suspended thread.

• Breakpoint

This page shows all the methods in the workspace that have breakpointsset in them and the source code for the method. You can add, remove, ordisable breakpoints, and insert conditional breakpoints.

VisualAge for Java 79

Page 100: Using VisualAge for Java To Develop Domino Applications

Figure 32. Debugger Window

VisualAge for Java also provides Automatic Code Completion or Code Assistto help you locate the correct type, method, or field while you are coding. Toinvoke it hold down the Control key and press the spacebar (Figure 33 onpage 80).

Figure 33. Automatic Code Completion

80 Using VisualAge for Java to Develop Domino Applications

Page 101: Using VisualAge for Java To Develop Domino Applications

3.2 Visual Composition Editor

VisualAge for Java includes a state-of-the-art object-oriented visualcomposition editor for assembling program elements visually from JavaBeanscomponents (see 1.4, “Java Beans” on page 14).

Using an object-oriented approach for complex systems provides thefollowing benefits:

• Individual classes are much easier to create and understand.

• Systems are much easier to maintain and enhance. Objectimplementations can be modified individually without modifying the rest ofthe system, as long as the objects continue to respond appropriately tomessages sent to them by other objects.

Despite these benefits, implementing large systems can still be expensive.One way to reduce the cost is to reuse object implementations. Manycompanies would prefer to buy reliable reusable classes, creating classesonly for functions specific to their business.

However, reuse is hard to achieve when the class interfaces are too specificto the application for which they were originally developed. To promote widerreuse, class interface conventions called component models have beendefined, such as ActiveX, OpenDoc, and JavaBeans.

As we have already mentioned, JavaBeans is the standard component modelfor the Java language and is the component model used by VisualAge.

The Visual Composition Editor enables you to create programs graphicallyfrom existing beans. VisualAge provides user interface beans based on Javaclasses in the Abstract Windowing Toolkit (AWT) and Swing packages. TheVisual Composition Editor is also extensible. It allows you to work with beansyou create yourself, and it allows you to include beans imported into theenvironment from other sources. You can even create your own beansgraphically using the Visual Composition Editor and then reuse these beansagain within another program being created with the Visual CompositionEditor.

To build a program with the Visual Composition Editor, you draw a pictureusing a canvas and palette of icons representing reusable beans. This picturespecifies the set of beans that implements the function of the larger program(or bean) you are creating. For beans like user interface controls, the positionof the controls relative to each other in the picture specifies how the controls

VisualAge for Java 81

Page 102: Using VisualAge for Java To Develop Domino Applications

will appear in the final program. For beans such as database components,the position of the bean in the picture generally has no significance.

Figure 34. VisualAge for Java Visual Composition

The Visual Composition Editor provides a very sophisticated connectioncapability to specify how components of the picture will interact to implementfunctions of the program. Using connections, much of the behavior of anapplication can be specified graphically. Connections also allow you tointegrate custom code written in the Java language.

Beans can be classified as:

• Visual

Visual beans are elements of the program that the user can see atruntime. The development-time representations of visual beans in theVisual Composition Editor closely match their runtime visual forms. Userscan edit these beans in the Visual Composition Editor in their visualruntime forms. Examples include windows, entry fields, and push buttons.In general, visual beans are subclasses of java.awt.Component.

• Nonvisual

Nonvisual beans are elements of the program that are not necessarilyseen by the user at runtime. On the Visual Composition Editor's free-formsurface, users can manipulate these beans only as icons. Examples

82 Using VisualAge for Java to Develop Domino Applications

Page 103: Using VisualAge for Java To Develop Domino Applications

include business logic, database queries, and communication accessprotocol beans. Beans that have a visual representation at runtime but donot support visual editing are treated as nonvisual. Examples of this kindof nonvisual bean include message boxes and file selection dialogs.

Composite beans can contain both visual and nonvisual components. Ingeneral, composite beans are based on one of these classes, but you are byno means limited to these:

• Applet or JApplet, for Web applets

• Frame or JFrame, for GUI (Graphical User Interface) applications

• Panel or JPanel, for reusable GUI surfaces embedded in either applets orapplications

• VisualServlet, for servlets

ConnectionsWhen you make a connection in the Visual Composition Editor, you define theinteraction between components. For example, if you want a data value tochange when an event occurs, you would make an event-to-propertyconnection.

A connection is directional; it has a source and a target. The direction inwhich you draw the connection determines the source and target. The beanon which the connection begins is the source; the bean on which it ends is thetarget.

VisualAge for Java has the following connections:

• Property-to-Property connections, that link two property values together.This causes the value of one property to change when the value of theother changes.

• Event-to-Property connections, that update the target property wheneverthe source event occurs.

• Event-to-Method connections, that call the specified method of the targetobject whenever the source event occurs. You can provide parametersthrough a parameter connection, by passing event data (an option in theconnection window), or through a return value.

• Code connection, that calls code of the primary bean whenever the sourceevent occurs. You can use a code connection for the bean you aredeveloping to connect to private, public, protected methods of the beanyou are editing, and public methods of any of its embedded beans.

VisualAge for Java 83

Page 104: Using VisualAge for Java To Develop Domino Applications

• Parameter connection, to supply an input value to the target of aconnection by passing either the value from a property or the return valuefrom a method.

Generated CodeWith the Visual Composition Editor, you lay out beans graphically and specifytheir interaction using a high-level connection model. When you save yourcomposition, VisualAge generates Java code that maps this graphicalrepresentation to the JavaBeans component model and to the APIs for thebeans themselves.

When you compose your bean visually, VisualAge generates much of theuser interface code for you. The connections you make between beans areoften sufficient to define behavior at runtime. If not, you can extend it byadding your own code.

In addition to other items generated for all classes, VisualAge generates thefollowing code for a composite bean:

• A field declaration for each embedded bean

• A private get method for each embedded bean

• For each promoted feature, a public get and set method

• A private method for each method or code connection

• An initConnections() method, which contains a call to every notifierrequired for event connections in the composite bean

• For applets, an init() method

• For nonapplets, an initialize() method

• A constructor with no arguments, which by default calls the superclassconstructor and the initialize() method

84 Using VisualAge for Java to Develop Domino Applications

Page 105: Using VisualAge for Java To Develop Domino Applications

Chapter 4. Visualage for Java and Domino

VisualAge for Java is an IBM Java application development environment forbuilding Java applications, applets, and servlets. VisualAge for Java can alsobe used to build Java-based business productivity applications using theLotus eSuite components and to develop, debug and test Lotus NotesAgents. In the following, we explain how to develop Java programs thataccess Domino objects using VisualAge for Java.

4.1 Java Support for Domino - VisualAge for Java Makes It Easy

VisualAge for Java supports Domino applications in many ways:

Creating Applets for Inclusion in DocumentsJava applets can be added to Notes documents. For example, developerscan easily enhance documents with Java applets that calculate mortgage orexchange rates, access a relational database, or create multimediaanimation. These applets can be developed from scratch or obtained from themany ISVs that produce Java beans and applets.

VisualAge for Java can be used to create, customize, extend and maintainJava applets for use in Domino. In addition, the VisualAge for Javaenvironment enables developers to import and customize Java applets andJava beans purchased from independent software vendors. These appletsand beans can then be exported to a Notes document. While developingapplets, developers will benefit from the VisualAge for Java visualprogramming interface, enterprise access builders, version control system,incremental compilation and integrated debugger.

Creating Java AgentsDomino agents can be created in Java. For instance, an agent could retrievedata from a DB2 database and use it to update the documents in a Dominodatabase. Creating that agent in Java allows the developer to reap thebenefits of using an object-oriented language, the ability to utilize themultithreading capabilities of Java and consistently program in a commonlanguage across different enterprise servers.

Agents can be created in VisualAge for Java and exported to Domino via thefile system. However, a Domino agent can only run in the context of a Dominodatabase. Domino AgentRunner creates the context of a Domino databasewithin the VisualAge for Java integrated development environment. Thisallows developers to take full advantage of the integrated debug facilities

Visualage for Java and Domino 85

Page 106: Using VisualAge for Java To Develop Domino Applications

when building Domino Java agents. In addition, wizards allow the agent to bedeployed to the Domino database directly, not via the file system.

Creating Web ClientsMany companies base their enterprise computing strategy on Domino.Therefore they require customized user interfaces and thin clients. Javaallows for the development of applications that use a thin client or customizedinterface to access Domino for the enterprise functionality.

For instance, a company might want to extend its supply managementsystem to its suppliers without requiring each supplier to use a Notes client.They could develop Java applets that enable suppliers to use an ordinaryWeb browser to access the supply management system via the Dominoserver. In addition, they could use Java applets, applications and servlets tocreate an entire set of Web-based interfaces for the supply managementsystem.

Technically speaking, the Java applets, servlets or applications can becreated in VisualAge for Java. The new user interface can be created usingVisualAge for Java's visual builder tools. VisualAge for Java automaticallygenerates RMI connectivity code, which makes it easy to distribute thefunctionality between the Domino server and the thin client.

Moving Forward - Enhancing the SupportWith VisualAge for Java Version 3, additional support will be added toVisualAge for Java to make it easier to build and maintain Dominoapplications written in Java. The initial enhancements will focus on providingsupport for the Domino Java Development Kit via support for writing Javaagents and samples and documentation illustrating how to use VisualAge forJava to build Domino applications. Future enhancements will focus onmaking it easier to create Web clients that connect to existing Dominodatabases. (See Part 3, “What’s Next?” on page 239 for a preview of the newDomino Access Builder of VisualAge for Java Version 3.)

4.2 Applet

In this section we explain how to create, debug, test, and install an applet thatconnects to Domino using CORBA. VisualAge for Java is the developmentenvironment.

The DominoApplet applet:

• Initializes the connections to Domino (connectCORBA).

86 Using VisualAge for Java to Develop Domino Applications

Page 107: Using VisualAge for Java To Develop Domino Applications

• Creates a list of employee names (empList) in a list box(EmployeeListBox).

• When the user selects one employee’s name and clicks on the Searchbutton (SearchButton), the applet gets additional information (employeefirst name) and fills the corresponding text fields(EmployeeFristNameTextField).

The example shows the techniques used to create a simple applet with agraphical interface made of labels, text fields and lists in VisualAge for Java.

The general steps for creating a Domino applet that uses CORBA withinVisualAge for Java are the following:

1. Set up the environment for developing, debugging and testing the applet.

2. Initialize the development environment.

3. Create the support methods of the applet such as connectCORBA,getEmployeeList, getEmployeeFirstName.

4. Compose the visual part—the graphical user interface—of the applet.

5. Debug and test the applet within VisualAge for Java.

6. Install the applet in Domino.

4.2.1 SetupBefore being able to develop a Domino application in VisualAge for Java, youhave to import the required packages into the workspace. We imported thefollowing environments into the VisualAge workspace:

• Domino R5 Java library (lotus.domino package in the Notes.jar file)

• Domino R5 CORBA library (lotus.domino.CORBA package in theNSCO.jar file)

For detailed information on how to import a package within VisualAge forJava see 3.1.3, “Importing and Exporting Java Code” on page 74.

Even if on your development machine Domino or Notes is not installed, tocompile and run remote Domino applications using VisualAge for Java youneed to import the Domino Java libraries.

However, to implement a CORBA applet within a Domino page or document,you need to use Domino Designer R5.

Visualage for Java and Domino 87

Page 108: Using VisualAge for Java To Develop Domino Applications

4.2.2 Development Environment InitializationLaunch VisualAge for Java. You have to create a project called VAJ Domino.In this project, create a package called dominoappletpackage. You are nowready to create the applet.

DominoApplet ClassIn the dominoappletpackage package create the DominoApplet class. Thisclass extends lotus.domino.AppletBase and can be built visually (see Figure35 on page 88).

Figure 35. Create Class

When you click on Finish, VisualAge for Java displays the VisualComposition Editor.

88 Using VisualAge for Java to Develop Domino Applications

Page 109: Using VisualAge for Java To Develop Domino Applications

Click on the Methods tab to allow the creation of the support methods.

4.2.3 Support Methods CreationYou have to create the following methods to support the applet:

• connectCORBA: a method that connects to Domino using CORBA.

• fillEmployeeList: a method that uses CORBA to access a database, readall the documents and fill a list passed as a parameter.

• getEmployeeFirstName: a method that requires an employee name asinput, uses CORBA to access the database and reads the documentcorresponding to the employee and returns the employee’s first name.

You have to define the import packages and some class variables that areused in the applet. VisualAge appends its own variables at the end of yourdefinition.

import java.applet.*;import java.awt.*;import lotus.domino.*;public class DominoApplet extends AppletBase implementsjava.awt.event.ActionListener {

Session s;Database db;DocumentCollection dcol;String dbname = "SG245425\\SG245425T";String server = "127.0.0.1";String viewname = "Employee\\Last Name";String user = "Administrator";String pwd = "password";

connectCORBA() MethodThe Session class is the root of the Domino back-end object containmenthierarchy. To create a session to a Domino server within an applet, use thefollowing methods:

AppletBase.openSession()orAppletBase.openSession(String user, String pwd) andAppletBase.closeSession(Session session).

The user and password parameters of AppletBase.openSession(String user,String pwd) must be a user name and Internet password in the Dominodirectory on the server being accessed. If a name and password are notspecified, anonymous access must be permitted by the server.

public void connectCORBA() throws lotus.domino.NotesException {

Visualage for Java and Domino 89

Page 110: Using VisualAge for Java To Develop Domino Applications

try {s = this.openSession("Administrator", "password");if (s == null) { // not able to make a connection

System.out.println("Unable to create a session to Domino");return;

}System.out.println("Session established to server "

+ s.getServerName());} catch (NotesException e) {

System.out.println("Error in connecting to the Domino server");e.printStackTrace();

}}

fillEmployeeList() MethodThis method receives a list as parameter and fills it with the employee namesand IDs.

Once the applet has established the connection to the Domino database, wecan use various methods to access the database, create a collection ofdocuments, access the documents in a sorted order using a view, and finallyaccess a specified document and its items.

The getDatabase() method of the Session class accesses a specifieddatabase. You provide the name of the server, or null for local, and the nameof the database. The getView() method of the Database class accesses aspecified view. The get---Document() methods of the View class allow you toaccess a specific document in the view (replace --- with First, Last, Next,Nth). The getItemValue---() methods of the Document class allow you toaccess a specific field of the document (replace --- with Integer, String,Double).

public void fillEmployeeList( List empList) throwslotus.domino.NotesException {

try {// Access Databasedb = s.getDatabase(s.getServerName(), dbname);//List All Documentsdcol = db.getAllDocuments();System.out.println("Database \"" + dbname + "\" has "

+ dcol.getCount() + " documents");//Get the Document through a viewView view = db.getView(viewname);Document doc = view.getFirstDocument();// Document doc;String[] val = new String[dcol.getCount()];

90 Using VisualAge for Java to Develop Domino Applications

Page 111: Using VisualAge for Java To Develop Domino Applications

//String[] val;for (int i = 1; i <= dcol.getCount(); i++) {

val[i] = doc.getItemValueString("EMPNO") + ":"+ doc.getItemValueString("LASTNAME");

empList.add(val[i]);doc = view.getNextDocument(doc);

}

} catch (NotesException e) {System.out.println("Error in filling the list box");e.printStackTrace();

}}

getEmployeeFirstName() MethodAs the employee list contains the names and the IDs of the employees, themethod uses the substring method to get the ID only. It searches the view onthe employee ID. It then accesses the document using thegetFirstDocument() method and returns the first name to the caller.

public String getEmployeeFirstName(String name) throws NotesException {String fname = null;String Lname = name.substring( name.indexOf(":") + 1);String Id = name.substring( 0, name.indexOf(":"));try {

View view = db.getView(viewname);db.updateFTIndex(true);int count = view.FTSearch(Id);// View is filteredif (count == 0)

System.out.println("No document found for key: " + Id);else {

System.out.println(count + " document(s) for key:" + Id);Document doc = view.getFirstDocument();fname = doc.getItemValueString("FIRSTNME");

}} catch (NotesException e) {

System.out.println("Error in accessing the employee first name");e.printStackTrace();

}return fname;

}

4.2.4 Visual CompositionYou are ready now to build the visual part of the applet. Select the VisualComposition tab.

Visualage for Java and Domino 91

Page 112: Using VisualAge for Java To Develop Domino Applications

LayoutFirst you have to create the layout of the applet.

• On the free-form surface, the dotted square is a visual representation ofthe DominoApplet bean. Select it and display its properties using the rightbutton of your mouse. Set the foreground attribute to <null>.

• Check that the tool category displays the AWT category as you arecreating a simple applet with no fancy objects.

• From the bean palette, select a List bean and drop it into theDominoApplet bean. Set the beanName to EmployeeListBox.

Select a TextField bean, drop it into the DominoApplet bean. Set thebeanName to EmployeeFirstNameTextField.

Select a Button bean, drop it into the DominoApplet bean. Set thebeanName to SearchButton and its label to Search.

Figure 36 on page 93 shows the Visual Composition editor of theDominoApplet class.

92 Using VisualAge for Java to Develop Domino Applications

Page 113: Using VisualAge for Java To Develop Domino Applications

Figure 36. Visual Composition Editor

ConnectionsYou can now connect visually the different beans, so that when the userselects an employee in the list box and clicks on the Search button, an eventis sent to the applet which invokes the setText method of theEmployeeIDTextField bean.

• Select the SearchButton bean and click on the right button of the mouseto display the context menu. Select the Event to Code.... option.

The Event-to-Code Connection from SearchButton window is displayed. Inthe SearchButton event drop-down, select the actionPerformed option. Inthe method drop-down, select the getEmployeeFirstName method thatyou have created in the previous step (see Figure 37 on page 94).

Toolbar

Class Browser Tabs

Free-form Surface Visual Representation of the Bean

Tool Category

Bean Palette

Visualage for Java and Domino 93

Page 114: Using VisualAge for Java To Develop Domino Applications

Figure 37. Event-to-Code Connection from SearchButton

• On the free-form surface, the Search button is connected to thegetEmployeeFirstName method with a dotted line, meaning that theconnection is not completely defined. You need to specify the input andoutput for this connection.

To set the input parameter, select the EmployeeListBox list box and clickon the right button of the mouse to display the Context menu. Select theConnect - selectedItem option. You can now visually pass this selecteditem to the connection. In the context menu that appears, you can selectthe name variable.

To set the output parameter, select the connection and click on the rightbutton of the mouse to display the context menu. Select the Connect -normalResult option. You can now visually pass the return value to thetext field. Select the text field. In the context menu that appears, you canselect the text property.

Figure 38 on page 95 shows the connections of the different beans.

94 Using VisualAge for Java to Develop Domino Applications

Page 115: Using VisualAge for Java To Develop Domino Applications

Figure 38. Bean Connections

Applet GenerationFinally, you can save the bean using the Bean - Save Bean menu option.

When VisualAge for Java saves the bean, it generates all the methodsrequested to run the applet.

If you select the Methods tab, you will see a list of all the methods includingthe one that you have created and the ones that have been generated byVisualAge. As you have created an applet, VisualAge has generated an initmethod. However, this applet extends the AppletBase class and thereforecannot override the init method; it has been declared as final in theAppletBase class. You have to replace the generated init method with anotesAppletinit method. In this method you can add your own code such asthe connection to Domino (connectCORBA) and filling of the list box(fillEmployeeList).

When you modify the applet GUI, VisualAge for Java re-generates all therequested methods including the init method.

Don’t forget to rename the init method to notesAppletInit and to add yourown modification such as the connection to Domino,

You also have to rename the super.init call to super.notesAppletInit.

Remember

Visualage for Java and Domino 95

Page 116: Using VisualAge for Java To Develop Domino Applications

4.2.5 Debug and TestAs explained in “Implementing CORBA enabled applets within Domino” onpage 60, an applet needs the NOI_IOR parameter, which is the objectreference to the Notes object server.

To enable the applet to be tested and debugged within VisualAge for Javathis parameter has to be provided to the applet. Select the DominoAppletclass, click on the right button of the mouse, select Properties and enter theNOI_IOR parameter and its value (see Figure 39 on page 96).

The value of this parameter is stored in the diiop_ior.txt file and it isgenerated the first time the DIIOP task runs on the Domino server. The valuedoes not change unless the file is deleted. In this case, the value isregenerated again when the DIIOP task is restarted. You can copy the valuefrom the diiop_ior.txt file.

Figure 39. Applet Properties

After this setup you can test the applet using VisualAge for Java, its appletviewer and its debugger.

96 Using VisualAge for Java to Develop Domino Applications

Page 117: Using VisualAge for Java To Develop Domino Applications

Figure 40 on page 97 shows the debugging environment:

• The DominoApplet applet in the Applet Viewer

• The console

• The debugger

Figure 40. Applet Debug Session

4.2.6 Installing the Applet in DominoOnce the correct behavior of the applet is tested within VisualAge for Java,you are ready to implement it into a Domino environment. You have to:

1. Export the DominoApplet class file into a directory from VisualAge for Java(see Figure 41 on page 98).

Visualage for Java and Domino 97

Page 118: Using VisualAge for Java To Develop Domino Applications

Figure 41. Export to a Directory SmartGuide

2. Install the DominoApplet applet into a Domino document, page or form byimporting the class file or linking the applet (refer to “Installing Applets InDomino” on page 52 for more information).

4.3 Agents

In this section we explain how to create, debug, test, and implement aDomino agent using VisualAge for Java.

The DominoAgent agent is an example of a single-threaded agent that runson all new and modified documents since the last run of a database. It usesthe Newsletter class to format a document containing doclinks to each of thenew or modified documents, and mails it to the agent’s author—the personwho signed it.

98 Using VisualAge for Java to Develop Domino Applications

Page 119: Using VisualAge for Java To Develop Domino Applications

The example shows the techniques used to create a simple agent inVisualAge for Java.

The general steps for creating a Domino agent within VisualAge for Java arethe following:

1. Set up the Domino AgentRunner.

2. Create the DominoAgent class.

3. Generate an AgentContext document in Domino.

4. Debug and test the agent within VisualAge for Java.

5. Deploy the agent in Domino.

4.3.1 Domino Agent RunnerIncluded in Notes and Domino R5 as well as in VisualAge for Java V2, theAgentRunner enables you to build and debug Domino agents withinVisualAge for Java while still accessing Domino. The powerful developmentand debugging features of VisualAge for Java can then be used to tune andperfect your agent before you export the production code to the Dominoenvironment. Using the Domino Java class libraries, also included withVisualAge for Java, you can develop agents and then use the AgentRunner toprovide a Domino environment while debugging.

Domino R4.6Follow these steps to set up the Domino R4.6 environment for agentdevelopment:

• Add the IVJAgentRunner.jar file to the JavaUserClasses statement of theDomino initialization file (notes.ini).

JavaUserClasses=<other path>;c:\VAJava\ide\runtime\IVJAgentRunner.jar

Because you have edited the notes.ini file you must shut down and restartDomino so that your changes take effect.

• Add the Notes directory (c:\notes) to your PATH environment variable.

• Copy the AgentRunner database (AgentRunner.nsf) from the VisualAgefor Java directory (c:\VAJava\ide\runtime) to the database directory of theNotes client (c:\notes\data). The AgentRunner database holds theAgentContext document that the AgentRunner uses.

In VisualAge for Java, use the Quick Start - Add Feature function to add theDomino Java Class Library 4.6.1 project from the repository to the workspace(Figure 42 on page 100). This project contains the lotus.notes package with

Visualage for Java and Domino 99

Page 120: Using VisualAge for Java To Develop Domino Applications

all the Java Classes for Notes Object Interface/Domino 4.6 and additionaldebug classes that support the AgentRunner tool.

Figure 42. Quick Start - Add Features Dialog Box

Domino R5In Domino R5 you no longer need to change the Domino initialization file or tocopy the AgentRunner.nsf file from the VisualAge for Java environment to theDomino environment, as the file is provided during the installation of theNotes client.

Instead you need to import the new Notes.jar file provided with Domino 5.0 tothe workspace of VisualAge for Java. This file contains the high-levellotus.domino package, the lotus.domino.local package for local calls, and theold lotus.notes package.

Install the fix to apply to VisualAge for Java V2 in order to enable theintegrated Domino AgentRunner to work with Domino R5. This fix can befound in the Lotus Domino Toolkit for Java R2.0. You can download the toolkitfrom the Lotus developer central Web site:http://www.lotus.com/developers/lotusdominotj.

In R5 you can install the Notes client and the Domino server in differentdirectories on a single machine.

The AgentRunner.nsf database has to be in the Domino Designer databasedirectory (c:\notes).

Designer or Server

100 Using VisualAge for Java to Develop Domino Applications

Page 121: Using VisualAge for Java To Develop Domino Applications

To set up the VisualAge for Java Version 2 environment, use the Import - Jarfile to add the Domino Java class library R5 project (Notes.jar in the Dominodirectory) to the repository and then add this project to the workspace (Figure42 on page 100).

Figure 43. Adding the Domino R5 Java Class Library

4.3.2 Domino Agent Class CreationLaunch VisualAge for Java. You have to create a project called VAJ Domino.In this project, create a package called dominoagentpackage. You are nowready to create the agent.

DominoAgent ClassIn the dominoagentpackage package create the DominoAgent class. Thisclass extends lotus.domino.DebugAgentBase. Import the lotus.dominopackage (see Figure 35 on page 88). As this class is a Domino agent, do notselect the Compose the class visually option.

Visualage for Java and Domino 101

Page 122: Using VisualAge for Java To Develop Domino Applications

Figure 44. DominoAgent Class Creation

Click on Next to define the attributes of the DominoAgent class. Import thelotus.domino package and select the public modifier.

VisualAge for Java automatically generates the DominoAgent class and itsconstructor.

import lotus.domino.* ;// * This type was created in VisualAge.public class DominoAgent extends lotus.domino.DebugAgentBase {

// * DominoAgent constructor comment.public DominoAgent() {

super();}

102 Using VisualAge for Java to Develop Domino Applications

Page 123: Using VisualAge for Java To Develop Domino Applications

NotesMain() MethodYou can enter the code using the NotesMain() method, the entry point of aDomino agent. The agent creates a session to the Domino server(getSession() method), gets the agent context (getAgentContext() method),selects all new and unprocessed documents (getUnprocessedDocuments()method), creates a newsletter (createNewsletter() method) containing thedoclinks of the selected documents (formatMsgWithDocslinks() method), andsends it to the to the agent’s author (getEffectiveUserName() method).

public void NotesMain() {

try {Session session = getSession();AgentContext agentContext = session.getAgentContext();Database db = agentContext.getCurrentDatabase() ;DocumentCollection dc = agentContext.getUnprocessedDocuments();System.out.println("DominoAgent : There are " + dc.getCount()

+ " unprocessed documents" ) ;Newsletter news = session.createNewsletter(dc) ;news.setSubjectItemName("LASTNAME") ;Document doc = news.formatMsgWithDoclinks(db) ;doc.appendItemValue("Subject", "The Employee Report");doc.send(agentContext.getEffectiveUserName()) ;System.out.println(" Newsletter sent to "

+ agentContext.getEffectiveUserName()) ;} catch(Exception e) {

e.printStackTrace();}

}}

Save this method to compile it.

Visualage for Java and Domino 103

Page 124: Using VisualAge for Java To Develop Domino Applications

4.3.3 AgentContext DocumentTo generate the AgentContext document in Domino you have to:

• Export the agent's .class file from the IDE to the file system (Figure 45 onpage 104).

Figure 45. Exporting the DominoAgent Class

• Create a Domino agent (DominoTestAgent) in the database containing thedocuments to be monitored (Figure 46 on page 104). Set the Whichdocument(s) should it act on? option to All new and modified documentssince last run.

Figure 46. DominoTestAgent Creation

104 Using VisualAge for Java to Develop Domino Applications

Page 125: Using VisualAge for Java To Develop Domino Applications

• Import the DominoAgent Java class file (Figure 47 on page 105).

Figure 47. Importing the DominoAgent Class within DominoTestAgent

• Save the DominoTestAgent

4.3.4 Debug and TestYou are ready to run your agent and debug it. When you run the agent whoseclass extends DebugAgentBase from the Domino environment, anAgentContext document is automatically generated in the AgentRunner.nsfdatabase. It does not actually run the agent—the getSession() methodreturns null—but the AgentContext document is needed to run the agentwithin VisualAge for Java. Figure 48 on page 105 shows the Java Consoleafter running the agent.

Figure 48. Domino Java Console

Visualage for Java and Domino 105

Page 126: Using VisualAge for Java To Develop Domino Applications

When you run an agent whose class extends DebugAgentBase, it creates anAgentContext document in the Java Agent Runner database (see Figure 49on page 106).

Figure 49. AgentContext Document

In VisualAge for Java you can now test and debug your agent. You can setbreakpoints somewhere within the code and then run the agent selectingSelected-Tools-AgentRunner (Figure 50 on page 106).

Figure 50. Running TaskAgent with Domino Agent Runner

In this case the AgentContext used to run the agent is either the lastAgentContext that you ran or the last one you saved. The agent stops at the

106 Using VisualAge for Java to Develop Domino Applications

Page 127: Using VisualAge for Java To Develop Domino Applications

breakpoint and you can inspect and debug the code even though it isaccessing the Domino environment (Figure 51 on page 107).

Figure 51. Debugging the Agent

When changing the class code you have to repeat the following steps:

• Export the class from VisualAge for Java.

• Import the class into the agent within the Domino environment.

• Run the agent from within Domino to regenerate the AgentContextdocument.

You can also run the agent or change the properties of the AgentContextdocument from within VisualAge for Java using Selected-Tools-AgentRunner-Properties (Figure 52 on page 108 and Figure 53 on page 108).

Visualage for Java and Domino 107

Page 128: Using VisualAge for Java To Develop Domino Applications

Figure 52. Domino Agent Runner Properties Dialog Box

Figure 53. Domino Agent Runner - Update AgentContext Dialog Box

4.3.5 Deploying the AgentTo deploy the agent to Domino you have to change thelotus.domino.DebugAgentBase superclass to lotus.domino.AgentBase andreimport the agent’s class file within the Domino agent.

In Figure 54 on page 109 you can see the message sent by theDominoTestAgent agent.

108 Using VisualAge for Java to Develop Domino Applications

Page 129: Using VisualAge for Java To Develop Domino Applications

Figure 54. Mail Sent by the DominoTestAgent Agent

4.4 Servlet

In this section we explain how to create, debug, test, and install a DominoCORBA servlet using VisualAge for Java. We use the same example that wedescribed in 2.7.3, “Java Servlets” on page 62.

The simple servlet PrintInfo prints the title and the list of all views with therelative number of documents contained in a database whose filename isprovided as a parameter.

The general steps for creating a Domino CORBA servlet within VisualAge forJava are the following:

1. Set up the environment.

2. Write the servlet code to be Domino CORBA enabled.

3. Debug and test the servlet within VisualAge for Java.

4. Implement the servlet within Domino.

Visualage for Java and Domino 109

Page 130: Using VisualAge for Java To Develop Domino Applications

4.4.1 SetupAs a servlet requires the JSDK— the JSDK contains javax.servlet,javax.servlet.http, sun.servlet, and sun.servlet.http classes—you need to:

• Import the jsdk.jar file in VisualAge for Java.

• Add a new project to the VisualAge for Java workspace that refers to theJSDK jar file.

If your servlet implements the Domino CORBA classes, you also need toimport the NSCO.jar file which contains the high-level lotus.domino packageand the lotus.domino.corba package for remote calls.

For detailed information on how to import a package within VisualAge forJava, see “Importing Java Code” on page 74.

4.4.2 Writing the ServletLaunch VisualAge for Java. In a new project or an existing project, create apackage called dominoservletpackage. You are now ready to create theservlet.

PrintInfo ClassIn the dominoservletpackage package, create the PrintInfo class. This classextends the javax.servlet.http.HttpServlet. Select the PrintInfo class andcreate the doGet() method (see Figure 55 on page 110).

Figure 55. Create doGet Method SmartGuide

The method is public and may throw the ServletException and IOExceptionexceptions (see Figure 56 on page 111):

110 Using VisualAge for Java to Develop Domino Applications

Page 131: Using VisualAge for Java To Develop Domino Applications

Figure 56. Attribute doGet Method SmartGuide

Create also the init() method to initialize the servlet. For a complete listing ofthe code, refer to “Writing a Servlet” on page 62.

4.4.3 Debug and TestTo test the servlet you use the Servlet Runner that is included in the JSDK.the Servlet Runner is a stand-alone server (called servletrunner) that can beused to test servlets within VisualAge for Java before running them in aservlet-enabled Web server. You need to have TCP/IP installed and runningon your machine, and you must be able to successfully run the ping localhostcommand. You must run the Servlet Runner on an unused TCP/IP port (8080by default).

You need to set the class path of the Servlet Runner to the Domino libraries.Select the sun.servlet.http.HttpServer class and Selected - Properties (seeFigure 57 on page 112). Click the Program tab and enter -v in the Commandline arguments field. Click on the Class Path tab and add your project andthe Domino libraries.

Visualage for Java and Domino 111

Page 132: Using VisualAge for Java To Develop Domino Applications

Figure 57. Classpath Settings

To test and debug the PrintInfo servlet, you have to start the HttpServer withinVisualAge for Java. Select the sun.servlet.http.HttpServer class and click theRun button. The console will show the running server (see Figure 58 on page113).

112 Using VisualAge for Java to Develop Domino Applications

Page 133: Using VisualAge for Java To Develop Domino Applications

Figure 58. Servlet Runner Console Messages

Once the Servlet Runner is started, you can calls the servlet from a Webbrowser using the following URL:

your.server.name:8080/servlet/dominoservletpackage.PrintInfo?=dbname

where:

• your.server.name is the IP address of the server.

• 8080 is the port number.

• dominoservletpackage.PrintInfo is the name of the servlet whose classfile is contained in the vaj.servlet package.

• dbname is the name of the Notes database file which is passed to theservlet as argument.

You can use all the debugging features of VisualAge for Java such asbreakpoints and variable inspection to test the servlet before exporting it in aservlet-enabled Web server like Domino.

Visualage for Java and Domino 113

Page 134: Using VisualAge for Java To Develop Domino Applications

4.4.4 Implementing the Servlet within DominoOnce the servlet is tested you can implement it within Domino. Domino is aservlet-enabled Web server.

In order to have the PrintInfo servlet available from within Domino you haveto:

• Set up Domino 5.0 Servlet Manager (see “Domino R5.0 Servlet Manager”on page 65).

• Export the PrintInfo class file to the directory which Domino uses asservlet default directory (see “Importing and Exporting Java Code” onpage 74).

• Optionally you can specify servlet properties in the servlets.properties filelocated in the Domino data directory (see “Domino R5.0 Servlet Manager”on page 65).

To call the servlet, use the following URL:

your.server.name/servlet/PrintInfo?1=readme

114 Using VisualAge for Java to Develop Domino Applications

Page 135: Using VisualAge for Java To Develop Domino Applications

Part 2. From Theory to Practice

In this part we explain how we created a full Domino application usingVIsualAge for Java. This part shows you how to develop critical parts of asample application that makes use of both Domino and Java technologies.This application is called eTrade Vendor, and it is an eBusiness solution forthe ACME Digital company.

First we will present an overview of the application process flow andarchitecture, then the development of application components will be dividedinto the following four sections:

1. Initial Domino Development

2. Developing the POApplet applet

3. Developing the PreparePOforEvaluator agent

4. Developing the StatusReport Servlet

Each of these sections includes a more detailed discussion of thearchitecture of the components being developed, and step-by-stepinstructions for the development. Although these instructions assume you areusing Domino R5, many of the same things can be achieved using DominoR4.6, although the specific instructions would be different.

By following the development process of this application you can understandmany aspects of Domino application development using VisualAge for Java.

© Copyright IBM Corp. 1999 115

Page 136: Using VisualAge for Java To Develop Domino Applications

116 Using VisualAge for Java to Develop Domino Applications

Page 137: Using VisualAge for Java To Develop Domino Applications

Chapter 5. ACME Digital eTrade Vendor

In this chapter we present an overview of the architecture of the ACME DigitaleTrade Vendor application.

The Client ViewThe eTrade Vendor application provides an interface for a buyer from acustomer company to do the following:

• Browse the ACME Digital product catalog.

• Register as an electronic buyer.

• Be authenticated as an electronic buyer by entering a name andpassword.

• Create a new purchase order (PO), based on his or her previous PO, ifany exists.

• Submit a new PO for processing by ACME Digital.

• View a report on the status of POs they have submitted.

This interface can be accessed online either through a suitable Web browseror through a Notes client.

The Staff ViewWithin ACME Digital, staff have been assigned to evaluate new POs. Theyuse their Notes client to view the POs. They can also view the customer creditsummary.

Staff can either reject the order and an e-mail is sent to the buyer explainingthe reason for rejection, or accept it and the application generates theworkflow to process the order such as inventory pick lists, packing slips,shipping labels, and invoices.

5.1 Architecture

Figure 59 on page 118 shows the different elements of the eTrade Vendorapplication and how they are related. Its architecture is based on aclient/server model and uses different protocols to communicate between theelements.

© Copyright IBM Corp. 1999 117

Page 138: Using VisualAge for Java To Develop Domino Applications

Figure 59. eTrade Vendor Application Architecture

The customer uses a Web browser to access the eTrade Vendor application.The POApplet applet allows customers to display the ACME Digital catalogand create an order. It uses Domino R5 CORBA classes to access theDomino objects on the server. To create an order, customers must beauthenticated using a user name and a password from the Domino directory.

We used an applet for the customer interface, because an applet provides away to dynamically update calculated information in a Web browser withouthaving to reload the form from the server every time it changes. Also, theapplet provides a way to make sure that current information is displayed andthere is no opportunity to tamper with it.

The development of the POApplet applet is described in Chapter 7,“Purchase Order Applet” on page 145.

ACME Digital implements all its business rules in a Java server application,called the Business Rules application. This application accesses variousenterprise systems and provides a single Java resource for implementingbusiness rules throughout the company. There are many advantages that can

118 Using VisualAge for Java to Develop Domino Applications

Page 139: Using VisualAge for Java To Develop Domino Applications

be obtained through such an application, including separation of the definitionof business rules from other application code, improved consistency in theapplication of business rules, and the ability to rapidly adapt business rules tochanging business conditions.

The development of the Business Rules server is described in“BusinessRulesServer Class” on page 169.

Once purchase order documents have been created, the Domino agentmanager task starts the PreparePOforEvaluator agent on the eTrade Vendordatabase. This agent obtains customer credit and volume discountinformation from the Business Rules application using RMI, and item pricesfrom the product documents in the eTrade Vendor database using Notes calls.Because this agent is written in Java, it can easily access the public classesand methods of the Business Rules application. The preparePOforEvaluationagent also updates the appropriate fields in the order documents so that theyare ready for evaluation.

The development of the PreparePOforEvaluator agent is described in Chapter8, “PreparePOforEvaluator Agent” on page 201.

Finally, customers can get the status of their orders. After a customer’sauthentication, the Web application is redirected to the StatusServlet servlet.This servlet uses a JDBC connection to access the order and productdocuments in the eTrade Vendor database. It then generates and sends anHTML report back to the browser.

The development of the StatusServlet servlet is described in Chapter 9,“StatusServlet Servlet” on page 219.

5.2 Java Network Communications

Java supports many protocols to distribute applications. You have to considerthe following factors when choosing the communication protocol:

• Size of the components that need to be downloaded or installed on theclient in order to use the protocol

• Development time required to use the protocol

• Network traffic generated

• Response time

• Server support

• Reliability

ACME Digital eTrade Vendor 119

Page 140: Using VisualAge for Java To Develop Domino Applications

In the eTrade Vendor application, we chose CORBA because it is easy toimplement for the Domino objects classes. However, the trade-off is thedownload time of the complete applet. Even using the compressed version,the Domino CORBA library (ncsoc.jar) is still 700 KB that need to bedownloaded to the browser when the form is first opened and each time thebrowser’s cache is refreshed. Depending on how often this occurs, it can addup to a lot of downloading time.

In addition to CORBA, we also used RMI, because the Domino CORBAlibrary only provides access to the Domino objects classes. The applet andthe agent need to access the BusinessRules classes. Developing a CORBAinterface from scratch for these tasks would be complex. On the other hand,we could have used RMI to access the DOM classes as well, and not usedCORBA at all.

To use RMI, you have to develop client side code and a server application.Each class that you need to access remotely requires an RMI interface, butdeveloping these is relatively straightforward. Not all the classes you useneed to be distributed with the client application either—classes can beloaded dynamically from the server.

A major advantage of RMI over CORBA is that the extra code required on theclient side is minimal. However, as RMI is still a relatively new technology, itmay be difficult to obtain detailed information on the multithreading behaviorof the server. RMI also puts a requirement on the client’s Web browser, asRMI requires JDK 1.02 or higher.

JDBC requires a Notes DLL on the client side, which prevents it from beingused in most Web applications. However, as we used JDBC in a servletrunning on a Domino server, JDBC can use the server ID to access the localDomino databases. No programming is required on the server side, and clientside development is straightforward. JDBC provides a more limited access toDomino databases than the Domino object classes. For example, you cannotobtain the contents of a calculated column in a View.

Server sockets, like RMI require only the code specific to the application onthe client side, but a server application must also be developed. Socketsgenerally require more code to implement, as each data transfer must bedealt with individually. Compared to socket programming in a language suchas C, however, Java sockets are relatively self-contained and easy to use.

120 Using VisualAge for Java to Develop Domino Applications

Page 141: Using VisualAge for Java To Develop Domino Applications

5.3 Domino Client Security

Domino security applies to all clients, but works somewhat differently foreach. There are also wrinkles specific to applets.

In general, there are a number of levels of security, starting with serveraccess, then database access, View and Form access, and continuingthrough a number of levels down to field level access. In this application weare mainly concerned with Form and Document access control. These arecontrolled through a combination of three elements:

• Person (and other user types) documents in the Domino directory andsigned certifier files containing user passwords

• ACL for the database. This list includes a default entry and can bepopulated from the Domino directory. Each entry can be assigned one ofthe following security levels, listed in order of access level:

• Manager (sets database security and other settings)

• Designer (creates views, forms, agents and other elements)

• Editor (edits most documents)

• Author (creates documents, edits own documents)

• Reader (reads documents)

• Depositor (creates documents but cannot read any)

• No Access

Managers can also create security objects called roles in the ACL. Once arole is created, it can be assigned to one or more entries in the ACL. Thisis useful, for example, in controlling form and document security.

• Security settings for the form. These settings allow you to control whichentries from the ACL, including roles, can create documents with the formand which entries can read those documents.

Our database has a default access level of Author, but access to thePurchaseOrder form and documents is restricted. Users with the PO Creatorsrole can create PurchaseOrder documents, and users with the PO Evaluatorsrole can read PurchaseOrder documents. Because PO Evaluators are alsogiven Editor status in the ACL for the database, they are able to editPurchaseOrder documents created by PO Creators.

Notes Client users need to have an ID file in order to use the Notes Client.Generally, they are authenticated when they try to access the server. Dominocan tell who the user is by the ID file they are using, so they are only required

ACME Digital eTrade Vendor 121

Page 142: Using VisualAge for Java To Develop Domino Applications

to enter a password. The actual authentication process is beyond the scopeof this book but, when implemented correctly, is very secure.

In the case of Web client users, Domino authenticates them when they try toaccess anything whose access is restricted. Since the server does not knowwho they are, the user is required to enter a user name and password.Domino then finds a person document in the Domino directory that matchesthe user name, and checks the password against the value stored in theinternet password field in the person document. If the password does notmatch, access is denied. This process is not as secure as Notes Clientauthentication because there is no ID file and the user’s name and passwordare transmitted on the network in plain text. Web authentication can be mademore secure by using SSL certificates and encryption, but that is not requiredfor our sample database.

In the case of CORBA applets, Web security is a bit different. Although theuser name and password are transmitted in plain text (when SSL is not used),the server keeps track of the IP address to which the applet was downloaded,so the same user name and password will not work on another system. Thisadds an extra level of security to our application.

For more information on security, see the Domino Application DevelopersGuide and Administrators Guide.

122 Using VisualAge for Java to Develop Domino Applications

Page 143: Using VisualAge for Java To Develop Domino Applications

Chapter 6. Domino Development

Before we can get to the parts of the eTrade Vendor application that includeJava elements, we must create the Domino database and its basiccomponents to interact with. These include the following:

• A Header Subform and companyName shared field

• The Product form

• The Catalog view

• The Catalog Interface form

• The UsersPOs view

• The EditItemList subform

• The PurchaseOrder form

• The PreparedPO view

• The DisplayItemList subform

6.1 eTrade Vendor Database

Although you could download the sample database (see Appendix A, “TheSample Application” on page 265) we explain in this chapter the differentsteps needed to create a database.

6.1.1 Database CreationDomino design components cannot exist outside of a Domino database, sobefore you can create the components described above you need to create aDomino database to put them in.

To create the eTrade Vendor database, follow these steps:

1. Make sure the server you are going to create the database on is runningand that you have sufficient rights to create databases on the server.

2. Launch Lotus Notes from the Start menu. If the Enter Password promptappears, enter your Lotus Notes password and click OK.

3. Select File - Database -New. The New Database dialog appears. Choosethe server/domain where you want to create the database from the Serverdrop down list (see Figure 60 on page 124). Don’t create the database onLocal, as the server is required for the sample application to work.

If the server is not listed in the Server drop down list, try typing the servername and domain name in the format server/domain.

© Copyright IBM Corp. 1999 123

Page 144: Using VisualAge for Java To Develop Domino Applications

Figure 60. New Database Dialog

4. Complete the Title and File Name fields and click OK to create thedatabase.

Note for 4.6 users: Select File - Database - Properties and select the optionWeb Access: Use JavaScript when generating pages. Enabling JavaScriptallows you to use multiple buttons on a Web form.

6.1.2 SecurityBy default, Web users are identified as Anonymous when they access theDomino server and all the read components of the database. To allowanonymous access to the catalog but to force identification to the other partof the application, set up some roles for the users. Roles force Webauthentication to prevent Web users from being identified as Anonymous. Toset up roles, do the following:

In the eTrade Vendor database, select File - Database - Access Control

1. Select the Roles icon of the Access Control List dialog.

Click Add and enter the name PO Creators and click OK. This is the rolefor buyers.

Click Add again, enter the name PO Evaluators and click OK. This is therole for evaluators.

2. Select the Basics icon of the Access Control List dialog.

Select yourself on the People, Groups, Servers list. In the Roles list on thebottom right corner of the dialog, select [PO Creators] and [POEvaluators].

124 Using VisualAge for Java to Develop Domino Applications

Page 145: Using VisualAge for Java To Develop Domino Applications

In a production system, customers would only have the PO Creators role,and evaluators the PO Evaluators role. As a developer you may need both.

Select Local Domain Servers from the People, Groups, Servers list. Selectthe role [PO Creators].

3. Click OK to close the Access Control List dialog.

Note: Web users must have an Internet password set up in their persondocument in the Domino directory in order to be successfully authenticated.

6.2 Initial Resources Creation

The eTrade Vendor application needs a consistent look and feel. However youmust avoid re-creating common elements on every form. Domino allows youto create some common elements separately that can be used in differentforms.

In order to be able to create design elements, you need to get to the DominoDesigner window from Lotus Notes. Normally, Domino Designer access to adatabase is restricted to users that have Designer access. Since you createdthe eTrade Vendor database you are assigned Manager access to thedatabase by default which includes Designer access.

6.2.1 companyName Shared FieldYou need to create the companyName shared field that can be used todisplay the ACME Digital company name anywhere in the application (seeFigure 61 on page 126).

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Shared Fields in thelist to open the Design - Shared Fields view

Click the New Shared Field action button to open the work area of theShared Field design pane. Create a shared field called companyName. Thistext field is Computed for display. When a field appears on a form, its contentis normally stored in documents created with that form. Computed for displayfields are not saved in documents. Also users cannot directly edit computedfields.

Domino Development 125

Page 146: Using VisualAge for Java To Develop Domino Applications

Figure 61. Shared Field Creation

In the Objects outline of the companyName shared field, select Value. Typethe name of the ACME Digital company into the design pane, surrounded bydouble quotes as shown in Figure 61. This sets the computed value of thefield to a static text string containing the company name.

Choose File - Save to save the companyName shared field.

6.2.2 Header SubformNow that you have defined a shared field to display the company name, youcan create a subform to store the formatting of the field. Then you can placethe subform at the top of each form (see Figure 62 on page 127).

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Subforms in the listto open the Design - Subform view.

Click the New Subform action button to open the work area of the Subformdesign pane. In the Subform properties dialog box, enter Header as the nameof the subform.

Recent Databases

Design Bookmark

Design pane

Work Area Properties Box

126 Using VisualAge for Java to Develop Domino Applications

Page 147: Using VisualAge for Java To Develop Domino Applications

Choose Create - Insert Shared Field from the menu bar and select thecompanyName shared field. Click OK and place the field on the subform.Select the field and set its characteristics such as text size using itsproperties box.

Figure 62. Subform Creation

Choose File - Save to save the Header subform.

6.2.3 Product FormIn this section you create the form that stores product information anddisplays it to potential customers. Normally you would want to take great carein choosing how your company’s products are displayed to the public. In theinterest of simplicity, however, the steps below create a very basic version ofthis form.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Forms in the list toopen the Design - Forms view (see Figure 63 on page 128).

Click the New Form action button to open the work area of the Form designpane. In the form properties dialog box, enter Product as the name of theform.

Domino Development 127

Page 148: Using VisualAge for Java To Develop Domino Applications

Choose Create - Insert Subform from the menu bar and select the Headersubform. Click OK to insert the subform in the form.

Click below the subform and choose Create - Table. The Create Table dialogbox opens. Set the Rows field to 4, and click OK.

Figure 63. Table Creation

Select View - Ruler to display the ruler at the top of the form. The ruler allowsyou to adjust the size of the table cells. You can set the table properties suchas color and border using the Table properties box.

Domino Designer allows you to position form elements precisely withouttables. However, the appearance of the form on the Web may be quitedifferent as some formatting information such as tabs cannot be translatedto HTML. For this reason, you generally need to use tables to control theappearance of forms on the Web. If you do not want the table grid to bedisplayed, set the border width to zero. The border width of the entire tableon the Web is determined by the top left cell of the table.

Designing Web Forms

128 Using VisualAge for Java to Develop Domino Applications

Page 149: Using VisualAge for Java To Develop Domino Applications

Type in the static text in the cells of the first column. Insert the cursor in thefields of the second column and select Create - Field... Complete theinformation for each field ([productName,text], [productId, text], [productPrice,currency], [productMinOrder, decimal]) (see Figure 64 on page 129).

Figure 64. Product Form Table

Choose File - Save to save the Product form.

6.2.4 Product DocumentsYou need to create some product documents to use as test cases. UsingLotus Notes open the eTrade Vendor database. Select Create - Product andcreate some test products (see Figure 65 on page 130).

Domino Development 129

Page 150: Using VisualAge for Java To Develop Domino Applications

Figure 65. Product Document Creation

6.2.5 Catalog ViewOn the Internet, potential buyers use a view to browse the productdocuments. The view displays a list of links to the product documents.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select View in the list toopen the Design - Views view (see Figure 66 on page 130). Click the NewView button to open the properties box. Create the shared view Catalog.Shared views are available to all users who have Reader access to thedatabase.

Figure 66. View Creation

130 Using VisualAge for Java to Develop Domino Applications

Page 151: Using VisualAge for Java To Develop Domino Applications

Create a selection condition to only display product documents through thatview. Click the Add Condition button and the Search Builder dialog opens.Choose By Form Used from the condition list, and select Product from theForm list.

Click OK twice to add the view.

Double click the Catalog view in the Design - View view to open the Viewdesign pane. Click the column labeled #. In the design pane for the ColumnValue, choose the Field option and select productId.

Using the properties box, set the title to Product ID and the sort order toAscending (see Figure 67 on page 131)

Figure 67. View Column Properties

Double click to the right of the ProductID column to create a new column. Inthe design pane for the Column Value, choose the Field option and selectproductName.

Using the properties box, set the title to Product Name and select Showvalues in this column as links in the Advanced tab. By default the firstcolumn of a view provides links to the listed documents. In this case, however,it makes more sense for the link to be on the product name.

You can also adjust the column size by dragging the column border.

Domino Development 131

Page 152: Using VisualAge for Java To Develop Domino Applications

Finally, create a column for the productPrice field. You can test the look of theview by clicking on the blue swirl.

6.2.6 Catalog Interface FormThe Catalog view by itself does not provide any interface beyond access tothe product documents, and the search form. To put a more useful interfacearound this view, you need to create a form into which you can embed theview.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Forms in the list toopen the Design - Forms view.

Click the New Form action button to open the work area of the Form designpane. In the form properties box, enter Catalog Interface as the name of theform.

HeaderChoose Create - Insert Subform from the menu bar and select the Headersubform. Click OK to insert the subform in the form. To make the form morefriendly, type a line of introductory static text below the Header.

Catalog ViewClick below the static text and choose Create - Embedded Element - View.The Insert Embedded View dialog opens. Choose the Catalog view and clickOK. Using the properties box, choose the Element tab and specify the widthand the height.

New Order ButtonPlace the cursor below the view and choose Create - Hotspot - Button toplace a button on the form. Using the properties box, set the label to NewOrder. In the design pane, choose Formula in the Run drop-down list andenter the following command to launch the PurchaseOrder form when theuser clicks on the New Order button:

@Command([Compose];"PurchaseOrder").

Order Status Report ButtonCreate another button labelled Order Status Report. Leave the formula forthis button blank for now. We do not need it to be functional until theStatusServlet is created in “Integrating the StatusServlet in the Application”on page 230.

132 Using VisualAge for Java to Develop Domino Applications

Page 153: Using VisualAge for Java To Develop Domino Applications

Choose Design - Preview in Notes to check out the look of the CatalogInterface form (see Figure 68 on page 133).

Figure 68. Catalog Interface Form

6.2.7 PurchaseOrder FormTo allow customers to purchase products, you need to create the PurchaseOrder form.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Forms in the list toopen the Design - Forms view.

Click the New Form action button to open the work area of the Form designpane. In the form properties box, enter PurchaseOrder as the name of theform.

HeaderChoose Create - Insert Subform from the menu bar and select the Headersubform. Click OK.

Domino Development 133

Page 154: Using VisualAge for Java To Develop Domino Applications

Buyer’s InformationAdd a table (2 columns, 5 rows) and insert the following static text and fieldsinto the table:

Table 2. PurchaseOrder Form Fields and Text (Part I)

Select the buyersName field and enter the following formula into the designpane to automatically insert the authenticated user’s common name when aPurchaseOrder is created:

@Name([CN];@UserName)

User Role DeterminationBelow the table, insert a subform based on a formula. In the design pane forthe subform, enter the following formula:

• If you set up security roles for the database (see “Security” on page 124):

@If(@IsMember("[PO Creators]";@UserRoles);"EditItemList";"DisplayItemList")

• If you did not set up security for the database:

@If(@IsMember("$$WebClient";@UserRoles);"EditItemList";"DisplayItemList")

This formula determines which subform is displayed, depending on the Roleassigned to the user for this database, or on the client type for the database.

Static Text (column 1) Field Name (column 2) Field Type

Company Name buyersCompany text, editable

Address buyersAddress text, editable

PO Number PONumber text, editable

Ordered By buyersName name, computedwhen composed

Orderer’s EMail buyersEMail text, editable

134 Using VisualAge for Java to Develop Domino Applications

Page 155: Using VisualAge for Java To Develop Domino Applications

Orders Status and HistoryTo record the order status so that the application can generate a report(see“StatusServlet Servlet” on page 219), add a table (2 columns, 2 rows)and insert the following static text and fields into the table:

Table 3. PurchaseOrder Form Fields and Text (Part II)

Add the following formula for the orderStatus field:

@If(@IsDocBeingSaved&@IsNewDoc;"submitted";@IsNewDoc;"new";approval="";"pending";approval)

In this formula, approval refers to a radio button field that is placed on theDisplayItemList subform (see“DisplayItemList Subform” on page 141). Thisfield is set to refresh fields on keyword change.

Most field formulas are computed each time the document is refreshed. In abrowser, this occurs just before the document is displayed the first time, andjust before it is saved. In the Notes client a refresh can also occur when theuser refreshes the form or, as in this case, when a keyword field is changedby the user and the field is set to refresh fields on keyword change.

Select the orderStatusHistory field and select the Allow multiple values optionon the Basics tab. This option allows each order status to be stored as aseparate value. On the Advanced tab choose New Line in the Displayseparate values with drop-down box. Add the following formula for theorderStatusHistory field:

oldStatusHistory := orderStatusHistory;@If(@IsDocBeingLoaded|@IsDocBeingSaved;null;@Return(oldStatusHistory));newStatusHistory := orderStatus + " as of " + @Text(@Now);@Trim(newStatusHistory:oldStatusHistory)

This formula simply places the status and current date and time as a newvalue in the list of values for the orderStatusHistory field. The ":" operator inthe last line is used to join an item or list to another item or list.

Static Text (column 1) Field Name (column 2) Field Type

Order Status orderStatus text, computed

History orderStatusHistory text, computed

Domino Development 135

Page 156: Using VisualAge for Java To Develop Domino Applications

Submit ButtonAdd a button at the bottom of the form. Using the properties box, set the labelto Submit. In the Hide When tab of the properties box, choose the Hideparagraph if formula is true option and insert the following formula (seeFigure 69 on page 136):

!@IsMember("[PO Creators]":"$$WebClient";@UserRoles)

Figure 69. Properties Box: Hide When Tab

We could have used the @NewLine function between each status entry toachieve the same effect with a single-value text field. The problem with thisis that the field is not computed when the document is saved later by thePreparePOforEvaluator agent, so the agent has to update the field.Because the agent is written in Java, we would have to use somecombination of \n and \r to separate the lines. Unfortunately thesecharacters are not translated to line wrap characters when the text isdisplayed in the Notes client.

Another option would have been to use a rich text field, because the Javaagent could use the addNewLine method of the RichTextItem class. Thiswould display fine in the Notes client, but it raises the problem that rich textfields are not computed when the document is saved, so our formula wouldnot do what we want. Also, rich text fields cannot be used as column valuesin a view, and this would have made it impossible to use JDBC in the POStatus Report servlet (see “StatusServlet Servlet” on page 219).

Multiline Text Fields

136 Using VisualAge for Java to Develop Domino Applications

Page 157: Using VisualAge for Java To Develop Domino Applications

This formula allows PO Creators who are viewing the form in a Web browserto see the button. PO Creators who view the form in a Notes client canchoose File - Save from the menu bar.

In the design pane, enter the following JavaScript formula in the button’sonClick event:

setItems(this.form);this.form.submit();

This formula allows you to create PurchaseOrder documents before thePOApplet is created. In “JavaScript Code” on page 198 you add JavaScript tothis button to recover the PO information from the applet and save thedocument.

Figure 70 on page 137 shows the PurchaseOrder form design.

Figure 70. PurchaseOrder Form

Security OptionsIf you set up the roles for the eTrade Vendor database (see “Security” onpage 124), you can implement the roles for the PurchaseOrder form.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Forms in the list toopen the Design - Forms view. Open the PurchaseOrder form.

Using its properties box, click the Security tab:

• Set the default read access for documents created with this form only to[PO Evaluators].

Domino Development 137

Page 158: Using VisualAge for Java To Develop Domino Applications

• Allow the [PO Creators] to create documents with this form. Deselect theAll authors and above option and select the [PO Creators] from the listjust below.

6.2.8 Previous Orders ViewThe eTrade Vendor application displays the buyer’s previous order each timea new order is created. The PreviousOrders view gathers the data.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select View in the list toopen the Design - Views view.

Click the New View button to open the properties box. Create the shared viewPreviousOrder.

Create a selection condition to only display documents created with thePurchaseOrder form.

Set the first column value to the buyersName field. Using the properties box,set the column to standard ascending sort. The column needs to be sorted toallow the use of a formula to look up values in the EditItemList subform.

Set the second column to the Creation Date simple function. Set this columnto sort in descending order to ensure that the most recent purchase ordersare listed first.

Set the third column to the following formula to display the unique identifier foreach document shown in the view:

@Text(@DocumentUniqueID)

6.2.9 EditItemList SubformAlthough the PurchaseOrder form exists, it is of no use until we create at leastthe EditItemList subform. This form provides a place to embed the purchaseorder applet (see Chapter 7, “Purchase Order Applet” on page 145), feed itparameters, and store the results.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Subforms in the listto open the Design - Subform view.

Click the New Subform action button to open the work area of the Subformdesign pane. In the Subform properties dialog box, enter EditItemList as thename of the subform.

138 Using VisualAge for Java to Develop Domino Applications

Page 159: Using VisualAge for Java To Develop Domino Applications

lastOrderID Text FieldCreate the lastOrderID text field with the Computed for display option.Uncheck the Allow multiple values option. Add the following formula to thefield value:

lastOrderIDs :=@DbLookup("":"NoCache";"":"";"PreviousOrders";buyersName;3);@If(@IsError(lastOrderIDs);"";@Subset(lastOrderIDs;1))

This formula obtains a list of unique identifiers for documents listed in thePreviousOrders view. Once the list is generated, the @Subset functionextracts the first element which becomes the value of this field.

Note: Obtaining the unique identifier in this way may not result in the buyer’smost recent entry being displayed when new entries are added during asession. We found that with Netscape 4.5 we could only guarantee getting thelatest entry if we used Shift+Refresh to clear the cache and reload the entirepage. Simply setting the browser to compare the cached file to the file on thenetwork every time, or clicking on the Refresh button, did not always returnthe latest entry. There may be ways to get around this, by including dynamicinformation in the URL that opens the page, for example. In the case of thisapplication, however, it is not a significant issue, since buyers are not likely tocreate more than one PurchaseOrder per session.

itemsOrdered Text FieldCreate the itemsOrdered text field with the Editable option. Check the Allowmultiple values option. Add the following formula to the field default value:

@If(lastOrderID="";"";@GetDocField(lastOrderID;"itemsOrdered"))

This formula sets this field to the list of items ordered in the buyer’s previousPurchaseOrder document.

quantitiesOrdered Text FieldCreate the quantitiesOrdered text field with the Editable option. Check theAllow multiple values option. Add the following formula to the field defaultvalue:

@If(lastOrderID="";"";@GetDocField(lastOrderID;"quantitiesOrdered"))

This formula sets the field to the list of quantities ordered in the buyer’sprevious PurchaseOrder document.

Static TextAdd the following line of static text to the next line of the subform:

The order items below are based on your previous order:

Domino Development 139

Page 160: Using VisualAge for Java To Develop Domino Applications

In the Hide When tab of the properties box of the text line, choose the Hideparagraph if formula is true option and insert the following formula:

!@IsNewDoc|lastOrderID="".

Figure 71 on page 140 shows the EditItemList subform.

Figure 71. EditItemList Subform

6.2.10 PreparedPO ViewThe evaluators at ACME Digital need a basic interface for accessing the POsthat need to be evaluated.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select View in the list toopen the Design - Views view (see Figure 66 on page 130). Click the NewView button to open the properties box. Create the shared view PreparedPO.Shared views are available to all users who have Reader access to thedatabase.

Create a selection condition to only display order documents that have beenprepared; that is, the orderStatus field is different from new or submitted.

Click the Add Condition button and the Search Builder dialog opens. ChooseBy Field from the condition list, and search for documents where theorderStatus field does not contain the value new.

Click again the Add Condition button. Choose By Form used from thecondition list, and search for documents where the orderStatus field does notcontain the value submitted.

140 Using VisualAge for Java to Develop Domino Applications

Page 161: Using VisualAge for Java To Develop Domino Applications

Finally, click the Add Condition button. Choose By Form Used from thecondition list, and select PurchaseOrder from the Form list.

Click OK twice to add the view.

Double click the PreparedPO view in the Design - View view to open the Viewdesign pane.

Set the value of the first column to the Simple Function Last Modified. Add anew column and set its value to the field orderStatus.

You may want to do further customization on your own but this is all we needfor the eTrade Vendor application.

6.2.11 DisplayItemList SubformWhen evaluators—users with [PO Evaluator] role—open a purchase orderdocument in the eTrade Vendor database the PurchaseOrder form isgenerated with the DisplayItemList subform instead of the EditItemListsubform presented to customers. Evaluators are able to mark the PO asapproved or rejected and can read additional information about the buyer.When creating the PurchaseOrder form, in the “User Role Determination” onpage 134, you place a formula that selects the subform to display dependingof the role of the user. You must now create the DisplayListItem subform.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Subforms in the listto open the Design - Subform view.

Click the New Subform action button to open the work area of the Subformdesign pane. In the Subform properties dialog box, enter DisplayItemList asthe name of the subform.

Domino Development 141

Page 162: Using VisualAge for Java To Develop Domino Applications

Select Create - Table to create a table (2 rows, 5 columns) to help format thefields properly. Insert the following static text and fields into the table:

Table 4. DisplayItemList Subform Fields and Text (Part I)

Add the following single value fields with static text labels below the table youjust created:

Table 5. DisplayItemList Subform Fields and Text (Part II)

Static Text(Row 1)

Field Name(Row 2)

Field Type Options

Product ID itemsOrdered computed text field

Allow multiple values

Display separatevalues with new line

Name itemNames computed text field

Price itemPrices computed currency field

Quantity quantitiesOrdered computed text field

Item Totals itemTotals computed currency field

Since the fields are computed, enter the field’s name (without quotes) in the Formuladesign pane for each field’s value. The values are filled in when the subform is displayed.

Field Name Field Type Formula

orderSubtotal computed currency field orderSubtotal

orderDiscount computed percent field orderDiscount

orderTotal computed currency field orderTotal

buyersCredit computed text field buyersCredit

evaluator computed names field @Name([CN];@UserName)

approval editable radio button field approval

Using the properties box of the approval field, create the following choices:approveddenied

Select the Refresh fields on keyword change option. As the status field on thePurchaseOrder form has a formula that references this field, setting this option forces thestatus field to change when the approval field changes.

142 Using VisualAge for Java to Develop Domino Applications

Page 163: Using VisualAge for Java To Develop Domino Applications

6.3 Testing the Domino Elements

At this stage, you can try out the eTrade Vendor application you have created.

Start your Web browser and enter the following URL:

your.server.name/eTradeVe.nsf/Catalog+Interface/?OpenForm

Try out the Catalog interface. You need to use the browser’s back button toget back to the catalog from the products. You can create purchase orderdocuments even though the purchase order applet has not yet beenimplemented. Simply type the product IDs and quantities into the itemsordered and quantities ordered fields. Separate multiple values with asemicolon.

Once everything is working using the Web browser, you can try the eTradeVendor application using the Notes client. At this stage, it should work almostthe same.

Since this subform is only intended to be used in a Notes client the refreshfields on keyword change option works. If the subform has to be displayedon the Web, you can use JavaScript.

Another way to refresh fields in a document in the Notes client is to selectthe Automatically refresh fields option in the properties box of the form.However, it can slow down the display of the form. Use a LotusScript orJavaScript field event instead.

Refreshing Fields

Domino Development 143

Page 164: Using VisualAge for Java To Develop Domino Applications

144 Using VisualAge for Java to Develop Domino Applications

Page 165: Using VisualAge for Java To Develop Domino Applications

Chapter 7. Purchase Order Applet

The Purchase Order applet (POApplet) allows customers to create an order.The applet is the customer user interface to the eTrade Vendor application.

In this chapter we explain how to develop a Java applet using VisualAge forJava and using the Domino classes for Java. We also explain how to connecta Domino application to an enterprise system using Java and its built-in RMIfacilities.

This development requires Domino R5. Using Domino R4.6, applets cannotuse the Notes object interface, as the Domino classes for Java only call Noteslibrary functions and the security restrictions for applets do not allow appletsto make calls to native libraries on the client system.

Domino R5 implements the Java class library using CORBA. CORBA offers acommunication mechanism between the applet and the server. CORBA isalso transparent for the user of the new Domino objects classes.

7.1 Design Overview

The POApplet applet is displayed as part of the EditItemList subform on thePurchaseOrder form (see “EditItemList Subform” on page 138). The appletdisplays the items on the customer’s current purchase order. It displaysbuttons to add and delete items. It has methods to pass the ordered itemsback to the purchase order form when the form is submitted.

Figure 72 on page 146 shows a prototype of the screen panels of thePOApplet applet. To place a purchase order, the customer connects to theeTrade Vendor application opening the PurchaseOrder form. Afteridentification, the POApplet starts, showing an initial list of items, based onthe last order that the customer placed. The items of the last order arepassed to the POApplet as applet parameters in the applet tag.

© Copyright IBM Corp. 1999 145

Page 166: Using VisualAge for Java To Develop Domino Applications

Figure 72. POApplet GUI Prototype

The customer can delete displayed items by selecting an item on the list andclicking the Delete Item button. This action triggers the following process:

• Call of the deleteItem() method of the purchase order object (PO)• PO sent to the BusinessRules for checking• Refresh of POApplet displayed fields

The customer can add an item to a purchase order by clicking the Add Itembutton. The catalog view (see “Catalog View” on page 130) is opened inanother browser window and the add dialog is shown (see Figure 73).

Figure 73. Add Dialog

The customer enters a productID from the catalog and the needed quantityand clicks on the Order button. This action triggers the following process:

• POApplet gets the required data (minOrder, price...) from the catalogdatabase on the database server.

• If correct (reference, quantity)• Item is added to PO• PO sent to the BusinessRules for checking• Refresh of POApplet displayed fields

• If in error:• Customer is prompted to correct order.

Finally, the customer clicks on the Submit button of the PurchaseOrder form.The form creates a new purchase order document with the POApplet data.

146 Using VisualAge for Java to Develop Domino Applications

Page 167: Using VisualAge for Java To Develop Domino Applications

7.2 POApplet Components

The POApplet applet is made of the following components:

• POApplet class

The POApplet class holds the graphical components of the applet. It alsoholds:

• A PO object—an instance of the PO class—that is displayed in theapplet.

• A Catalog object that does all the communication with the Dominoserver.

• A BusinessRules object that ensures the PO is in accordance with yourcompany’s business rules.

• PO class

The PO class holds the ID of the customer and all items of the PO. It alsoholds a field for a possible discount and a status field to report the statusof the business rules method. In addition it supplies a string representationof the ordered items, which is stored in the PO document, and methods toadd and delete items.

• POItem class

The POItem class represents one single item on a PO. It holds the itemID,the item description, the price per unit, the minimum quantity that can beordered and the quantity that is ordered. In addition it supplies methods tocompute the total price and to create the output for the PO form.

• Catalog class

The Catalog class holds the products database. In addition it has methodsto get product data from the database.

• BusinessRules class

The BusinessRules class holds a Vector of SingleRule objects. It has acheck method, that checks if the provided PO meets all of the businessrules that are stored in the vector. The PO that is passed by the checkmethod is probably modified by the method by means of updating thestatus and providing a possible volume discount.

• SingleRule interface

The SingleRule interface defines only the check method, which takes aPO as input and checks the PO for accordance. The check method canmodify the PO. If the PO stands in contrast to the business rules the checkmethod appends its status to the PO’s status field.

Purchase Order Applet 147

Page 168: Using VisualAge for Java To Develop Domino Applications

• BusinessRulesServer class

The BusinessRulesServer class is a server application that marshalls RMIcalls to check the business rules. It hold a BusinessRules object that doesthe actual checking.

• AddDialog class

The AddDialog class holds the graphic components needed to enter a newitem for the PO.

The POApplet class and the Catalog class encapsulate all the communicationbetween the POApplet and the Domino server. CORBA is used to access theDomino objects on the server.

The BusinessRulesServer class doesn’t reside on the client machine. It is aserver application, whose methods are called using RMI. Implementing thebusiness rules in that way gives you the possibility to integrate almost everyrule ACME Digital might have. You just have to write a class that implementsthe SingleRule interface, which means it has a check method. This checkmethod translates the PO into the proper format and can access almost anyenterprise system either Java-based or implemented in other languagessupported by the Java native interface (JNI).

7.3 Project and Packages

VisualAge for Java helps you to organize the Java code. All eTrade Vendorapplication classes are grouped in one project called eTradeVendor.

Launch VisualAge for Java. Select Selected - Add - Project in any browserwindow. Create the eTradeVendor project using the Add Project pane (seeFigure 74 on page 149).

148 Using VisualAge for Java to Develop Domino Applications

Page 169: Using VisualAge for Java To Develop Domino Applications

Figure 74. Add Project Pane

Within that project you need to create the packages. Select the eTradeVendorproject and Selected - Add - Package. You can create the followingpackages using the Add Package pane (see Figure 75 on page 150):

• acme.po package for the non-graphical parts

• acme.po.gui package for the GUI classes needed for the POApplet

• acme package for the back-end classes

• acme.rmi for the RMI-related classes

Purchase Order Applet 149

Page 170: Using VisualAge for Java To Develop Domino Applications

Figure 75. Add Package Pane

7.4 POItem Class

The POItem class represents one single item on a PO. It holds the itemID, theitem description, the price per unit, the minimum quantity that can be orderedand the quantity that is ordered. In addition, it supplies methods to computethe total price and to create the output for the PO form.

To create the Java code for a class you need to create:

• Class• Fields• Constructor• Methods

POItem ClassIn the eTradeVendor project, select the acme.po package and Selected -Add - Class. The Create Class pane is displayed (see Figure 35 on page 88).Select Create a new class and enter POItem as the classname. Leavejava.lang.Object in the superclass field. You don’t browse the class whenfinished and don’t compose the class visually.

150 Using VisualAge for Java to Develop Domino Applications

Page 171: Using VisualAge for Java To Develop Domino Applications

Click Next to display the Attributes pane (see Figure 76 on page 151). ThePOItem class does not require any additional import statement and does notimplement any interface. (You can add import and implements statementslater.)

The POItem class is public. Keep the other default checked values.

Create a toString() method to print out the attributes of the POItem classrather than its memory address.

Figure 76. Attributes Pane

Though the workbench is a very useful view for managing your code, we findthe project browser the most useful view for actual development. To open theproject in the project browser (see Figure 77 on page 152), double-click onthe eTradeVendor project.

The project browser has the same functions as the packages view of theworkbench. However, it shows only the packages included in the selectedproject. The project browser window allows you to concentrate only on theproject you are currently working on. Using the project browser you have a

Purchase Order Applet 151

Page 172: Using VisualAge for Java To Develop Domino Applications

structured view of your entire project that no text editor could ever give you.We consider this view a reason to use VisualAge for Java even if you write allyour code manually.

Figure 77. Project Browser

FieldsNow, you need to add the required attributes to the POItem class. In theeTradeVendor project browser window, select the acme.po package, thePOItem class and Selected - Add - Field. The Create Field pane is displayed(see Figure 78 on page 153).

Create the fields listed in Table 6 on page 154. To set the name of a fieldstrictly you have to enter the fully qualified typename. That meanspackagename.classname. But there are exceptions to that rule. You don’thave to enter the package name if one of the following is true:

• The type is in the same package.

• You added an import statement for the package or type you arereferencing to your class declaration.

• The type is defined in the java.lang package.

152 Using VisualAge for Java to Develop Domino Applications

Page 173: Using VisualAge for Java To Develop Domino Applications

Set the corresponding field type for each created field. To set the fieldtype—String for example—you can do one of the following:

• Enter String in the type field (String is contained in java.lang so you don’thave to specify the packagename).

• Select String from the drop-down list.• Click Browse and select String that way.

Enter any value in the Initial Value field to initialize the field with that value. Ifyou leave that field blank your field is implicitly initialized with null.

To prevent the uncontrolled modification of any attribute, set the AccessModifiers to private. Check the Access with getter and setter methodscheckbox and choose public as access modifiers for those methods toprovide access to these attributes (getter method).

Figure 78. Create Field Pane

Purchase Order Applet 153

Page 174: Using VisualAge for Java To Develop Domino Applications

Table 6 lists the fields of the POItem class.

Table 6. POItem Class Fields

Fields padding and padding1 are static fields used as fill characters (see“align() method” on page 157). The initial value for padding is {’ ’,...}, where ...stands for another 19 space characters. The initial value for padding1 is{’0’,...}, where ... stands for another 9 zeroes.

ConstructorTo create a new object of a class you need to call its constructor. Aconstructor is a special method that has the same name as the class itself. Itis used to create a new instance of the class using the new instruction. Forexample, the following Java code creates a new instance of the POItemclass:

// new instance of POItem:POItem item=new POItem();

Every class has an implicit constructor, the default constructor. The defaultconstructor requires no input parameters and implicitly calls super(), thedefault constructor of the superclass. But be careful if you define additionalconstructors. Then the default constructor disappears and you have to defineit explicitly. A class can have multiple constructors with different inputparameters.

Field Name Field Type getter method

productID String Yes

productName String Yes

priceUnit double Yes

minOrder double Yes

quantity double Yes

padding static char[] No

padding1 static char[] No

154 Using VisualAge for Java to Develop Domino Applications

Page 175: Using VisualAge for Java To Develop Domino Applications

You need to create a new constructor for the POItem class in order toinitialize its attributes with the provided values. In the eTradeVendor projectbrowser window, select the acme.po package, the POItem class, andSelected - Add - Method. The Create Method pane is displayed (see Figure78 on page 153).

Figure 79. Create Method Pane

Select Create a new constructor. Set the constructor name to POItemaccording to the constructor syntax. Click Next. On the Attributes pane leavethe modifier set to public.

The description of a method, its input types and parameters and return typein the form:

Returntype methodname(Type1 param1, ... Typen paramn)

is referred to as the signature of the method. A signature declares theformat of the method call. You can omit the return type if the method doesnot return any value. You can also omit the input parameters if the methoddoes not require input parameters.

Signature of a method

Purchase Order Applet 155

Page 176: Using VisualAge for Java To Develop Domino Applications

Select the new constructor from the Methods pane and replace the codeshown in the source pane with the following lines:

public POItem(String productID, String productName,double priceUnit,double minOrder, double quantity) {

this.productID = productID;this.productName = productName;this.priceUnit = priceUnit;this.minOrder = minOrder;this.quantity = quantity;

}

The prefix this. tells the compiler that you are referring to the object itself.This is necessary here because the name of an instance variable is hidden bythe input parameter with the same name. Usually you can access instancevariables without prefixing their names with this.

MethodsThe interaction of an object with its environment is defined in the methods ofthe class. A method definition includes a signature and a body that containsthe code to be executed.

In Java you can restrict the visibility of methods using access modifiers. Thisallows you to specify who is able to invoke the method.

In the following section we develop additional methods for the POItem class.

• getTotal() method

In the eTradeVendor project browser window, select the acme.popackage, the POItem class, and Selected - Add - Method. The CreateMethod pane is displayed. Replace the suggested signature voidnewMethod() with double getTotal(). Leave the modifiers set to public.

public double getTotal() {return (quantity*priceUnit);

}

156 Using VisualAge for Java to Develop Domino Applications

Page 177: Using VisualAge for Java To Develop Domino Applications

• align() method

The align method is a static helper method that formats double values in aString with the total length length and the precision precision. There is norounding. To get the integer part and the fraction of input we use the classjava.util.StringTokenizer. StringTokenizer allows you to specify a String tobe tokenized and a string that contains the token separators. Followingeach call, the nextToken() method will return the next token of the inputstring.

public static String align(double input, int precision, int length) {// CREATE STRINGBUFFER TO CONSTRUCT THE OUTPUTStringBuffer temp = new StringBuffer();// CREATE STRINGTOKENIZER TO PARSE THE INPUTjava.util.StringTokenizer tok =new java.util.StringTokenizer(Double.toString(input), ".");// GET DOLLARSString first = tok.nextToken();// GET CENTSString last = tok.nextToken();// FILLUP LEFTEND WITH SPACES, APPEND DOLLARS AND DECIMAL SEPARATORtemp.append(padding1, 0,

length-first.length()-precision-1).append(first).append('.');if (last.length() >= precision) {

// CUT WHOLE CENTStemp.append(last.substring(0, precision));

} else {// FILL WITH ZEROS TO GIVE PRECISIONtemp.append(last).append(padding, 0, precision - last.length());

}// RETURN OUTPUTreturn temp.toString();

}

• toString() method

In Order to enhance the performance of your Java applications youshould define a method final (which means that it can’t be overridden bya subclass) or static whenever it is possible. That means that thecompiler (when started with the -O option) can replace every call to thatmethod with the method’s code, because it can’t be overridden by anysubclass. That makes every overhead for calling a method obsolete. Butbe careful. Copying the method code into every call will also increasethe size of your bytecode.

Performance Issues

Purchase Order Applet 157

Page 178: Using VisualAge for Java To Develop Domino Applications

You have to define the behavior of the toString() method as VisualAge forJava has just generated the super.toString() call which just prints the classname and memory address. You need to modify the output to a formattedstring that includes productID, description, priceUnit, minOrder, quantityand the total price. The alignment of the different parts of the output isdone by calls to the align() method.

public String toString() {// CREATE STRINGBUFFER TO CONSTRUCT OUTPUTStringBuffer temp = new StringBuffer();// APPEND PRODUCTIDtemp.append(productID);// FILL WITH SPACES TO LENGTH OF 10temp.append(padding, 0, 10 - productID.length());// APPEND PRODUCTNAMEtemp.append(productName);// FILL WITH SPACES TO LENGTH OF 10temp.append(padding, 0, 25 - productName.length());// APPEND PRICE PER UNIT WITH TOTAL LENGHT 10 AND PRECISION 2temp.append(align(priceUnit, 2, 10));// APPEND MINIMUM ORDER WITH TOTAL LENGHT 10 AND PRECISION 2temp.append(align(minOrder, 2, 10));// APPEND QUANTITY WITH TOTAL LENGHT 10 AND PRECISION 2temp.append(align(quantity, 2, 10));// APPEND TOTAL WITH TOTAL LENGHT 10 AND PRECISION 2temp.append(align(getTotal(), 2, 10));// RETURN OUTPUTreturn temp.toString();

}

The toString() method utilizes a StringBuffer variable, which is dynamicallyextendable to hold the output. For each field, the method adds anappropriate number of spaces to get a properly formatted output. Thenumerical fields are aligned using the align() method.

Avoid excessive use of the concatenation operator (+) on String,because it results in the construction of a new String object every timethat it is executed. If you build a long String from many short ones usethe StringBuffer class and its append method instead.

Performance Issues

158 Using VisualAge for Java to Develop Domino Applications

Page 179: Using VisualAge for Java To Develop Domino Applications

7.5 PO Class

The PO class holds all data needed for the purchase order: the user ID, a listof items, a discount and a status text. The addItem() method of the PO classadds items to the order. Methods getSubtotal(), and getTotal() compute theprice of the items on the purchase order.

PO ClassCreate the PO class in the acme.po package the same way you created thePOItem class.

FieldsAdd the fields listed in Table 7 on page 159 to the PO class. Set all modifiersto private. Check the Access with getter and setter methods checkbox andcreate the getter and setter methods.

Table 7. PO Class Fields

ConstructorCreate a new constructor for the PO class that sets the userID field of thenew object to the passed parameter value.

public PO (String username) {this();userID= username ;

}

MethodsYou need to create the following methods:

• addItem() method

This method takes a POItem object and adds it to its itemlist. This is doneby delegating the add operation to the addElement method of the classjava.util.Vector.

public void addItem(POItem item) {// CALL VECTOR.ADDELEMENTitemlist.addElement(item);

}

field name type

userID String

itemlist java.util.Vector

discount double

statusText String

Purchase Order Applet 159

Page 180: Using VisualAge for Java To Develop Domino Applications

• getSubtotal() method

This method returns the total price of all items on the PO before anydiscount. This is done by adding up the results of the getTotal() method ofeach POItem in itemlist.

public double getSubtotal() {double temp=0;for (int count=0;count<itemlist.size();count++){

temp=temp+((POItem)itemlist.elementAt(count)).getTotal();}return temp;

}

• getTotal() method

This method returns the total price for the PO after discount. This is doneby calling the getSubtotal method and applying the discount provided inthe discount field.

public double getTotal() {return (getSubtotal()*((100-discount)/100));

}

7.6 AddDialog Class

The AddDialog class provides the user interface for entering the product IDand quantity for a new order item to be added to a purchase order. As thisclass contains only visual components, you use the Visual CompositionEditor to create the AddDialog.

AddDialog ClassIn the eTradeVendor project, select the acme.po.gui package and Selected -Add - Class. The Create Class pane is displayed. Select Create a new classand enter AddDialog as the classname. Enter java.awt.Dialog in thesuperclass field. The Dialog class provides the basic behavior for a dialogwindow. You don’t compose the class visually.

FieldsTo link the POApplet and the AddDialog windows, you need to create thepoapplet field to store the reference of the POApplet instance that created theAddDialog object.

However, at this stage of the development, you are not able to create thepoapplet field using the Create Field pane. VisualAge for Java does notrecognize the POApplet type as the POApplet class is not yet created.

160 Using VisualAge for Java to Develop Domino Applications

Page 181: Using VisualAge for Java To Develop Domino Applications

As the POApplet class holds also a reference to its AddDialog, you get anerror message no matter which class is created first.

There are two workarounds for this problem:

• Create the class POApplet with an empty body.

• Define the poapplet field directly in the Source pane of the AddDialogclass. Although the class is tagged with an error, you are able to save itsdefinition.

To define the field directly, select the AddDialog class and enter the followinginto the source pane:

public class AddDialog extends java.awt.Dialogimplements java.awt.event.ActionListener,

java.awt.event.WindowListener {private POApplet poapplet=null;

}

ConstructorCreate a new constructor for the AddDialog class that receives a reference tothe caller, delegates its construction to another (inherited) constructor andsets the poapplet field to the parameter’s value.

public AddDialog(acme.po.gui.POApplet poapplet) {this(new java.awt.Frame());this.poapplet=poapplet;

}

Visual CompositionThe Visual Composition Editor of VisualAge for Java allows you to lay out thegraphical components of the AddDialog dialog.

Select AddDialog class and Selected - Open to open the Visual CompositionEditor (see Figure 80 on page 162).

Purchase Order Applet 161

Page 182: Using VisualAge for Java To Develop Domino Applications

Figure 80. Visual Composition Editor: AddDialog

VisualAge for Java creates automatically the connection to the dispose()method.

From the bean palette, select a Label bean and drop it into the AddDialogbean. Set the beanName to productIDLabel and the text to Product ID.Create also the quantity label (quantityLabel, Quantity) and the status linelabel (statuslineLabel, Statusline).

Using the TextField bean create the two entry fields with beanName set toproductIDField and quantityField.

Using the Button bean, create two buttons with beanName set to orderButtonand cancelButton and their text to Order and Cancel.

Figure 81 on page 163 shows the final layout of the AddDialog class.

162 Using VisualAge for Java to Develop Domino Applications

Page 183: Using VisualAge for Java To Develop Domino Applications

Figure 81. AddDialog Layout

To generate all the variables, save the bean. Select Bean - Save Bean.

Connecting the ComponentsIn this section you create connections between the components using theVisual Composition Editor. When the composition is done, VisualAge for Javagenerates the needed lines of code automatically.

In “POApplet Class” on page 172, we explain an alternative method to theVisual Composition Editor.

Cancel ButtonThe Cancel Button invokes the dispose method. Select the Cancel button andclick on the right mouse button. Choose Connect - actionPerformed. Movethe mouse pointer over the invisible part of the AddDialog and click on theright button again. Choose dispose().

Order ButtonUsing Event-to-Code connections of the Visual Composition Editor, you canconnect each event within your class to a piece of handwritten code. TheOrder button is defined with an Event-to-Code connection.

Select the Order button and click on the right mouse button. Choose Connect- actionPerformed. Move the mouse pointer over the invisible part of theAddDialog and click on the right button again. Choose Event to Code. TheEvent-to-Code connection window opens (see Figure 82 on page 164).

Purchase Order Applet 163

Page 184: Using VisualAge for Java To Develop Domino Applications

Figure 82. Event to Code Window - Visual Composition Editor.

Enter the code for the method; that is, call the POApplet’s addItem() methodwhen the user clicks the Order button.

Save the new method. Again, VisualAge for Java may say that the variablenamed poapplet is not defined.

invalidData MethodThis method is invoked from the PO’s addItem method if it encounters aninvalid productID or a quantity less than the minimum quantity for the product.The invalid data sets the display fields to the provided values and refreshesits display.

public void invalidData(String status,String productID, double quantity) {ivjstatuslineLabel.setText(status);ivjproductIDField.setText(productID);ivjquantityField.setText(Double.toString(quantity));validate();

}

7.7 Catalog Class

The Catalog class is used in the POApplet applet to communicate with theDomino server. The POApplet accesses ACME Digital’s product catalog toextract the name, price and the minimum quantity that can be ordered for agiven productID and quantity. The Catalog class gathers data to construct a

164 Using VisualAge for Java to Develop Domino Applications

Page 185: Using VisualAge for Java To Develop Domino Applications

new POItem object for a valid productID and a sufficient quantity. It throws aNotesException with a proper status text in any other case.

PrerequisitesDomino R5 and its CORBA implementation allows you to access the Dominoobjects. The CORBA communication is totally transparent. You just have toimplement the NotesFactory class that includes static methods to create asession with the Domino server. When the remote session is created, you canuse it in the same manner as if it was local. And because the POApplet appletis downloaded from the eTradeVe.nsf database on the Domino server, youdon’t even have to worry about the creation of a session.

To use the Domino object classes required for remote Domino access usingCORBA you have to import the required packages into your workspace.

In VisualAge for Java, create a new Domino CORBA Classes project. SelectFile - Import, from the menu bar to import a Jar file. Import from a jar/zip filethe following jar file:

c:\lotus\domino\domino\java\ncso.jar

Catalog ClassThe Catalog class holds fields for the eTradeVe.nsf database and for theCatalog view of that database. In addition it holds constants for database,view and column names.

Select the eTradeVendor project and the acme package. Create the Catalogclass in the acme package the same way you created the POItem class.Make sure that you import the acme.po and lotus.domino packages.

FieldsAdd the following field definitions:

public class Catalog {// CONSTANTS FOR DB, FIELD AND VIEW NAMESprivate final static String VIEWNAME = "Catalog";private final static String COLUMNNAME = "productName";private final static String COLUMNMINORDER = "productMinOrder";private final static String COLUMNPRICE = "productPrice";// CATALOG VIEWprivate View catalog;private Database Db ;

}

ConstructorsThe constructor sets the Catalog’s view field by calling the getView method.

Purchase Order Applet 165

Page 186: Using VisualAge for Java To Develop Domino Applications

public Catalog(Database db) {try{

catalog= db.getView(VIEWNAME);}catch (lotus.domino.NotesException e) {

System.out.println(e);System.out.println(e.text);e.printStackTrace();

}}

getItem() MethodThe main purpose of the Catalog class is to create a new POItem for a givenproduct ID and quantity, with the additional fields contained in theeTradeVe.nsf database. All the work is done by the getItem() method, aunique method of the Catalog class.

The getItem() method receives a productID and a quantity as parameter andreturns a POItem. It gets the data required to create a POItem by retrievingthe right product Document from the catalog view using itsgetDocumentbyKey() method. It then extracts the values of the Document’sitems using the getItemValueType() method (where Type stands for the actualtype).

The getItem() method throws a NotesException when an invalid productID ispassed or the quantity is less than the minimum order. If a NotesException isthrown by one of the Domino objects classes, set the database and the viewto null and pass the NotesException to the caller.

public POItem getItem(String productID, double quantity)throws NotesException {

// CHECK IF PRODUCTID WAS PASSEDif (productID.equals("")) {

throw new NotesException(-1, "Invalid productID " + productID);}// GET PRODUCT DOCUMENT FROM CATALO VIEWDocument doc = catalog.getDocumentByKey(productID);// INVALID PRODUCTIDif (doc == null) {

throw new NotesException(-1, "Invalid productID " + productID);}// GET MINORDER FROM CATALOG VIEWdouble minOrder = doc.getItemValueDouble(COLUMNMINORDER);if (minOrder > quantity) {

// THROW EXCEPTION IF QUANTITY LESS THEN MINORDERthrow new NotesException(-1, "Minimum Quantity of " + productID + " "

+doc.getItemValueString(COLUMNNAME) + " is "

166 Using VisualAge for Java to Develop Domino Applications

Page 187: Using VisualAge for Java To Develop Domino Applications

+ minOrder);} else {

// GET REST OF THE FIELDS FROM THE CATALOG VIEW// CREATE NEW POITEM AND RETURN ITtry {return new POItem(productID, doc.getItemValueString(COLUMNNAME),

doc.getItemValueDouble(COLUMNPRICE), minOrder, quantity);} catch (NotesException ne) {

// SET CATALOG TO NULL// A NEW SESSION WILL BE CREATED BY THE NEXT CALL OF GETITEMcatalog = null;db = null;throw ne;

}}

}

7.8 Business Rules

At ACME Digital, all business rules are enforced using a business rulesserver. The BusinessRulesServer uses RMI to communicate with its clientsand serve their requests to check a purchase order for accordance.

The BusinessRules application use RMI to communicate. It has the followingcomponents:

• The BusinessRulesServer application holds all references to aBusinessRules object. To be checked, orders are passed to theBusinessRulesServer’s check() method which, in turn, delegates thechecking to the BusinessRules’s check() method.

• The BusinessRules application represents all business rules of ACMEDigital, each rule being represented by a SingleRule object. TheBusinessRules’s check() method checks orders by subsequent calls to thecheck() method of each SingleRule.

• SingleRule is an interface. It defines the check() method that takes a POas input, does the check and returns the PO to the caller. The checkmethod may change the PO for two reasons. If the PO does not meet therule it appends a reason description to the status of the PO. A SingleRulelike ACME Digital’s DiscountRule, that applies a certain volume discount,can change other fields of the PO as well (in the case of the DiscountRulethe discount field of the PO is changed).

Purchase Order Applet 167

Page 188: Using VisualAge for Java To Develop Domino Applications

7.9 Interfaces

You need to create two interfaces that are used in the business rules classes.

POChecker InterfaceThe first step when creating an RMI server is defining an interface with themethods that are accessible from the clients.

Select the eTradeVendor project, the acme.rmi package and Selected - Add- Interface to display the Create Interface pane. Create the POCheckerinterface that extends the java.rmi.Remote interface.

A POChecker needs only the check() method, which takes a PO as input,checks, and probably modifies it, and then returns the PO. Select thePOChecker interface and Selected - Add - Method to display the CreateMethod pane. Create the check() method that accepts a PO as input andoutput parameter. The check() method throws a java.rmi.RemoteException asit is called remotely.

PO check(PO order) throws java.rmi.RemoteException

SingleRule InterfaceSelect the eTradeVendor project, the acme package and Selected - Add -Interface to display the Create Interface pane. Create the SingleRuleinterface. The definition of the SingleRule interface is identical to thedefinition of the POChecker class with the exception that it doesn’t need toextend any interface.

To separate the business rules from the RMI server (business rules don’thave to know anything about RMI) you create all classes related to the actualbusiness rules in the acme package, which contains your back-end classes.

7.10 BusinessRules Class

The BusinessRules class represents a set of business rules that are to bechecked against a PO. It holds a vector of single rules. Its check() methodclears the statusText field of the passed PO and delegates the actualchecking to the check() method of the rules it contains.

BusinessRules ClassSelect the eTradeVendor project and the acme package. Create theBusinessRules class. Make sure that you import the packages acme.po,java.rmi, and java.rmi.server.

168 Using VisualAge for Java to Develop Domino Applications

Page 189: Using VisualAge for Java To Develop Domino Applications

FieldsThe BusinessRules class uses a vector of single rules that are to be checked.Create the rules private field of the java.util.Vector type. Do not create getterand setter methods as you don’t need them.

ConstructorThe constructor initializes the rules field. Usually you want to add single rulesat this time, so that a new instance of BusinessRules always contains thestandard set of business rules you have. ACME Digital has just one businessrule called the DiscountRule. Add a new DiscountRule to the rules at thispoint. This will cause an error, because we didn’t define the DiscountRuleclass yet. You fix that error when you create the DiscountRule class later.

public BusinessRules(){rules=new java.util.Vector();rules.addElement(new DiscountRule());

}

check() MethodThe check() method of the BusinessRules class has to:

• Clear the statusText field of the passed PO.

• Pass the PO to the check() methods of each contained business rule tohave it checked.

public PO check (PO order){order.setStatusText("");for (int count=0;count<rules.size();count++){

order=((SingleRule)rules.elementAt(count)).check(order);}return order;

}

7.11 BusinessRulesServer Class

The BusinessRulesServer application serves the RMI requests to check aPO. As it is a Java application it has to have a main() method, which is theentrypoint for its execution.

BusinessRulesServer ClassAs you are implementing an RMI server application the BusinessRulesServerclass has to extend the class java.rmi.server.UnicastRemoteObject.

Select the eTradeVendor project and the acme.rmi package. Create theBusinessRulesServer class that extend the UnicastRemoteObject class in the

Purchase Order Applet 169

Page 190: Using VisualAge for Java To Develop Domino Applications

java.rmi.server package. Make sure that you import the packages acme.po,java.rmi, and java.rmi.server.

This class implements the acme.po.rmi.POChecker interface as you arecreating a POChecker. You are creating an application, so make sure that themain(String[]) checkbox is checked.

FieldsThe BusinessRulesServer class holds a field that represents the set of rulesto be checked. Create the ruleset private field of the acme.BusinessRulestype. Do not create getter and setter methods as nobody outside has toaccess this field. Define a constant String called SERVER and initialize it withyour server’s IP address.

ConstructorThe constructor creates a new BusinessRules object and stores it in theruleset field.

public BusinessRulesServer() throws RemoteException {super();ruleset = new acme.BusinessRules();

}

main() MethodThe BusinessRulesServer application creates an new instance of itself andregisters it with the RMI registry when it starts. Client applications can obtain,from the RMI registry, a reference to the BusinessRulesServer object andinvoke methods on it.

public static void main(java.lang.String[] args) {if (System.getSecurityManager() == null) {

System.setSecurityManager(new RMISecurityManager());}String name = "//"+SERVER+"/POChecker";try {

BusinessRulesServer rulesserver = new BusinessRulesServer();Naming.rebind(name, ruleserver);System.out.println("Business Rules bound");

} catch (Exception e) {System.err.println("Business Rules exception: " + e.getMessage());e.printStackTrace();

}}

The Naming.rebind() method registers the object to the RMI registry. It hastwo parameters:

170 Using VisualAge for Java to Develop Domino Applications

Page 191: Using VisualAge for Java To Develop Domino Applications

• A string that contains the address of the server that is running the RMIregistry and the name that is used for a lookup on the registry by clients.

• An instance of a RemoteUnicastObject object associated with the nameyou entered with the first parameter.

An exception may be thrown by the rebind method in case of any networkproblems.

check() MethodThe check() method returns the result of a call to the ruleset’s check()method.

public PO check(PO order) throws java.rmi.RemoteException {return ruleset.check(order);

}

7.12 DiscountRule Class

In our sample we only implemented the discount rule. The discount ruleapplies a volume discount depending on the total amount of the order.

The DiscountRule class holds two static arrays with the limits for the totalamount over which a certain discount applies and the discount percentagesthemselves. The check() method calls the getSubtotal() method of the passedPO and sets the PO’s discount field to the applicable discount.

DiscountRuleClassSelect the eTradeVendor project and the acme package. Create theDiscountRule class that implements the SingleRule interface and import theacme.po package.

FieldsAdd the fields listed in Table 8 on page 171.

Table 8. DiscountRule Class Fields

The limit array holds the limits in $. The percentage given in the discountsfield with the same index, applies.

Field Name Type Modifiers Initial Value

limits double[] private static {100,500,1000}

discounts double[] private static {5.0,10.0,20.0}

Purchase Order Applet 171

Page 192: Using VisualAge for Java To Develop Domino Applications

check() MethodThe DiscountRule class has only the check() method defined in theSingleRule interface that checks which discount percentage applies for thepassed PO and sets the discount field to the correct percentage.

public PO check (PO order) {if(order.getTotal()<limits[0]){

order.setDiscount(0.0);return order;

}for (int count=0;count<limits.length-1;count++){

if(order.getTotal()<limits[count+1]){order.setDiscount(discounts[count]);return order;

}}order.setDiscount(discounts[discounts.length-1]);return order;

}

7.13 POApplet Class

In this section you put the parts together to get the POApplet working. Most ofthe functions we need for the POApplet are done by delegating the tasks toclasses we implemented in the section above.

POApplet ClassIn the eTradeVendor project, select the acme.po.gui package and Selected -Add - Class. The Create Class pane is displayed. Select Create a new classand enter POApplet as the classname. The POApplet applet extendsAppletBase (refer to “Writing the Applet” on page 51 for more information). Itimplements the java.awt.event.ActionListener interface. As the applet refersto many classes defined in the application, include the following packages:acme.po, acme, and acme.rmi. It also requires classes defined in thejava.awt, java.awt.event, and java.rmi packages.

172 Using VisualAge for Java to Develop Domino Applications

Page 193: Using VisualAge for Java To Develop Domino Applications

FieldsAdd the fields listed in Table 9 on page 173. SERVER is a string containingthe IP address of the server. SEPARATOR is a separator for the Dominomultivalue fields.

Table 9. POApplet Class Fields

MethodsThe POApplet applet uses the notesAppletInit() method. In addition it hasmethods to get the ordered items and quantities, add an item to the PO,refresh the display, private helpers to initialize the PO and the GUI and amethod to react on button clicks.

Create the additional methods first because you need some of them in thenotesAppletInit().

getItemsOrdered() MethodThe getItemsOrdered() method gets a POItem’s vector from the PO’sgetItemList() method. Then it constructs a string that includes the product IDsof all items separated by semicolons.

Variable Name Type

SERVER java.lang.String

SEPARATOR java.lang.String

items acme.po.PO

catalog acme.Catalog

businessrules acme.rmi.POChecker

input acme.po.gui.AddDialog

listheader java.awt.Label

itemList java.awt.List

subTotal java.awt.TextField

discount java.awt.TextField

total java.awt.TextField

statusText java.awt.TextField

addButton java.awt.Button

deleteButton java.awt.Button

layoutconstraints java.awt.GridBagConstraints

Purchase Order Applet 173

Page 194: Using VisualAge for Java To Develop Domino Applications

public String getItemsOrdered() {// CREATE STRINGBUFFER TO CONSTRUCT OUTPUTStringBuffer output = new StringBuffer();// GET ITEMLIST FROM POVector it = items.getItemlist();if (it.size() != 0) {

//ADD FIRST PRODUCTIDoutput.append(((POItem) it.elementAt(0)).getProductID());for (int count = 1; count < it.size(); count++) {

// ADD "; PRODUCTID" FOR ALL FURTHER ITEMSoutput.append("; ");output.append(((POItem) it.elementAt(count)).getProductID());

}}// RETURN OUTPUTreturn output.toString();

}

getQuantitiesOrdered() MethodThe getQuantitiesOrdered() method does exactly the same asgetItemsOrdered(), but its output also contains a string of quantities.

public String getQuantitiesOrdered() {// CREATE STRINGBUFFER TO CONSTRUCT OUTPUTStringBuffer output = new StringBuffer();// GET ITEMLIST FROM POVector it = items.getItemlist();if (it.size() != 0) {

//ADD FIRST QUANTITYoutput.append(((POItem) it.elementAt(0)).getQuantity());for (int count = 1; count < it.size(); count++) {

// ADD "; QUANTITY" FOR ALL FURTHER ITEMSoutput.append("; ");output.append(((POItem) it.elementAt(count)).getQuantity());

}}return output.toString();

}

174 Using VisualAge for Java to Develop Domino Applications

Page 195: Using VisualAge for Java To Develop Domino Applications

addItem() MethodThe addItem() method is called from the initList method.

public void addItem(String productID, double quantity) {try {

// CREATE NEW POITEM WITH GIVEN ID AND QUANTITYPOItem item = catalog.getItem(productID, quantity);// ADD ITEM TO DISPLAYitemList.add(item.toString());// ADD ITEM TO POitems.addItem(item);// CHECK BUSINESSRULESitems = businessrules.check(items);// HIDE ADDDIALOGinput.dispose();

} catch (NotesException ne) {System.out.println(ne.text);ne.printStackTrace();input.invalidData(ne.text, productID, quantity);input.show();

} catch (RemoteException re) {System.out.println("error occurred during checking of busines

rules"+re);re.printStackTrace();

} catch (Exception re) {System.out.println("error occurred when creating new Item"+re);re.printStackTrace();

}}

validate() MethodThe validate() method is used to refresh the screen output. Usually you don’thave to overwrite the validate() method, as it validates all includedcomponents. The validate() method refreshes the subtotal, discount and totaldisplay fields by setting them to the values included in the PO and calls thevalidate() method of the superclass to repaint all components.

public void validate() {// RECOMPUTE SUBTOTAL DISCOUNT AND TOTALsubTotal.setText(POItem.align(items.getSubtotal(), 2, 10));discount.setText(POItem.align(items.getDiscount(), 2, 5));total.setText(POItem.align(items.getTotal(), 2, 10));statusText.setText(items.getStatusText());// REFRESH DISPLAYsuper.validate();

}

Purchase Order Applet 175

Page 196: Using VisualAge for Java To Develop Domino Applications

initList() MethodThe initList() method is a private helper that initializes the PO and the displaylist with the values provided in the applet parameters itemsOrdered andquantitiesOrdered. The method parses the parameter values (single valuesare separated by the SEPARATOR string) and calls the addItem() method.

private void initList() {// APPLET PARAMETERS ITEMSORDERED AND QUANTITIES PROVIDED INIT LISTif (getParameter("itemsOrdered") != null &&

getParameter("quantitiesOrdered") != null) {// CREATE STRINGTOKENIZER TO PARSE PRODUCTIDSStringTokenizer it = new StringTokenizer(

getParameter("itemsOrdered"),SEPARATOR);// CREATE STRINGTOKENIZER TO PARSE QUANTITIESStringTokenizer q = new StringTokenizer(

getParameter("quantitiesOrdered"),SEPARATOR);// FOR EACH PRODUCTID DOwhile (it.hasMoreTokens() && q.hasMoreTokens()) {

// GET NEXT PRODUCTIDString ittok = it.nextToken();// GET NEXT QUANTITYString qtok = q.nextToken();// CREATE NEW ITEM AND ADD IT TO POaddItem(ittok.trim(),

Double.valueOf(qtok.trim()).doubleValue());}

}}

actionPerformed() MethodThe actionPerformed() method is called every time an ActionEvent occurs ona Component you registered as an ActionListener. The ActionEvent that ispassed to the actionPerformed() method includes the source of the event, soyou know which button was clicked. You have to distinguish if the target wasthe addButton or the deleteButton. In case of the addButton you have to bringup the addDialog and show the catalog view of eTrade.nsf in another browserwindow. In the case of the deleteButton, you have to delete the selected itemfrom the PO and the itemList, and then check the business rules again.

public void actionPerformed(ActionEvent ae) {// GET EVENT SOURCEObject source = ae.getSource();// ADD BUTTON CLICKEDif (source.equals(addButton)) {

// SHOW CATALOG VIEW IF NOT ALREADY SHOWNtry {getAppletContext().showDocument(

176 Using VisualAge for Java to Develop Domino Applications

Page 197: Using VisualAge for Java To Develop Domino Applications

new java.net.URL( "http://"+SERVER+"/eTradeVe.nsf/Catalog"),"Product Catalog");

} catch (java.net.MalformedURLException mfURL) {SYstem.out.println("URL error" + mfURL) ;

}// CLEAR ADDDIALOG AND SHOW ITinput.clear();input.show();

}// DELETE BUTTON CLICKED AND ITEM SELECTEDif(source.equals(deleteButton)&&(itemList.getSelectedIndex()!= -1)){

// GET SELECTIONint index = itemList.getSelectedIndex();// REMOVE SELECTED ITEM FROM POitems.getItemlist().removeElementAt(index);// REMOVE SELECTED ITEM FROM DISPLAYitemList.remove(index);// CHECK BUSINESSRULES AGAINtry {

items = businessrules.check(items);} catch (RemoteException re) {

System.out.println("error when checking busines rules");re.printStackTrace();

}// REFRESH DISPLAYvalidate();

}}

createGUI() MethodThe createGUI() method creates and lays out all GUI components. It createsthe connections for the Add and Delete button events registeringActionListener.

In “AddDialog Class” on page 160, the GUI is created using VisualAge forJava Visual Composition Editor. In this section we create the layout manuallyto show you an alternative to the Visual Composition Editor.

The createGUI() method uses the JDK GridBagLayout layout manager tocreate the interface (see Appendix B, “JDK Layout Managers” on page 267 formore information).

The createGUI() method initializes the input and the other GUI components.

The createGUI() method then lays out the components using theGridBagLayout layout manager. It first sets the layout constant values and

Purchase Order Applet 177

Page 198: Using VisualAge for Java To Develop Domino Applications

uses the add() method to add components to the layout. For example, theitemList component has the following layout constraints:

• itemList uses the whole width of the POApplet.

layoutconstraints.gridwidth=GridBagConstraints.REMAINDER;

• itemList is placed on the second line.

layoutconstraints.gridy=1;

• itemList fills the horizontal space it is given in proportion tolayoutconstraints.weightx.

layoutconstraints.fill=GridBagConstraints.HORIZONTAL;

• itemList uses all the horizontal space it is given.

layoutconstraints.weightx= 1.0;

These constraints are then added to the POApplet.

• itemList is rendered as described in the layout constraints.

add(itemList,layoutconstraints) ;

Finally, the createGUI() method registers the POApplet as ActionListener forthe add and delete buttons using the Button’s addActionListener() methodand refreshes the display:

public void createGUI() {// CREATE ADDDIALOGinput = new AddDialog(this);// CREATE GUI COMPONENTSlistheader = new Label("ID Product Name Price

Min. Quantity Total");listheader.setFont(new Font("Monospaced", Font.PLAIN, 12));addButton = new Button("Add Item");deleteButton = new Button("Delete Item");// INIT DISPLAYED LISTitemList = new List(5);itemList.setSize(new Dimension(500, 150));// DISABLE MULTISELECTIONitemList.setMultipleMode(false);itemList.setFont(new Font("Monospaced", Font.PLAIN, 12));subTotal = new TextField(10);subTotal.setFont(new Font("Monospaced", Font.PLAIN, 12));subTotal.setEditable(false);discount = new TextField(5);discount.setEditable(false);discount.setFont(new Font("Monospaced", Font.PLAIN, 12));total = new TextField(10);

178 Using VisualAge for Java to Develop Domino Applications

Page 199: Using VisualAge for Java To Develop Domino Applications

total.setEditable(false);total.setFont(new Font("Monospaced", Font.PLAIN, 12));statusText = new TextField(70);statusText.setEditable(false);statusText.setFont(new Font("Monospaced", Font.PLAIN, 12));// INITIALIZE LAYOUTCONSTRAINTSlayoutconstraints = new GridBagConstraints();// INITIALIZE LAYOUTsetLayout(new GridBagLayout());// ADD LIST HEADERlayoutconstraints.gridy = 0;layoutconstraints.gridwidth = GridBagConstraints.REMAINDER;add(listheader, layoutconstraints);// ADD ITEMLISTlayoutconstraints.gridy = 1;layoutconstraints.fill = GridBagConstraints.HORIZONTAL;layoutconstraints.weightx = 1.0;add(itemList, layoutconstraints);// ADD SUBTOTALlayoutconstraints.gridy = 11;layoutconstraints.gridx=1;layoutconstraints.fill = GridBagConstraints.NONE;layoutconstraints.anchor = GridBagConstraints.EAST;add(subTotal, layoutconstraints);// ADD DISCOUNTlayoutconstraints.gridy = 12;add(discount, layoutconstraints);// ADD TOTALlayoutconstraints.gridy = 13;add(total, layoutconstraints);// ADD ADD BUTTONlayoutconstraints.gridy = 12;layoutconstraints.gridx=0;layoutconstraints.anchor = GridBagConstraints.WEST;add(addButton, layoutconstraints);// ADD DELETE BUTTONlayoutconstraints.gridy = 13;add(deleteButton, layoutconstraints);// ADD STATUSTEXTlayoutconstraints.gridy = 14;layoutconstraints.gridwidth = GridBagConstraints.REMAINDER;layoutconstraints.fill = GridBagConstraints.HORIZONTAL;layoutconstraints.weightx = 1.0;add(statusText, layoutconstraints);// ADD ACTIONLISTENERaddButton.addActionListener(this);deleteButton.addActionListener(this);

Purchase Order Applet 179

Page 200: Using VisualAge for Java To Develop Domino Applications

}

notesAppletInit() MethodThe notesAppletInit() method is called from the AppletBase’s init() method.The notesAppletInit() method creates a session and accesses the Dominodatabase. It initializes the fields, the catalog and the business rules. It looksup the RMI registry (see “BusinessRules Client” on page 181). It calls thecreateGUI() method to create and lay out the GUI components, initializes theitemlist and refreshes the display.

public void notesAppletInit() {// INIT SESSIONtry {

Session s = this.openSession() ;if (s==null) {

System.out.println("Unable to create a session with Domino");return;

}Database cat = s.getDatabase("", "eTradeVe.nsf");// CREATE CATALOGcatalog = new Catalog(cat);// CREATE EMPTY PO FOR CUSTOMER NAME PASSED IN PARAMETER BUYERSNAMEitems = new PO(getParameter("buyersName"));

} catch (Exception e) {System.out.println("catalog not instantiated\n" + e);

}// CONNECT TO BUSINESSRULESif (System.getSecurityManager() == null) {

System.setSecurityManager(new RMISecurityManager());}try {

String name = "//"+SERVER+"/POChecker";businessrules = (POChecker) Naming.lookup(name);

} catch (Exception e) {System.err.println("Business Rules Server not reachable: " +

e.getMessage());e.printStackTrace();

}// CREATE GUIcreateGUI();// INITIALIZE ITEMLISTinitList();// REFRESH DISPLAYvalidate();

}

180 Using VisualAge for Java to Develop Domino Applications

Page 201: Using VisualAge for Java To Develop Domino Applications

7.14 BusinessRules Client

The POApplet class is the client of the BusinessRulesServer application. Itsimplementation is described in 7.13, “POApplet Class” on page 172. In thissection we explain the special tasks that an RMI client has to perform toconnect to a server application.

All types used as parameters for remote method calls must be serializable asremote call parameters are serialized for transfer over the network.

In the eTrade Vendor application only the BusinessRulesServer’s check()method is used remotely. Therefore, PO and POItem (since it is a part of aPO) have to be defined as serializable. Modify the declaration of both classesby adding implements java.io.Serializable.

public class PO implements java.io.Serializablepublic class POItem implement java.io.Serializable

To get a reference to a remote object you have to do a lookup with the RMIregistry. The lookup is done by the static lookup method of the classjava.rmi.Naming. This method requires a security manager to be installedfirst.

As the POApplet class requires a connection to the RMI server, add thefollowing lines in the notesAppletInit() method:

if (System.getSecurityManager() == null) {System.setSecurityManager(new RMISecurityManager());

}try {String name = "//"+SERVER+"/POChecker";POChecker businessrules = (POChecker) Naming.lookup(name);} catch (Exception e) {System.err.println("Business Rules Server not reachable: " +

e.getMessage());e.printStackTrace();}

7.15 Testing the POApplet

When all the required classes have been created, you can test the POAppletapplet.

Run the first test of the applet within VisualAge for Java, in order to use thedebugger and its powerful features. You have to set up and start

Purchase Order Applet 181

Page 202: Using VisualAge for Java To Develop Domino Applications

• Domino Server

• RMI and the business rules server

• Applet

7.15.1 Domino Server SetupDomino has to be set up to support IIOP access as the POApplet applet usesCORBA to access Domino objects. To set up security for IIOP, using DominoAdministrator, open the server document and select the Security tab (seeFigure 83 on page 182).

In the IIOP Restrictions section, set Who can Run unrestrictedJava/Javascript field to * as you don’t want to be restricted during the testperiod. The Domino administrator may set a more realistic value when theapplication is in production.

Figure 83. Server Document: Security

7.15.2 RMI and the Business Rules ServerTo set up RMI and the business rules server:

• Set the IP address of the server.

• Generate RMI stub and skeleton.

182 Using VisualAge for Java to Develop Domino Applications

Page 203: Using VisualAge for Java To Develop Domino Applications

• Set the workspace classpath.

• Start the RMI registry.

• Start the business rules server.

Server AddressMake sure that you set the correct server address in the eTrade Vendorapplication code. In the classes acme.rmi.BusinessRulesServer andacme.po.gui.POApplet, set the SERVER variable to the IP address of yourserver machine. The address has to be entered in exactly the same way asthe address you access your Domino server with.

RMI stub and skeletonTo allow the client to access the server classes (see “Remote MethodInvocation” on page 21 for more information), you need to create the stub andskeleton for the BusinessRulesServer class.

In the eTradeVendor project, select the acme.rmi package, theBusinessRulesServer class and Selected - Tools - RMI Generate Stub andSkeleton.

This operation creates two new classes:

BusinessRulesServer_SkelBusinessRulesServer_Stub

RMI Registry and ClassesThe BusinessRulesServer class requires the following classes to run:

• POItem• PO• BusinessRules• BusinessRulesServer• BusinessRulesServer_Stub• BusinessRulesServer_Skel• SingleRule• POChecker• DiscountRule

The RMI registry has to find them when starting the BusinessRulesServer.

Export the classes to a directory or jar file and add that directory or jar file toyour workspace classpath. In VisualAge for Java, select Window - Options -Resources and add the classpath in the field.

Purchase Order Applet 183

Page 204: Using VisualAge for Java To Develop Domino Applications

If your server is not your local machine you have to provide the classes in theclasspath of the server machine.

Start the RMI RegistryBefore you can start the BusinesRulesServer you have to start the RMIregistry on the server machine.

If the server is the development machine, in VisualAge for Java, selectWindow - Options - RMI Registry to display the RMI registry pane (seeFigure 84 on page 184). Click the Restart RMI Registry button.

Figure 84. RMI Registry Pane

If the server is not the development machine, type the following command ina Command Prompt window:

rmiregistry

The RMI registry program (rmiregistry.exe) is included in the JDK.

Start the BusinessRulesServerYou have to start the BusinessRulesServer.

If the server is the development machine, in VisualAge for Java, select theeTradeVendor project, the acme.rmi package, the BusinessRulesServer classand Selected - Run - Run main.

If your server is not the development machine, type the following command ina Command Prompt window:

java acme.rmi.BusinessRulesServer

The Java interpreter (java.exe) is included in the JDK.

184 Using VisualAge for Java to Develop Domino Applications

Page 205: Using VisualAge for Java To Develop Domino Applications

Your console should include the line BusinessRules bound after starting theBusinessRulesServer.

7.15.3 ParametersAs you are testing the applet using VisualAge for Java, you need to providethe applet’s parameters manually. When the applet is installed in Domino,parameters are passed by the form (see “Installing Applets In Domino” onpage 52).

Applet ParametersThe needed parameters are itemsOrdered and quantitiesOrdered. TheitemsOrdered parameter is a string that holds the initial productID’sseparated by commas. The quantitiesOrdered parameter is a string thatcontains the quantities of the products for the initial itemlist.

In the eTradeVendor project, select the acme.po.gui package, the POAppletclass and Selected - Properties to display the Properties pane for thePOApplet applet. Select the Applet tab (see Figure 85 on page 185).

Figure 85. POApplet Properties Pane: Applet Tab

Enter the parameter names and values as shown assuming items 001 and003 exist in the eTrade Vendor application and customer Customer isdeclared in the Domino directory:

Purchase Order Applet 185

Page 206: Using VisualAge for Java To Develop Domino Applications

<param name=quantitiesOrdered value="123.0, 321.0"><param name=itemsOrdered value="001, 003"><param name=buyersName value="Customer/Almaden">

CORBA ParametersIn addition to the applet parameters, two additional parameters are used bythe AppletBase class (see “CORBA Applets” on page 55):

• NOI_IOR

The NOI_IOR parameter determines the server on which the session iscreated.

• NOI_COOKIE_URL

The NOI_COOKIE_URL parameter is the location of a cookie that iscreated for the session. It ensures a single user login for the wholeCORBA session. Its value is set by Domino when you include anAppletBase subclass in a form or document.

If the NOI_IOR parameter is omitted, the AppletBase creates a local sessionand not a remote CORBA session, resulting in an error. The value of thisparameter is stored in the diiop_ior.txt file of the Domino server.

If the server is the development machine, copy and paste the content of thediiop_ior.txt file to create the following param command:

<param name=NOI_IOR value="IOR:0100000029..........000000">

If the server is not the development machine, you can obtain the value bycalling the getIOR(server) method of the NotesFactory class where serverstands for the IP address of your Domino Server. In VisualAge for Java, selectWindow - ScrapBook and enter the following instruction:

lotus.domino.NotesFactory.getIOR("your.server.name")

Select the instruction and Edit - Inspect to display the Inspector window (seeFigure 86 on page 187).

186 Using VisualAge for Java to Develop Domino Applications

Page 207: Using VisualAge for Java To Develop Domino Applications

Figure 86. Inspector Pane

The Value pane contains the value for the NOI_IOR variable. Copy and pastethe value to create the following param command:

<param name=NOI_IOR value="IOR:0100000029..........000000">

Running the POAppletYou are ready to run the applet. In the eTradeVendor project, select theacme.po.gui package, the POApplet class and Selected - Run - In AppletViewer to display the POApplet applet in the VisualAge for Java AppletViewer (see Figure 87 on page 187).

Figure 87. Applet Viewer: POApplet

Purchase Order Applet 187

Page 208: Using VisualAge for Java To Develop Domino Applications

7.16 Debugging the POApplet

One of the main reasons to use VisualAge for Java to develop Javaapplications is the power of the built-in debugger. In this section we highlightthe most common features.

Figure 88 on page 189 shows the Debugger’s panes open for a POAppletapplet:

• All Programs/Threads pane

It shows all currently running threads. In this case, it includes theBusinessRulesServer thread, the POApplet threads and the RMI registrythread. The selected thread runs the code containing the validate()method at the breakpoint.

• Visible Variables pane

It contains all visible variables of the thread selected in the AllPrograms/Threads pane.

• Value pane

It contains the value of the variable selected in the Visible Variables pane.

• Source pane

It contains the source code of the method the selected thread is currentlyexecuting (if available).

188 Using VisualAge for Java to Develop Domino Applications

Page 209: Using VisualAge for Java To Develop Domino Applications

Figure 88. Debugger Panes

Adding BreakpointsTo check that a program performs correctly, you can inspect the values of theattributes at different point of their execution. Using VisualAge for Java, youcan set breakpoints in the source code, assuming the code is saved and errorfree.

You can set breakpoints only on instructions, not on all statements of yourcode. For example you cannot set breakpoints:

• In class declarations

• In inner classes

• On try or catch statements

• On else or case statements

• On comments

ResumeStep Into Step Over Run to Return Caught Exceptions

Purchase Order Applet 189

Page 210: Using VisualAge for Java To Develop Domino Applications

VisualAge for Java offers you three ways to set breakpoints:

• Position the cursor within the line where you want to set the breakpoint.Click on the right mouse button and select Breakpoint.

• Position the cursor within the line where you want to set the breakpoint.Select Breakpoint from the Edit menu.

• Click with the right mouse button on the left margin next to the line whereyou want to set your breakpoint. Select Add from the context menu.

• Double-click on the left margin next to the line where you want to set yourbreakpoint.

In the eTradeVendor project, select the acme.po.gui package, the POAppletclass, and the notesAppletInit() method to display the source (see Figure 89on page 190). In the source pane, click on the left margin next to thevalidate() method. Select Add from the context menu.

Figure 89. Setting a Breakpoint

Run the applet. In the eTradeVendor project, select the acme.po.gui package,the POApplet class and Selected - Run - In Applet Viewer. When theexecution of the program hits the breakpoint the Debugger shows up.

190 Using VisualAge for Java to Develop Domino Applications

Page 211: Using VisualAge for Java To Develop Domino Applications

Examining Field ValuesThe Visible Variables pane displays all the variables that can be examined.Select the variable you want to inspect from the Visible Variables pane and itsvalue—precisely, the return value of its toString() method— is displayed inthe Value pane.

If a variable contains a type that holds multiple attributes you can expand thevariable by clicking on the + sign next to it. You can expand the variables untilyou reach basic types. In Figure 88 on page 189 the POApplet, the includedPO items and the Vector of POItems are expanded to display the first POItem.

Evaluating ExpressionsThe debugger allows you to inspect any Java expression during debugging.This evaluation can be used to check an if-statement’s condition or tounderstand why an expression evaluates to an unexpected value.

To inspect the result of an expression, highlight it, click on the right mousebutton and select Inspect. You can also inspect a highlighted expressionusing Inspect from the Inspect menu of the debugger. The expression youwant to inspect doesn’t necessarily have to be in your code. You can enterany expression you like in any part of the debugger’s Source pane andinspect it like it was included in your code.

Stepping through the CodeVisualAge for Java offers different possibilities to step through the code at abreakpoint. The buttons used for this are located underneath the menu bar(see Figure 88 on page 189).

• You can resume the execution of your program at any time by clicking onthe Resume button.

• You can step through the execution of each statement of your code byclicking on the Step Into button. Doing this enters every method your codecalls, enabling you to debug every statement executed by your code.

• You can step through the code of the method you are actually debuggingby clicking on the Step Over button. The debugger stays in the methodyou are actually debugging without stepping through the methods calledfrom your code. Doing this enables you to debug the code of a methodafter the execution of each statement.

• You can step to the end of a method by clicking on the Run To Returnbutton. The debugger stops at the execution of the return statement of themethod.

Purchase Order Applet 191

Page 212: Using VisualAge for Java To Develop Domino Applications

• You can step to the actual cursor position by selecting Run To Cursorfrom the Selected menu. The debugger runs to the line of the actualcursor position.

Modifying BreakpointsVisualAge for Java Version 2 allows you to modify breakpoints in two ways:

• Set a condition for the breakpoint. The execution of your program will stopat the breakpoint only if the condition is true. The standard condition forbreakpoints is the constant true.

• You can add any number of instructions to be executed whenever thebreakpoint is reached.

Also a combination of these two concepts is possible.

To modify a breakpoint without actually stopping the execution of thedebugging session, click on the blue mark next to the breakpoint with the rightmouse button and select Modify to display the Configuring Breakpoint pane(see Figure 90 on page 192).

Figure 90. Configuring Breakpoint Pane

In this pane, you can modify or create a new breakpoint condition by addingJava code. Any variables accessible from the actual context can be used inthe code. After the code you have to specify a condition for the breakpoint.Here we deliver false, which causes the debugger not to stop at thisbreakpoint.

If you restart the POApplet and look at the console, you can see the initial listof POItems separated by commas, output produced by the Vectors toString()method.

192 Using VisualAge for Java to Develop Domino Applications

Page 213: Using VisualAge for Java To Develop Domino Applications

Reacting to ExceptionsVisualAge for Java can react on exception. For example, VisualAge for Javacan react to unexpected exceptions for which no catch statements have beenprogrammed.

To specify the class of the exception on which you want the debugger to beopened, click on the Caught Exceptions button. Select the exceptions youwant to be caught by the debugger and click on OK. From now on everyprogram throwing the specified exception will be opened in the debugger.

7.17 Importing the POApplet in Domino

When the POApplet is working properly, you can include it in thePurchaseOrder form. You have to:

• Export the applet files from VisualAge for Java.

• Include the applet in the Domino EditItemList subform.

• Set the applet’s properties.

• Define the applet’s parameters.

• Hide parameters’ fields.

• Use JavaScript to transfer data between the applet and the form.

• Test the form.

7.17.1 Export the AppletYou have to export the applet files from VisualAge for Java. To keep networktraffic as low as possible export only the required classes needed for thePOApplet in a jar file. These are:

• POApplet

• AddDialog

• POItem

• PO

• Catalog

• BusinessRulesServer_Stub

• BusinessRulesServer_Skel

• POChecker

Purchase Order Applet 193

Page 214: Using VisualAge for Java To Develop Domino Applications

In VisualAge for Java, select File - Export to display the Export SmartGuide.Select jar file and click on Next. Enter the location and name for the jar file(c:\classes\POApplet.jar).

Check .class and Details to display the .class export pane (see Figure 91 onpage 194.

Figure 91. Class Export Pane

Select the eTradeVendor project in the Project column and select thecomponents to be exported in the Types column. Click OK.

Check the Compress the contents of the jar file checkbox and click Finishto create the jar file.

7.17.2 Include the Applet in the Domino ComponentYou are ready to include the applet in a Domino component. You created theEditItemList subform—used in the PurchaseOrder form—to contain the applet(see “EditItemList Subform” on page 138).

Importing the AppletUsing Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Subforms in theresources list to open the Design - Subform view. Open the EditItemListsubform.

Position the cursor at the end of the subform. Choose Create - Java Appletfrom the menu bar to display the Create Java Applet pane (see Figure 92 onpage 195).

194 Using VisualAge for Java to Develop Domino Applications

Page 215: Using VisualAge for Java To Develop Domino Applications

Figure 92. Create Java Applet Pane

Import the POApplet applet giving its class name (acme.po.gui.POApplet)and the base directory where the jar file is located (c:\classes).

To include the applet jar file, click on Locate to display the Locate JavaApplet Files pane (see Figure 93 on page 195).

Figure 93. Locate Java Applet Files Pane

Select the POApplet.jar file in the Available Java Files column and selectAdd/Replace File to import the jar file.

Purchase Order Applet 195

Page 216: Using VisualAge for Java To Develop Domino Applications

7.17.3 Setting the PropertiesUsing Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Subforms in theresources list to open the Design - Subform view. Open the EditItemListsubform.

Select the Java applet and Java Applet - Java Applet Properties to displaythe Java Applet properties box. Set the width to 550 pixels and the height to200 pixels.

Check the Applet uses Notes CORBA classes checkbox to have Dominoinclude the NCSO.jar file and add the NOI_IOR applet parameter to theapplet HTML tag before serving the document to the Web browser (see“CORBA Applets” on page 55).

7.17.4 Defining the Applet ParametersYou have to provide the initial items, quantities, and the buyer’s name asapplet parameters. To set applet parameters, select the Java applet. ClickApplet Parameters in the Info List of the Programmer’s pane (see Figure 94on page 197).

Create the three parameters in Table 10 on page 196 by clicking Add to enterthe parameter name and entering the corresponding value in the ParameterValue window.

Table 10. POApplet Parameters

Parameter Name Parameter Value Remark

itemOrdered @Implode(itemsOrdered;",") The formula passes thevalues of the multivaluedfield in one stringconsisting of thecomma-separated valuesquantitiesOrdered @Implode(quantitiesOrdered;",")

buyersName buyersName

Domino replaces theparameter’s value with thebuyersName field valuewhen it serves thePurchaseOrder form

196 Using VisualAge for Java to Develop Domino Applications

Page 217: Using VisualAge for Java To Develop Domino Applications

Figure 94. Setting Applet Parameters

7.17.5 Hiding the Parameter SourcesThe user should not see the fields used to pass parameters to the applet.

lastOrderID FieldUsing the lastOrderID field properties box, set both Hide paragraph fromNotes R4.6 or later and Hide paragraph from Web browsers properties.

itemsOrdered and quantitiesOrdered FieldsWhen you set the Hide paragraph from Web browsers field property, the fieldis not inserted in the HTML flow of the page. However, the itemsOrdered andquantitiesOrdered fields need to be in the HTML flow as they contain theproductID’s and quantities of the ordered items.

To include a hidden field in an HTML page, use the HTML section of the fieldproperties and enter Type="hidden" as Other HTML tag (see Figure 95 onpage 198).

To prevent Domino from inserting Line breaks after the field, select the fieldand open the Text menu. Make sure that Pass-Thru HTML is checked. Thisprevents Domino from rendering the field.

Purchase Order Applet 197

Page 218: Using VisualAge for Java To Develop Domino Applications

Figure 95. HTML Field Properties Box

7.17.6 JavaScript CodeYou use JavaScript to transfer the item and quantities from the applet to theform.

Using Domino Designer, select the Recent Databases design bookmark. Inthe Design pane of the eTrade Vendor database, select Forms in theresources list to open the Design - Form view. Open the PurchaseOrder form.

Expand PurchaseOrder(Form) in the Object tab of the Info List of theProgrammer’s pane and select JS Header (see Figure 96 on page 199).

The JS Header contains JavaScript methods that can be used throughout theform. Provide the setItems() method to set the itemsOrdered andquantitiesOrdered form fields to the values returned by the get() method ofthe POApplet applet. The setItems() method is used in the Submit button (see“Submit Button” on page 136).

198 Using VisualAge for Java to Develop Domino Applications

Page 219: Using VisualAge for Java To Develop Domino Applications

Figure 96. PurchaseOrder Form: JSHeader

7.17.7 Testing the Purchase Order FormFinally, to test the complete application in a Domino environment, you have to

• Start the RMI registry.

• Start the BusinessRulesServer.

• Access the Order form using a Web browser.

• Access the Order form using a Notes client.

Starting the RMI RegistryThe BusinessRulesServer class requires the following classes to run:

• POItem• PO• BusinessRules• BusinessRulesServer• BusinessRulesServer_Stub• BusinessRulesServer_Skel• SingleRule• POChecker• DiscountRule

The RMI registry has to find them when starting the BusinessRulesServer.

Purchase Order Applet 199

Page 220: Using VisualAge for Java To Develop Domino Applications

Export the classes to a directory or jar file and add that directory or jar file tothe server classpath.

Type the following command in a Command Prompt window of your servermachine:

rmiregistry

The RMI registry program (rmiregistry.exe) is included in the JDK.

Starting the BusinessRulesServerYou have to start the BusinessRulesServer on the server machine.

Type the following command in a Command Prompt window:

java acme.rmi.BusinessRulesServer

The Java interpreter (java.exe) is included in the JDK.

Accessing the Purchase Order Form Using a Web BrowserTo access the purchase order form from a Web browser, point your Webbrowser to the following URL:

HTTP://your.server.name/eTradeVe.nsf/PurchaseOrder

which shows the PurchaseOrder form in Netscape Navigator. The initial list ofitems depends on your previous order.

Accessing the Purchase Order Form Using a Notes ClientIf you try to access the PurchaseOrder form using a Notes client you get anerror message in the status line.

The POApplet applet cannot be started from a Notes client as there are somedifferences in the behavior of the AppletBase class between using a Webbrowser and a Notes client:

• The getSession() method of AppletBase returns a Session on the Dominoserver if you use a Web browser. If you use a Notes client, getSession()always returns a local Session. You can fix this problem by using theisOnServer() method of the Session class and providing the server namein the getDatabase() method depending on the result.

• If you run an applet that extends AppletBase in a Notes client the Sessionis only available in the applet’s main thread. Every use of the Session andthe dependent objects like Databases of the Session from another thread(like the event handling thread) fail.

200 Using VisualAge for Java to Develop Domino Applications

Page 221: Using VisualAge for Java To Develop Domino Applications

Chapter 8. PreparePOforEvaluator Agent

Once customers have submitted purchase orders using the POApplet applet,the PreparePOforEvaluator agent prepares the orders for evaluation. Itobtains customer credit and volume discount information, item prices andupdates the appropriate fields of the order.

In this chapter we explain how to develop a Domino Java agent usingVisualAge for Java. We also explain how to test the agent using DominoAgentRunner.

The PreparePOforEvaluator agent involves multiple areas. It is a Dominoagent that imports a Java class. The class is developed using VisualAge forJava. It involves the Domino AgentRunner to test and debug it. The agentalso needs to connect to the business rules server using RMI to access thecredit check business rules. To avoid overlapping problems in this complexenvironment, you need to address the development and test in a step-by-stepapproach:

1. Create a simple version of the PreparePOforEvaluator class.

2. Create a simple version of the PreparePOforEvaluator agent by importingthe class into the Domino agent. Test and debug the agent.

3. Create a modified version of the PreparePOforEvaluator class thatimplements business rules verification.

4. Implement the credit check rule.

5. Implement RMI to access the business rules server.

6. Install and run the final agent in the production environment.

In the following sections, after giving a design overview, we explain the fullprocess.

8.1 Design Overview

The PreparePOforEvaluator agent requires the following components:

• Prepared POs view

This is a very basic Domino view for selecting POs after the agent hasprocessed them.

• DisplayItemList subform for the PO

This subform allows orders’ evaluators to view the purchase orders withprices, discounts, and totals, along with credit information for the buyer.

© Copyright IBM Corp. 1999 201

Page 222: Using VisualAge for Java To Develop Domino Applications

• PreparePOsForEvaluator Class

We first create a simple class that can process submitted POs to test theintegration of VisualAge for Java with Domino Designer. Then weimplement the actual processing of purchase orders:

• Obtain a list of unprocessed PurchaseOrder documents from theAgentContext.

• Use the POItem and PO classes to create a PO object from eachunprocessed PurchaseOrder document.

• Use the Catalog class to fill in the price for each item.

• Process the PO object using RMI and the check() method.

• Set the prices, discount, and total amount for each item of unprocessedpurchase orders.

Finally we will add credit checking using the check() method of the newSingleRule implementation called CreditRule and a new extension of thePO class called SubmittedPO.

8.2 PreparePOforEvaluator Class

To begin testing the PreparePOforEvaluator agent, you need a basicPreparePOforEvaluator class.

Using VisualAge for Java, select the eTradeVendor project and Selected -Add - Package to add the poAgent package.

Select the new poAgent package and Selected - Add - Class to display theCreate Class pane. Select Create a new class and enterPreparePOforEvaluator that extends lotus.domino.DebugAgentBase. Youdon’t compose the class visually. Make sure that you import the lotus.domino,acme and acme.po packages.

You need to use DebugAgentBase as the superclass in order to be ableto use AgentRunner for debugging. If you are unable to find theDebugAgentBase class in the class browser, or lotus.domino in thepackage browser, make sure that the Domino Java class library R5project exists in your Workspace (see 4.3.1, “Domino Agent Runner” onpage 99 for more information).

DebugAgentBase

202 Using VisualAge for Java to Develop Domino Applications

Page 223: Using VisualAge for Java To Develop Domino Applications

You need to create the NotesMain() method in the PreparePOforEvaluatorclass in order to define the entry point of the Domino agent. In theeTradeVendor project browser window, select the poAgent package, thePreparePOforEvaluator class, and Selected - Add - Method to create thepublic NotesMain() method.

When you click on Finish in the SmartGuide, VisualAge for Java gives youthe following message: "By convention, Java method names usually start witha lowercase letter. The selected name is NotesMain." Choose to proceed asDomino requires the capital letter.

The first version of the NotesMain() method creates a session to the Dominoserver, gets the current agent context, opens the current database, andcreates a collection of unprocessed documents to set their order status.

public NotesMain() {try {

Session session = getSession();AgentContext ac = session.getAgentContext();Database db= ac.getCurrentDatabase();Document doc = null;DocumentCollection dc = ac.getUnprocessedDocuments();if (dc.getCount() > 0) {

for (int i = 1;i <= dc.getCount();i++) {doc = dc.getNthDocument(i);doc.replaceItemValue("orderStatus","set by java agent");ac.updateProcessedDoc(doc);doc.save(true,false);

}}

} catch (NotesException e) {System.err.println("Error, Notes Exception: " + e);

} catch (Exception e) {System.err.println("Error, Exception: " + e);

}}

Export the PreparePOforEvaluator class to a directory (or a jar file) on the filesystem. The exporter creates subfolders to match the package names of theclass. It puts the class file in the last folder. In this example, if you exported tothe c:\wkspace directory, the class is found in the following directory:

c:\wkspace\acme\poAgent\PreparePOforEvaluator.class

PreparePOforEvaluator Agent 203

Page 224: Using VisualAge for Java To Develop Domino Applications

8.3 PreparePOforEvaluator Agent

Once the class file is exported, you are ready to create the Domino agent thatruns the Java class.

Using Domino Designer, select the Recent Databases design bookmark. Inthe Design pane of the eTrade Vendor database, select Agents in the list toopen the Design - Agents view.

Click the New Agent action button to open the work area of the Agent designpane. Create the shared PreparePOforEvaluator agent. The agent needs tobe shared so other users can run it. This agent should run If Documents HaveBeen Created or Modified. Domino server runs the agent when documentschange in the database.

Click on Add Search to display the Search Builder pane and search fordocuments where the orderStatus field contains submitted.

From the Run pull-down list, select Imported Java and click on Import ClassFiles to open the Import Java Files dialog.

Browsing the Local Filing System, set the Base Directory to the directorywhere you exported the class file (c:\wkspace). Expand the subdirectory to

The Agent Manager controls when agents run on a server. Every time anagent runs, it uses server resources. Settings in the Server document andin the notes.ini file control when scheduled and event-triggered agents run.Here are two important settings:

• AMgr_DocUpdateAgent MinInterval

Specifies the minimum elapsed time, in minutes, between the executionof the same document update-triggered agent. Default is 30 minutes. Asmaller interval results in more agent runs and increases serverdemand. Note that even if this variable is set to zero, a built-in delay willalways exist.

• AMgr_DocUpdate EventDelay

Specifies the delay time, in minutes, the Agent Manager schedules adocument update-triggered agent after a document update event.Default is 5 minutes. The delay time ensures the agent runs no moreoften than the specified interval, regardless of how frequently documentupdate events occur.

Domino Agent Manager

204 Using VisualAge for Java to Develop Domino Applications

Page 225: Using VisualAge for Java To Develop Domino Applications

select the class and click the Add/Replace File(s) button. Set the Base classto the full class name:

acme\poAgent\PreparePOforEvaluator.class

The Base class can be specified either with backslashes or dots. However,you need to specify an accurate reference to the class of your agent (seeFigure 97 on page 205).

Figure 97. Import Java Files dialog

Figure 98 on page 206 shows the Agent design pane.

PreparePOforEvaluator Agent 205

Page 226: Using VisualAge for Java To Develop Domino Applications

Figure 98. Agent Design Pane

You can save the PreparePOforEvaluator agent.

Simulating the Running of the AgentYou can simulate a run of the PreparePOforEvaluator agent by using the Testfunction.

In the design pane of the eTrade Vendor database, select Agents in the list toopen the Design - Agents view. Then select the PreparePOforEvaluator agentand choose Action - Test.. The Test Run Agent Log opens, telling you whatwould happen if the agent ran (see Figure 99 on page 207).

206 Using VisualAge for Java to Develop Domino Applications

Page 227: Using VisualAge for Java To Develop Domino Applications

Figure 99. Test Run Agent Log

If the log indicates that no documents matched the search criteria, you needto create some more PurchaseOrder documents.

8.4 Testing and Debugging the Agent

Once the first version of the class is correctly imported into the Domino agent,you are ready to verify the installation of the Domino AgentRunner inVisualAge for Java.

AgentRunner SetupAs you are developing and testing a Domino agent with VisualAge for Java,you have to install and set up the Domino AgentRunner. Refer to 4.3.1,“Domino Agent Runner” on page 99 for the instructions.

AgentContext DocumentYou have to generate an AgentContext document in the AgentRunnerdatabase (agentrunner.nsf). The AgentRunner code accesses theAgentContext document to make Java behave as though it were running as aDomino agent when it is running in VisualAge for Java.

Make sure that you have authority to run shared agents on your server.

In the design pane of the eTrade Vendor database, select Agents in the list toopen the Design - Agents view and select the PreparePOforEvaluator agentand choose Action - Run. The Agent Log opens and displays the result of therun (see Figure 100 on page 208).

PreparePOforEvaluator Agent 207

Page 228: Using VisualAge for Java To Develop Domino Applications

Figure 100. Agent Log

The messages in the log file tell you only part of the story, though. In fact, theJava code could fail completely and you would not be able to tell from themessages. To ensure that the Java code ran successfully you need to checkthe Java console. Select File - Tools - Show Java Debug Console to openthe Java Console window. If the agent context document was createdsuccessfully, the Java console displays the following message:

AgentContext dumped to file AgentRunner.nsf

Using Notes client, select the Databases bookmark and open the JavaAgentRunner database on the local Notes database directory. TheAgentContext view displays an entry for the PreparePOforEvaluator agent(see Figure 101 on page 208).

Figure 101. AgentContext View

As the PreparePOforEvaluator class extends DebugAgentBase, the call togetSession(), after generating an AgentContext document, returns null. Anyuse of the returned session results in a thrown exception, but since the

208 Using VisualAge for Java to Develop Domino Applications

Page 229: Using VisualAge for Java To Develop Domino Applications

purpose of running the agent is only to generate the context document (andnot to run any of the agent code), you can ignore the exception.

You are ready to debug the agent. Using VisualAge for Java, select theeTradeVendor project, the poAgent package, the PreparePOforEvaluatorclass and open the NotesMain() method to set a breakpoint at the firstinstruction (getSession()).

Select the PreparePOforEvaluator class and Selected - Tools -DominoAgentRunner - Properties to display the Domino AgentRunnerproperties pane (see Figure 102 on page 209). You can update the agentcontext or run the agent.

Figure 102. AgentRunner Properties

Select the PreparePOforEvaluator class and Selected - Tools -DominoAgentRunner - Run to run the agent. After initialization, the Debugwindow opens showing the class execution stopped at your breakpoint. Asyou step through the code to the line which creates the AgentContext, you areprompted to enter a password. Enter your Notes password.

From this point you have full access to the Debugger facilities—examiningfield values, evaluating expressions, stepping through the code, modifyingbreakpoints. You can debug your agent until at least one document has beenprocessed and saved. Then stop the debugger.

To control that the agent executes correctly, using Notes client, open theeTrade Vendor database and display the PreviousOrders view. Thedocument(s) that have been altered by the agent will have the orderStatusfield set to set by java agent.

PreparePOforEvaluator Agent 209

Page 230: Using VisualAge for Java To Develop Domino Applications

If you change the code in VisualAge for Java, there is no need to re-exportyour code and re-import it into Domino Designer. While you are debugging,you code runs entirely in VisualAge for Java. If you do update the code inDomino Designer for some reason, however, you should generate a newcontext document before continuing your debugging.

8.5 Implementing the Business Rules Verification

So far the PreparePOforEvaluator agent (Version 1) is not very useful. Youneed to modify the class to access the Business Rules class created in“BusinessRules Class” on page 168. The agent uses the same infrastructureto check the business rules.

Using VisualAge for Java, select the eTradeVendor project, the poAgentpackage, and the PreparePOforEvaluator class.

In the class definition, add a class variable, businessRules, as follows:

import acme.*;import acme.po.*;import lotus.domino.*;public class PreparePOforEvaluator extends lotus.domino.DebugAgentBase {

private BusinessRules businessRules;}

Edit the NotesMain() method to check every single order line (item, quantity,...) against the business rules server. The modifications added to the

If you use the same agent in different databases, AgentRunner uses thecontext document for the first one listed for the agent in the AgentRunnerdatabase. Since that list is sorted by the database file name, the contextdocument that is used may not be the one for the database you areexpecting.

Agent context documents hold references to the documents that areaccessed by an agent. Usually you do not need to keep generating newagent context documents while you are debugging an agent. However, thePreparePOforEvaluator agent modifies the document orderStatus fieldused in the selection criteria. Once all the documents available have beenmodified, you must create new documents. In order for AgentRunner to findthe new documents, generate a new context document.

AgentContext Documents

210 Using VisualAge for Java to Develop Domino Applications

Page 231: Using VisualAge for Java To Develop Domino Applications

NotesMain method created in “PreparePOforEvaluator Class” on page 202are highlighted in bold.

public NotesMain() {try {

Session session = getSession();AgentContext ac = session.getAgentContext();Database db = ac.getCurrentDatabase();Document doc = null;Catalog catalog = new Catalog(db);POItem poItem = null;java.util.Vector orderItems = new java.util.Vector();java.util.Vector quantitiesOrdered = new java.util.Vector();java.util.Vector itemNames = new java.util.Vector();java.util.Vector itemPrices = new java.util.Vector();java.util.Vector itemTotals = new java.util.Vector();java.util.Vector orderStatusHistory = new java.util.Vector();String productID = null;double quantity;double itemPrice;double itemTotal;StringBuffer orderStatus;DocumentCollection dc = ac.getUnprocessedDocuments();if (dc.getCount() > 0) {

//initialize the businessRules objectbusinessRules = new BusinessRules();for (int i = 1; i < (dc.getCount() + 1); i++) {

doc = dc.getNthDocument(i);//First make the PO object.PO po = new PO(doc.getItemValueString("buyersName"));//Then get the items and quantities from the PO.orderItems = doc.getItemValue("itemsOrdered");quantitiesOrdered = doc.getItemValue("quantitiesOrdered");for (int j = 0; j < orderItems.size(); j++) {

//We need productID and Quantity from the PO.productID = (String) orderItems.elementAt(j);quantity =

Double.valueOf(quantitiesOrdered.elementAt(j).toString()).doubleValue();//Now get the product document.try {

poItem = catalog.getItem(productID, quantity);po.addItem(poItem);

} catch (NotesException ne) {System.out.println("Error adding item to PO " + ne.text);

} catch (Exception e) {e.printStackTrace();

}

PreparePOforEvaluator Agent 211

Page 232: Using VisualAge for Java To Develop Domino Applications

}//Check against the business rules.if (orderItems.size() > 0) {

po = businessRules.check(po);}//Rebuild the local representation of the order.orderItems.removeAllElements();itemNames.removeAllElements();itemPrices.removeAllElements();quantitiesOrdered.removeAllElements();itemTotals.removeAllElements();java.util.Vector checkedItems = po.getItemlist();for (int j = 0; j < checkedItems.size(); j++) {

orderItems.addElement(((POItem) checkedItems.elementAt(j)).getProductID());

itemNames.addElement(((POItem) checkedItems.elementAt(j)).getProductName());

itemPrice = ((POItem) checkedItems.elementAt(j)).getPriceUnit();

itemPrices.addElement(new Double(itemPrice));quantity = (

(POItem) checkedItems.elementAt(j)).getQuantity();quantitiesOrdered.addElement(Double.toString(quantity));itemTotal = (

(POItem) checkedItems.elementAt(j)).getTotal();itemTotals.addElement(new Double(itemTotal));

}//Update the PurchaseOrder documentdoc.replaceItemValue("itemsOrdered", orderItems);doc.replaceItemValue("itemNames", itemNames);doc.replaceItemValue("itemPrices", itemPrices);doc.replaceItemValue("quantitiesOrdered", quantitiesOrdered);doc.replaceItemValue("itemTotals", itemTotals);doc.replaceItemValue("orderSubtotal",

new Double(po.getSubtotal()));doc.replaceItemValue("orderDiscount",

new Double(po.getDiscount() / 100));doc.replaceItemValue("orderTotal", new Double(po.getTotal()));orderStatus = new StringBuffer();orderStatus.append("processed");doc.replaceItemValue("orderStatus", orderStatus.toString());orderStatus.append(" as of ");orderStatus.append(new java.util.Date().toString());orderStatusHistory.removeAllElements();orderStatusHistory = doc.getItemValue("orderStatusHistory");orderStatusHistory.insertElementAt(orderStatus.toString(), 0);

212 Using VisualAge for Java to Develop Domino Applications

Page 233: Using VisualAge for Java To Develop Domino Applications

doc.replaceItemValue("orderStatusHistory",orderStatusHistory);

ac.updateProcessedDoc(doc);doc.save(true, false);

}}

} catch (NotesException e) {System.err.println("Error, Notes Exception: " + e);

} catch (Exception e) {System.err.println("Error, Exception: " + e);

}

Save your changes. Referring to “PreparePOforEvaluator Agent” onpage 204, update the PreparePOforEvaluator agent in Domino Designer.When you export your VisualAge for Java code and refresh the classes of theDomino agent using Domino Designer, you have to reimport all the requiredclasses, even though the agent classes are not executed when you generatethe context document.

Refer to “Testing and Debugging the Agent” on page 207 to test and debugthe new version of the agent using AgentRunner.

8.6 Implementing the CheckCredit Rule

Once the agent is using the BusinessRules class, you have to make a fewminor changes to implement the CreditRule rule.

SubmittedPO ClassUsing VisualAge for Java, select the eTradeVendor project, the acme.popackage, and create the public SubmittedPO class that extends PO andimports acme.*.

The SubmittedPO constructor is as follows:

/*** SubmittedPO constructor comment.* @param username java.lang.String*/public SubmittedPO(String username) {

super(username);}

We use this class to differentiate between POs checked by the PO applet andPOs checked by the agent. In a real application, this class would normally domore processing.

PreparePOforEvaluator Agent 213

Page 234: Using VisualAge for Java To Develop Domino Applications

CreditRule ClassUsing VisualAge for Java, select the eTradeVendor project, the acmepackage, and create the public CreditRule class that implements SingleRuleand imports acme.*.

In the CreditRule class, create a public PO check method that checks forcredit. In the sample, the rule is generate a random credit limit.

public PO check(PO order) {if (order.getClass().toString().equals("class acme.po.SubmittedPO")) {

double customerCredit = (double) Math.random() * 1000;customerCredit = Math.round(customerCredit);order.setStatusText("Customer credit limit is: $"

+ new Double(customerCredit).toString());}return order;

}

BusinessRules ClassYou have to make the BusinessRules class aware of the new credit checkrule.

Using VisualAge for Java, select the eTradeVendor project, the acmepackage, and open the BusinessRules class constructor to add the new creditcheck rule.

public BusinessRules(){rules=new java.util.Vector();rules.addElement(new DiscountRule());rules.addElement(new CreditRule());

}

PreparePOforEvaluator classYou have to update the NotesMain method of the PreparePOforEvaluatorclass to use the SubmittedPO class.

Replace the line:

PO po = new PO(doc.getItemValueString("buyersName"));

with

SubmittedPO po = new SubmittedPO(doc.getItemValueString("buyersName"));

Then replace the line:

po = businessRules.check(po);

with

214 Using VisualAge for Java to Develop Domino Applications

Page 235: Using VisualAge for Java To Develop Domino Applications

po = (SubmittedPO)businessRules.check(po);

Somewhere before the document is saved, add the following line:

doc.replaceItemValue("buyersCredit", po.getStatusText());

Save your changes. Refering to “PreparePOforEvaluator Agent” on page 204,update the PreparePOforEvaluator agent in Domino Designer.

Refer to “Testing and Debugging the Agent” on page 207 to test and debugthe new version of the agent using AgentRunner.

8.7 Implementing RMI

Although you have implemented the BusinessRules check method in thePreparePOforEvaluator agent, the architecture is based on a central resourcethat implements changes throughout the organization.

To follow this architecture, you need to use RMI to access theBusinessRulesServer class.

PreparePOforEvaluator ClassUsing VisualAge for Java, select the eTradeVendor project, the poAgentpackage, and the PreparePOforEvaluator class.

In the class definition, import the RMI Java packages:

import java.rmi.*;import acme.rmi.*;

Replace the businessRules class variable with the following definition:

private POChecker businessRules;

Then, in the NotesMain method, replace the businessRules classinstantiation:

businessRules = new BusinessRules();

with a connection to the RMI security manager and a lookup to the RMIregistry (refer to “BusinessRules Client” on page 181 for more informationabout the RMI registration):

if (System.getSecurityManager() == null) {System.setSecurityManager(new RMISecurityManager());

}try {

String name = "//"+SERVER+"/POChecker";

PreparePOforEvaluator Agent 215

Page 236: Using VisualAge for Java To Develop Domino Applications

businessRules = (POChecker) Naming.lookup(name);} catch (Exception e) {

System.err.println("Business Rules Server not reachable: " +e.getMessage());

e.printStackTrace();}

The SERVER variable contains the IP address of the server. It is identical tothe addresses used for the POApplet and BusinessRulesServer classes.(refer to “notesAppletInit() Method” on page 180 and “main() Method” onpage 170).

To test the agent, you have to set up the RMI environment as described in“RMI and the Business Rules Server” on page 182. However, you do not needto re-create the RMI stub and skeleton:

1. Make the required classes available to the RMI registry andBusinessRulesServer.

In addition to POItem, PO, BusinessRulesServer,BusinessRulesServer_Stub, BusinessRulesServer_Skel, SingleRule,POChecker and DiscountRule you also need to make the SubmittedPO,CreditRule, and the new version of the BusinessRules available to theBusinessRulesServer and the RMI registry.

2. Start the RMI registry.

3. Start the BusinessRulesServer.

4. Create PurchaseOrder documents to process and an agentContextdocument that refers to them.

5. If you are running the BusinessRulesServer in VisualAge for Java, set abreakpoint in the check method of the BusinessRules class. Otherwise seta breakpoint in the NotesMain method of the PreparePOforEvaluatorclass.

6. Run the PreparePOforEvaluator class with AgentRunner in VisualAge forJava.

Once you are satisfied that the agent is running correctly, re-export the filesand import them into the agent in Domino Designer. You no longer need theBusinessRules, DiscountRule, CreditRule, or SingleRule in the agent. Theclasses you do need are as follows:

• PreparePOforEvaluator

• Catalog

• POItem

216 Using VisualAge for Java to Develop Domino Applications

Page 237: Using VisualAge for Java To Develop Domino Applications

• PO

• SubmittedPO

• BusinessRulesServer_Skel

• BusinessRulesServer_Stub

• POChecker

Now test your agent running natively in Domino. You should not have to makeany additional changes to the RMI server, whether you are running it inVisualAge for Java or from the console.

8.8 Running the Agent Natively in Domino

Once the agent gives satisfactory results, you can implement it as a realagent.

You have to replace the superclass of the PreparePOforEvaluator class withAgentBase:

public class PreparePOforEvaluator extends lotus.domino.AgentBase {

Then you need to export it again and reimport the class in the Domino agent.Make sure to include the acme and acme.po packages in the export.

Using Domino Designer, reimport the class files of thePreparePOforEvaluator agent. Include also the contents of the acme andacme.po packages.

You are ready to use the agent in a production environment.

When you create an agent that uses classes besides the Domino objectclasses, you must import all of them from the same Base directory. This isstraightforward if you export all your files to the same directory inVisualAge for Java. If you change directories, you must export all theclasses to the new directory, then reimport them all from that directory.

The directory that you use does not need to be in the Domino datadirectory, or on the classpath of your server’s environment. In fact Dominodoes not use the classpath to look for any classes used by your agent. Thatis the reason why you must always import all the files.

Multi-class Agents

PreparePOforEvaluator Agent 217

Page 238: Using VisualAge for Java To Develop Domino Applications

218 Using VisualAge for Java to Develop Domino Applications

Page 239: Using VisualAge for Java To Develop Domino Applications

Chapter 9. StatusServlet Servlet

The StatusServlet servlet gets all previous orders of a certain customer fromthe Domino server and generates HTML output to be displayed to thecustomer.

In this chapter we explain how to develop a Java servlet using VisualAge forJava. To show a different way to access Domino data from a Java program,we use the Domino Driver for JDBC.

9.1 Design Overview

The StatusServlet receives requests that include the customer’s name andencrypted HTTP password as parameters. The response to the request is anHTML document that contains all purchase orders that were previouslycreated by that customer. For each order, the servlet returns the PO number,the creation date, the list of ordered items and the status history. The outputis created by the doGet() method of the StatusServlet servlet.

The doGet() method gets the required data for the output using the DominoDriver for JDBC.

9.2 Prerequisites

Before you can start creating the StatusServlet you have to download andinstall additional software required for developing servlets and using theDomino Driver for JDBC.

Java Servlet Development Kit (JSDK):Download the JSDK from Sun’s Web site and install it on your developmentmachine in the jsdk directory.

Using VisualAge for Java, select Selected - Add - Project in any browserwindow. Create the Java Servlet Development Kit project using the AddProject pane. Select Selected - Import to import the jsdk.jar file from thejsdk\lib directory into the Java Servlet Development Kit project.

Domino Driver for JDBCDownload the Domino Driver for JDBC from Lotus’s Web site and install it onyour development machine in the jdbcSql directory.

Using VisualAge for Java, select Selected - Add - Project in any browserwindow. Create the Domino JDBC Driver project using the Add Project pane.

© Copyright IBM Corp. 1999 219

Page 240: Using VisualAge for Java To Develop Domino Applications

Select Selected - Import to import the JdbcDomino.jar file from thejdbcSql\lib directory into the Domino JDBC Driver project.

9.3 StatusServlet Class

The StatusServlet does not have anything in common with the other classes.It is recommended to create a new package.

StatusServlet ClassUsing VisualAge for Java, select the eTradeVendor project and Selected -Add - Package to add the acme.servlet package.

Select the new acme.servlet package and Selected - Add - Class to displaythe Create Class pane. Select Create a new class and enter StatusServletthat extends javax.servlet.http.HttpServlet. You don’t compose the classvisually. Make sure that you import the java.io, java.util, javax.servlet,javax.servlet.http, and java.sql packages.

FieldsThe StatusServlet servlet needs one field to hold the connection to theDomino database.

In the eTradeVendor project browser window, select the acme.servletpackage, the StatusServlet class and Selected - Add - Field.

Create the private con field of type Connection used to connect toeTradeVe.nsf database. Create the private con1 field of type Connectionused to connect to the Domino directory.

As the fields should not be accessible from outside the StatusServlet, theyare defined as private and have no get or set methods. The Connection classdefinition is included in the imported package java.sql.

Create the SERVERNAME String constant and set its initial value to thename of your Domino Server.

MethodsAs described in “Java Servlets” on page 11, a servlet has a lifecycle similar toan applet. The main methods are init(), service() and destroy().

init() MethodThe init() method has to perform the following actions:

• Load the Domino Driver for JDBC.

• Get a JDBC connection to the eTradeVendor database.

220 Using VisualAge for Java to Develop Domino Applications

Page 241: Using VisualAge for Java To Develop Domino Applications

• Get a JDBC connection to the Domino server’s directory.

public void init(ServletConfig config) throws ServletException{super.init(config);try { // LOAD JDBC DRIVER

try {Class.forName("lotus.jdbc.domino.DominoDriver");

} catch (ClassNotFoundException e) {System.out.println("ClassNotFoundException: " + e.getMessage());

}// GET CONNECTIONSString connStr = "jdbc:domino/eTradeVe.nsf/"+SERVERNAME;con = DriverManager.getConnection(connStr);String connStr1 = "jdbc:domino/names.nsf/"+SERVERNAME;con1 = DriverManager.getConnection(connStr1);

}catch (Exception e) {System.out.println(e);e.printStackTrace();

}}

destroy() MethodThe destroy() method frees all resources held by the StatusServlet servlet.You need to close all the connections to the Domino databases.

public void destroy() {try{ // CLOSE CONNECTIONS

con.close();con1.close();

}catch(Exception e){System.out.println(e);e.printStackTrace()

}super.destroy();

}

authenticate() MethodThe authenticate() method requires a user name and the encrypted HTTPpassword for that user. There has to be a person document for the user withthe specified HTTP password in the Domino server’s directory.

The authenticate() method uses the con1 connection to create and execute aquery of the person document for the user name in the Domino directory. Theuser is authenticated, if the encrypted HTTP password stored in the directorymatches the parameter passed to the authenticate() method.

public boolean authenticate(String user, String password) {Statement stmt1 = null;

StatusServlet Servlet 221

Page 242: Using VisualAge for Java To Develop Domino Applications

String sql="Select HTTPPassword from Person where FullName = '"+user+"'";

ResultSet rs1=null;try {

stmt1 = con1.createStatement();rs1 = stmt1.executeQuery(sql);if (!rs1.next() ||!(rs1.getString(1).toLowerCase().equals(password.toLowerCase()))){stmt1.close();return false; // USER NOT AUTHENTICATED

}stmt1.close();

} catch (Exception e) {System.out.println("Exception: " + e.getMessage());e.printStackTrace();

}return true; // USER AUTHENTICATED

}

createHeader() MethodThe createHeader() method is a private method called from the doGet()method.

The createHeader() method requires the buyer’s name as input and returns astring containing the HTML code used in the header of the output. The outputsets the title for the browser window and creates the heading for the outputpage.

private String createHeader(String buyersName) {StringBuffer out = new StringBuffer();try {

out.append("<html>\n");out.append("<head><title>Order Status </title></head>\n");out.append("<body>\n");out.append("<h1>Order Status for ");out.append(buyersName);out.append(":</h1>\n");

} catch (Exception e) {System.out.println("Exception: " + e.getMessage());e.printStackTrace();

}return out.toString();

}

getItems() MethodThe getItems() method is a private method called from the doGet() method. Itrequires two parameters: the ItemsOrdered and QuantitiesOrdered fields of a

222 Using VisualAge for Java to Develop Domino Applications

Page 243: Using VisualAge for Java To Develop Domino Applications

purchase order. The method parses the two parameters using thejava.util.StringTokenizer. To gather the product name and price out of theeTradeVe.nsf database the method uses a PreparedStatement.

After the execution of the query, the method creates a row in a subtable foreach item of the purchase order. The executeQuery() method returns aResultSet object. Use the next() method to manipulate the rows of the resultset. The next() method returns true if there are still rows in the result set andadvances the current row. The nth column in a row can be accessed using theget---(n) (where --- stands for the actual type) method of the ResultSet class.

private String getItems(String items, String quantities) {String sql = "SELECT * FROM Catalog WHERE productId=?";try {

// CREATE PREPARED STATEMENT TO GET ITEM DATAPreparedStatement ps = con.prepareStatement(sql);StringBuffer out = new StringBuffer();// CREATE STRINGTOKENIZER TO PARSE PRODUCTIDSStringTokenizer ittok = new StringTokenizer(items, "; ");// CREATE STRINGTOKENIZER TO PARSE QUANTITIESStringTokenizer qtok = new StringTokenizer(quantities, "; ");ResultSet rs = null;out.append("<Table WIDTH=300>\n"); // START TABLE FOR ITEM DATAwhile (ittok.hasMoreTokens()) {

ps.setString(1, ittok.nextToken());// SET PARAM IN PREP STATEMENTrs = ps.executeQuery(); // EXECUTE PREPARED STATEMENTwhile (rs.next()) {// CREATE A TABLE ROW FOR EACH ITEMout.append("<TR>\n\t\t\t<TD ALIGN=LEFT NOWRAP>");out.append((rs.getString(2) +

" ").substring(0, 25));out.append("</TD>\n\t\t\t<TD ALIGN=RIGHT NOWRAP>");out.append("$ " + rs.getString(3));out.append("</TD>\n\t\t\t<TD ALIGN=RIGHT NOWRAP>");out.append(qtok.nextToken());

Statement and PreparedStatement are slightly different:

• A Statement contains the full SQL statement.

• A PreparedStatement can contain question marks as placeholders forvalues provided just before execution. The value for the nth placeholderis set using the setType(n,value) method, where Type stands for theactual parameter type. We use PreparedStatement here because weexpect more than one item to be on a purchase order.

Statement and PreparedStatement

StatusServlet Servlet 223

Page 244: Using VisualAge for Java To Develop Domino Applications

out.append("</TD>\n\t\t</TR>\n\t");} // END WHILE

} // END WHILEout.append("</Table>\n\t"); // END TABLEps.close(); //CLOSE STATEMENTreturn out.toString(); // RETURN OUTPUT} catch (Exception e) {

System.out.println(e);e.printStackTrace();return null; //RETURN ERROR OUTPUT= NULL

}}

createBody() MethodThe createBody() method is a private method called from the doGet()method. It creates the HTML output for the body of the servlet’s output. Theoutput is an HTML table with one row for each purchase order. Define thecreateBody() method as synchronized to make it thread-safe.

The createBody() method:

1. Creates table header

2. Gets previous orders of the customer

3. For each order:

1. Appends the purchase order number

2. Appends result of getItems(ponumber)

3. Appends statushistory

private synchronized String createBody(String buyersName) {// CREATE STRINGBUFFER TO CONSTRUCT OUTPUTStringBuffer out = new StringBuffer();out.append("<Table Border=5>\n"); // CREATE TABLE HEADERout.append("<TR><TD><H4>PONumber</H4><TD><H4>Date

</H4><TD><H4>Items</H4><TD><H4>Status History</H4>\n");// RETRIEVE ALL PREVIOUS ORDERS OF THE CUSTOMERString sql = "SELECT * from PreviousOrders where buyersName='"

+ buyersName + "'";Statement stmt = null;ResultSet rs = null;try {

stmt = con.createStatement(); // CREATE STATEMENTrs = stmt.executeQuery(sql); // EXECUTE STATEMENT

} catch (Exception e) {System.out.println("Exception: " + e.getMessage());

}

224 Using VisualAge for Java to Develop Domino Applications

Page 245: Using VisualAge for Java To Develop Domino Applications

try {// CREATE HTML OUTPUT FOR EACH PREVIOUS ORDER AS TABLE ROW// SET CURSOR TO NEXT ROWwhile (rs.next()) { // GET DATA

String poNumber = rs.getString(3);String date = rs.getDate(2).toString();String statusHistory = rs.getString(5);String itemsOrdered = rs.getString(6);String quantitiesOrdered = rs.getString(7);// CREATE STRINGBUFFER TO CONSTRUCT OUTPUT// FOR ONE ENTRY IN THE STATUSHISTORYStringBuffer str = new StringBuffer();int i; // POINTER FOR END OF NEXT ENTRYint j; // POINTER FOR START OF NEXT ENTRYj = 0; //INIT POINTERSi = statusHistory.indexOf(";");while (i > j) {

str.append(statusHistory.substring(j, i)); // STATUSHISTORYstr.append("<BR>"); // APPEND LINEBREAKj = i+1; // ADVANCE POINTERSi = statusHistory.indexOf(";", i + 1);

}if (j > 0) { // APPEND LAST ENTRY

str.append(statusHistory.substring(j));}out.append("<TR VALIGN=TOP>\n\t<TD NOWRAP>"); // CREATE OUTPUTout.append(poNumber);out.append("</TD>\n\t<TD NOWRAP>");out.append(date);out.append("</TD>\n\t<TD COLSPAN=1 NOWRAP>");out.append(getItems(itemsOrdered, quantitiesOrdered));out.append("</TD>\n\t<TD NOWRAP>");out.append(str);out.append("</TD>\n</TR>");

}out.append("</Table>\n"); // END TABLEstmt.close(); // CLOSE STATEMENT

} catch (Exception e) {try {

System.out.println(e);e.printStackTrace();stmt.close();

} catch (Exception ex) {}

}return out.toString(); // RETURN OUTPUT

StatusServlet Servlet 225

Page 246: Using VisualAge for Java To Develop Domino Applications

}

doGet() MethodThe doGet() method:

1. Retrieves the servlet parameters Name and Password

2. Sets the content type for the HttpServletResponse to text/html

3. Gets the OutputStream from the HttpServletResponse

4. Calls the authenticate(Name, Password) method

5. Calls theCreateHeader() method

6. Calls theCreateBody() method

7. Prints the closing line to the OutputStream

public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, IOException {

String name;String password;name = (String) req.getParameter("Name"); // GET PARAMETERSpassword = (String) req.getParameter("Password");res.setContentType("text/html"); // SET RESPONSE CONTENTTYPE// GET OUTPUTSTREAM TO DELIVER THE RESPONSEServletOutputStream out = res.getOutputStream();if(authenticate(name,password)){

out.print(createHeader(name)); // CREATE HEADERout.print(createBody(name)); // CREATE BODY

}else{// PRINT ERROR MESSAGEout.println("<html>\n<head><title>StatusServlet Error</title></head>

\n<body><H1> Error: User not authenticated</H1>");}out.println("</body></html>"); // END RESPONSE

}

9.4 Testing the StatusServlet

As described in “Debug and Test” on page 111, VisualAge for Java allows youto test and debug servlets before running them in a servlet-enabled Webserver. You can use the powerful debugging facilities of VisualAge for Java todebug your servlet.

During the test, you may bypass the authenticate() method to avoid enteringan encrypted password manually every time. To bypass the authentication,comment out the code authenticate() method and let it always return true.

226 Using VisualAge for Java to Develop Domino Applications

Page 247: Using VisualAge for Java To Develop Domino Applications

public boolean authenticate (String user, String password)throws ServletException{

/* Statement stmt1 = null.....*/return true ;

}

With this modification it is enough to provide the user name as parameter.

VisualAge for Java SetupTo act as a Servlet Runner, you have to enable the HttpServer to serve theStatusServlet servlet. The HttpServer must be able to find both theacme.servlet.StatusServlet class and all classes used by theDomino Driverfor JDBC. You need to set the CLASSPATH of the Servlet Runner to theDomino libraries, the project libraries (eTradeVendor project), and the DominoDriver for JDBC library (Domino Driver for JDBC project).

Running the StatusServletRun the HttpServer within VisualAge for Java. The Servlet Runner is listeningon port 8080 of your local machine. Start Domino Server.

To run the StatusServlet servlet (see Figure 103 on page 228), you can callthe servlet from a Web browser using the following URL:

localhost:8080/servlet/acme.servlet.StatusServlet?Name=Anonymous

StatusServlet Servlet 227

Page 248: Using VisualAge for Java To Develop Domino Applications

Figure 103. StatusServlet Servlet Output

Using the Servlet Runner within VisualAge for Java enables you to setbreakpoints in the code and debug the servlet in the same way as any otherJava application.

9.5 Deploying the StatusServlet on a Domino Server

When the StatusServlet servlet is running without error in VisualAge for Java,you have to set up the Domino Server that is supporting the servlet. You alsohave to copy all the required files into the correct directories.

In order to have the StatusServlet servlet available from within Domino youhave to:

• Set up Domino 5.0 Servlet Manager (see “Domino R5.0 Servlet Manager”on page 65).

• Export the StatusServlet class file into the directory which Domino uses asservlet default directory (see “Importing and Exporting Java Code” onpage 74.

• Optionally you can specify servlet properties in the servlets.properties filelocated in the Domino data directory (see “Domino R5.0 Servlet Manager”on page 65).

228 Using VisualAge for Java to Develop Domino Applications

Page 249: Using VisualAge for Java To Develop Domino Applications

Installing the Domino Driver for JDBCIf the servlet is supported on a Domino server on a separate machine, youhave to install the Domino Driver for JDBC on the server machine. TheDomino Driver for JDBC uses the Domino server DLLs and a Notes client isnot necessary. The driver uses the server ID.

However, the Domino Driver for JDBC R1 cannot find the path to the Dominoserver. You must put the Domino server path in your PATH environmentvariable. (The Domino server path is the directory where nserver.exe exists).The next release, 1.1, will be able to find the Domino server.

SecurityThe Domino Driver for JDBC doesn’t support the option of passing a username and a password in the getConnection() method. Instead you are alwaysprompted for the password of the current ID file used by the client. You canuse the server ID or an ID that is not password protected to avoid thepassword prompt.

However, the Domino Servlet Manager managing the StatusServlet servletruns under the server’s ID; therefore, it is already authorized when the servletis started.

Domino Server ClasspathDomino needs to find the Domino Driver for JDBC classes. Do not append thefully qualified file name of JdbcDomino.jar to the classpath field of the DominoJava Servlet Configuration pane (see Figure 24 on page 66), as the Dominoservlet manager uses its own security manager to load classes. This securitymanager prevents classes that make calls to native methods from beingloaded. The Domino Driver for JDBC makes that kind of call.

To work around this restriction of the servlet manager, use the Domino serversystem class loader. Add a JavaUserClasses directive to the Notesinitialization file (notes.ini) of the Domino server:

JavaUserClasses=<other paths>;c:\JdbcSql\Lib\JdbcDomino.jar

servlets.properties FileYou can customize the behavior of the Domino servlet manager by addingalias, initial start parameters, and servlet loading options in theservlets.properties file located in the domino\data directory of the Dominoserver.

Here is the servlets.properties file that defines the alias Status to theStatusServlet servlet. It also specifies that the servlet has to be loaded whenthe Domino HTTP task is started.

StatusServlet Servlet 229

Page 250: Using VisualAge for Java To Develop Domino Applications

servlet.Status.code=acme.servlet.StatusServletservlets.startup=Status

Shut down and restart your Domino Server to make the changes take effect.

You can now point your Web browser or Notes client to the following URL:

http://your.server.name/servlet/Status?buyersname=Anonymous

Replace Anonymous with a user name with which you already created a PO.

9.6 Integrating the StatusServlet in the Application

To finalize the integration of the servlet, you have to integrate the servlet inthe Catalog Interface form (see “Catalog Interface Form” on page 132).

Login TechnologyThe user of the StatusServlet servlet is authenticated using the authenticate()method. Therefore, the user needs to provide a user name and an encryptedHTTP password in the URL that calls the servlet.

The encrypted HTTP password comes from the Domino directory where theuser has to be identified.

To support the login process, you have to create a Login Domino form. TheLogin form has restricted access and uses Domino security to force users,trying to access the StatusServlet servlet, to log in if they are notauthenticated. The Login form gets the HTTP password of the user from theDomino directory, creates the URL for the StatusServlet servlet and leadsdirectly to that URL.

Login FormBecause the Login form is invisible to the user we don’t show the layout of thefields here.

Using Domino Designer, select the Recent Databases design bookmark. Inthe design pane of the eTrade Vendor database, select Forms in the list toopen the Design - Forms view.

Click the New Form action button to open the work area of the Form designpane. In the form properties box, enter Login as the name of the form.

Create the SaveOptions editable text field. Its value determines whether adocument created or edited within the form is saved. Set the default value to0 meaning that the document is not to be saved.

230 Using VisualAge for Java to Develop Domino Applications

Page 251: Using VisualAge for Java To Develop Domino Applications

Create the password editable text field. It holds the encrypted value of theuser’s HTTP password. The default value is generated by the followingDbLookup in the Domino directory:

@DbLookup("":"Nocache";@Name([Abbreviate];@Subset(@DbName;1)):"names.nsf";"($LDAPCN)";@Name([CN];@UserName);6)

Create the $$Return computed text field. Its value is returned after creating adocument based on the form. Use $$Return to return the URL of theStatusServlet servlet including the user name and password as parameters.

b:="[http://your.server.name/servlet/Status?Name="+@ReplaceSubstring(@Name([CN];@UserName);" ";"+")+"&Password="+password+"]";

b

Using the Login form properties box, restrict the access so that only [POCreators] are allowed to create documents with that form.

Modifications of the Catalog Interface FormOn the Catalog Interface form, you can provide the correct behavior of theOrder Status Report button (see“Order Status Report Button” on page 132).

When the user clicks on the Order Status Report button, a new document iscreated based on the Login form. If the user isn’t already logged in, Dominoprompts for a user name and password to access the Login form. Nodocument is created by the Login form because of the SaveOptions set to "0".The user is directly led to the StatusServlet servlet represented by the URL inthe return value.

Enter the following command for the Click event of the Order Status Reportbutton:

@URLOpen("http://your.server.name/etradeve.nsf/Login?CreateDocument")

StatusServlet Servlet 231

Page 252: Using VisualAge for Java To Develop Domino Applications

232 Using VisualAge for Java to Develop Domino Applications

Page 253: Using VisualAge for Java To Develop Domino Applications

Chapter 10. Conclusion

The eTrade Vendor application illustrates many ways of integrating Java in aDomino application. It uses an applet that uses the Domino objects classes, aJava agent, and a servlet that uses the Domino Driver for JDBC to connect toa Domino database. Each of the different approaches has its advantages anddisadvantages. There are also alternatives you may want to consider in somesituations. In this chapter we consider the different elements that can be usedto develop a Domino application in Java.

10.1 Domino Applet

Domino R5 offers the possibility to use the Domino objects classes directly inan applet. The CORBA implementation allows the Java program running on aclient to communicate with a Domino server. The client does not require anyDomino software installed but the Domino CORBA classes. The DominoCORBA Java library is provided in the ncso.jar file containing thelotus.domino.corba package.

Domino CORBA PackageA Web browser needs to download all the required packages before startingthe applet. When using CORBA, the Web browser has to download thelotus.domino.corba package on top of the application package file. That is1,621 KB for the uncompressed version (ncso.jar), 790 KB for thecompressed version for Netscape Communicator (ncsoc.jar), or 490 KB forMicrosoft Internet Explorer (ncso.cab).

When using Domino CORBA-enabled applets from a Web browser, try toavoid the long download time. For example, the applet can be downloaded atthe start of users’ sessions and they can perform their tasks without having todownload others applets. Another option—in an intranet environment—is toinstall the jar file directly on the Web browser machine.

You can also access the Domino server resources using other mechanismssuch as RMI. An RMI server application running on the Web server canreceive requests for Domino operations, execute them of behalf of the clientsand send back results to the clients.

AppletBaseThe AppletBase class simplifies greatly the creation and maintenance of thesession to the Domino server. We experienced some differences between thebehavior of the AppletBase in a Web browser and in a Notes client (see

© Copyright IBM Corp. 1999 233

Page 254: Using VisualAge for Java To Develop Domino Applications

“Accessing the Purchase Order Form Using a Notes Client” on page 200).You have to take these differences into account.

Note also that VisualAge for Java can help you test and debug an appletrunning in a Web browser as it uses the appletviewer to display the applet.VisualAge for Java is unable to test and debug the applet within a Notesclient.

10.2 Domino Java Agents

Java offers a true object-oriented architecture, with built-in networkfunctionality. Java is accepted as a standard in the IT industry.

Java or LotusScript, Formulas...Developing Domino Java agents is equivalent to developing LotusScriptagents. The Domino objects class and function names are similar to theirLotusScript equivalents. It facilitates the Java learning curve for LotusScriptdevelopers. Java agents are also easier to develop when they need to accessresources outside of Domino.

However, there are still many things you can do with simple actions, formulas,LotusScript, or JavaScript but not with Java. For example, there are noDomino classes for interacting with the Notes Client UI.

VisualAge for JavaUsing the external IDE for debugging is essential for an agent involving anylevel of complexity. VisualAge for Java offers an excellent debuggingenvironment. Developing an agent using VisualAge for Java may requiresome training as the use of DebugAgentBase, AgentRunner, and agentcontext documents is somewhat cumbersome. However, the full debuggingfacilities and VisualAge for Java’s incremental compilation are features thatgreatly improve the development process.

10.3 Domino Java Servlets

Servlets are an easy way to dynamically create HTML pages. As servlets runon the server, the performance of an application running a Web browser isincreased as it does not need any downloads apart from the HTML. Servletsare also a means to support different Web browser versions as no code isexecuted on the client.

Servlets can be multithreaded and in contrast to agents stay loaded on theserver at least after the first request from a client. That increases

234 Using VisualAge for Java to Develop Domino Applications

Page 255: Using VisualAge for Java To Develop Domino Applications

performance and eliminates the overhead of loading the required classes foreach request.

For applications producing results to be published on the Web, servlets canbridge them to Web browsers, make calls to the applications, wrap resultswith HTML, and send back the page to the browsers.

10.4 Agents, Servlets, or CGI Programs?

If you compare agents, servlets, and CGI programs, each type of programhas its advantages and can be the best choice in particular situations. Hereare some suggested uses for each type of program:

Table 11. Best Uses for Agent, Servlet and CGI Programs

Some differences in the program properties can be pointed out and they arerelated to:

• Programming language

• You can write agents in Java, LotusScript, or using the Notes formulalanguage.

• Servlets are written exclusively in Java.

• In CGI programs you use platform scripting languages, any languagecompiled into an executable file, or cross-platform languages such asJava or Perl.

• Program Storage

• Agents are stored in a Domino database, which means that agentstake advantage of database replication and server clustering.

Program Type Best Uses

Agent Programs that perform Domino actions when documents areread or posted.Programs that need to be run on a schedule or whendatabase actions occur, such as the arrival of new mail.

Servlet Programs that use standard Java interfaces such as JDBC.Programs that use HTTP session maintenance or cookies.Complex or resource-intensive Java programs.

CGI program Programs that need low-level access to system resources.Programs that interface with another product through anon-Java API.

Conclusion 235

Page 256: Using VisualAge for Java To Develop Domino Applications

• Servlets are stored in the file system, usually in the domino\servletdirectory.

• CGI programs are stored in the file system, usually in thedomino\cgi-bin directory.

• Web program invocation

• Agents are invoked automatically by a WebQueryOpen orWebQuerySave event, or invoked directly by an OpenAgent URL. Asalready mentioned agents can also be triggered by server events, suchas the arrival of new mail, or on a scheduled basis.

• You can invoke servlets and CGI programs directly by a URL.

• Program life-cycle

• Agents are loaded every time they are invoked and unloaded whentheir action is finished.

• Servlets are loaded once and stay loaded until the HTTP server task isshut down or restarted. This gives servlets a significant performanceadvantage over agents or CGI programs. However, this also meansthat the servlet module can be accessed from many requestssimultaneously, so you must make sure that the servlet code isthread-safe.

• Like agents, CGI programs are loaded every time they are invoked andunloaded when they finish.

• Domino interaction

• LotusScript and Java agents can use the Domino object classes.Formula agents can use most @functions (exceptions are noted in theApplication Developer's Guide).

• Servlets can access Domino through the Domino Object RequestBroker (CORBA) interface.

• CGI programs can access Domino through the CORBA interface, orthrough the Domino C or C++ APIs.

• Security

• To invoke an agent, a Web user must have at least Depositor access tothe database containing the agent. An agent can run with the identity ofits creator or the user. The full range of Domino security featuresapplies to operations performed by the agent.

• Access to the servlet can be controlled by file-protection documents inthe Domino Directory. If the servlet accesses Domino through the

236 Using VisualAge for Java to Develop Domino Applications

Page 257: Using VisualAge for Java To Develop Domino Applications

CORBA interface, it can specify a Domino user name and Internetpassword. Domino security applies to all CORBA operations.

Access to the program can be controlled by file-protection documents in theDomino Directory. If the program accesses Domino through a C API, it takesthe identity of the server ID; if it uses the CORBA interface, it can specify auser name and Internet password. In both cases, Domino security applies.

10.5 Domino Driver for JDBC

The Domino Driver for JDBC allows you to access a Java program. It can beused to access Domino through SQL commands (see“Domino Driver forJDBC” on page 44).

RestrictionsThe Domino Driver for JDBC has some environment restrictions as well asdata restrictions.

• A Notes client or a Domino server needs to be installed on the machinewhere the JDBC program runs.

• Columns that contain formulas are not visible in the JDBC tables.

• The Domino Driver for JDBC is not fully JDBC-compliant as it does notimplement the CallableStatement class or some methods of other classes.

AdvantagesThe Domino Driver for JDBC is a good solution when developing a Javaprogram that accesses and modifies Domino data, especially when:

• The program is required to only modify a Domino document’s field values.

• The team has JDBC skills.

• The program is migrated from a relational database system to a Dominodatabase. In this case, you don’t have to change anything in the programexcept loading the Domino Driver for JDBC.

• The program searches for data using simple SQL joins.

10.6 VisualAge for Java

VisualAge for Java is a very powerful IDE for developing Java applications. Inaddition to all the standard features like incremental compilation, codecompletion, project-centric development and the debugger, it provides theAgentRunner as a standard feature to run and debug Java agents for Domino.That opens a very powerful debugging environment for agents. VisualAge for

Conclusion 237

Page 258: Using VisualAge for Java To Develop Domino Applications

Java can also act like an HTTP server so that you can develop and debugservlets as well.

Overall, VisualAge for Java Version 2 is a very powerful and matureenvironment for developing Java applications with a powerful debugger.Together with the AgentRunner and the JSDK it opens all its great facilities tothe world of Java applications for Domino applications.

In addition, VisualAge for Java Version 3 ships with a Domino Access Builderthat again simplifies the access to Domino from Java code. The DominoAccess Builder is described in Chapter 11, “Domino Access Builder” on page241.

238 Using VisualAge for Java to Develop Domino Applications

Page 259: Using VisualAge for Java To Develop Domino Applications

Part 3. What’s Next?

VisualAge for Java is a fully integrated development environment for writing,compiling and testing 100% pure Java applets, servlets, Java storedprocedures and JavaBeans for enterprise e-business applications. Newfeatures in VisualAge for Java Version 3.0, including greater integration withIBM DB2 Universal Database and the WebSphere family, will make it easierthan ever to quickly and securely develop e-business applications and extendexisting data to the Web.

• New support for SQLJ speeds data access response times and simplifiesSQL coding.

• A new Stored Procedure Builder for DB2 simplifies development, testingand deployment of stored procedures and allows applications to benefitfrom the reliability and security of DB2.

• New support for deploying applications on Sun Solaris reinforcesVisualAge for Java's position as an open, cross-platform solution forcreating and testing e-business applications, supporting more platformsthan any other development environment.

• Greater integration with WebSphere Application Server and WebSphereStudio helps facilitate remote debugging, which simplifies testing andsaves time. Improved compiler optimization speeds development andhelps control costs.

• Domino Access Builder is a tool that creates customized Java beans toaccess Domino databases and services located on a Domino server or aLotus Notes client.

The new beta version of VisualAge for Java Professional Edition is availablefor download from IBM's VisualAge Developer resource site, VisualAgeDeveloper Domain at:

http://www.software.ibm.com/vadd

In this part we introduce the Domino Access Builder.

© Copyright IBM Corp. 1999 239

Page 260: Using VisualAge for Java To Develop Domino Applications

240 Using VisualAge for Java to Develop Domino Applications

Page 261: Using VisualAge for Java To Develop Domino Applications

Chapter 11. Domino Access Builder

The IBM Domino Access Builder is an application development tool thatcreates customized Java beans to access databases and services located ona Domino server or on a Notes client installation. It is composed of a set ofgeneric beans based on the Domino Java classes and a SmartGuide thatcreates user-defined beans to be used for programming and visualcomposition. The Domino Access Builder can be invoked from the VisualAgefor Java Integrated Development Environment (IDE).

The generic beans include wrapper classes for databases, forms, views, andother Domino design elements. The SmartGuide is used to select a databaseand to configure the code generator, which creates customized beans thatmatch the selected Domino design elements.

The Domino Access Builder has the following key features:

• Creation of customized beans

The Domino Access Builder has an easy-to-use interface to specify whichdatabases should be used as templates for the bean generation process.There are a variety of options to customize the generated beans forspecial purposes. User-defined code can easily be integrated.

• Easy access to Domino views and forms

Visual beans are generated for form beans. They allow quick compositionof user interfaces with the Visual Composition Editor. Generic treetablecontrol makes it easy to display Domino views.

• Easy-to-use error handling facility

An error handler bean is included which can be used to captureexceptions and transform them into messages that can be displayed usinga prompter.

• Transparent session management

All Domino connections and resources are maintained and managed bythe Domino Access Builder. No low-level programming is required.

• Support for multiple usage scenarios

The Domino Access Builder beans can be used for standaloneapplications as well as for creating applets. Applets can be configured torun in browsers or as part of the Domino or Notes client user interface asUI components.

© Copyright IBM Corp. 1999 241

Page 262: Using VisualAge for Java To Develop Domino Applications

Figure 104 on page 242 shows the workflow of a Domino Access Buildersession.

Figure 104. Domino Access Builder Session

The workflow of a Domino Access Builder session usually looks like this:

• The IDE is started and the Domino Access Builder Settings SmartGuide isused to specify the Domino data source location and the useridentification.

• Next, a database is selected and the Domino Access Builder SmartGuideanalyzes the design elements of the given database.

• After specifying which beans should be generated, the destination for thegenerated code is determined and the generator is started.

• Then, the customized beans can be used in Java programs and for visualcomposition in the VisualAge for Java IDE.

11.1 Main Components

The Domino Access Builder's main components are:

• Generic Domino Access Builder Beans (Domino Access Builder Library)

The Domino Access Builder wraps a number of essential Domino Javaclasses with bean interfaces. These beans can be used in Java programsand for visual composition in the VisualAge for Java IDE. The library alsoincludes beans for error handling, connection management, and atreetable view for displaying Domino views as a categorized tabularstructure.

242 Using VisualAge for Java to Develop Domino Applications

Page 263: Using VisualAge for Java To Develop Domino Applications

• SmartGuide and bean generator

The Domino Access Builder features a SmartGuide to configure the beangenerator. The SmartGuide allows the selection of a database on a localinstallation or on a Domino server. It then reads structural information fromthat database and offers a selection of forms and views which are used astemplates for the bean generation. Each element can be customized (forexample a Domino view may be changed to contain only a subset ofcolumns or a form may be enhanced by user-defined fields). The final stepin the SmartGuide is to select a destination package for the generatedbeans. Beans are generated according to the specifications and inconformity with the Domino Access Builder naming conventions.

• Generated Domino Access Builder Beans

The generation process yields beans for each form and view selectedduring the SmartGuide session as well as other useful beans.

• Generated beans based on Domino forms

A document bean, a form bean, and a quickform bean are generatedfor each selected Domino form. The document bean is used torepresent documents that contain all of the fields defined in thecorresponding form. The form bean is used during visual compositionand serves as a document factory. The quickform bean is a visualcomponent that contains predefined controls (entry fields). These entryfields can be linked to the document bean's field properties. EverySmartGuide session generates a formswitch bean that can be used toconnect document selection events from view beans to the appropriateform beans.

• Generated beans based on Domino views

A view bean is generated for every selected Domino view. Thenon-visual Domino view bean is predominantly used during visualcomposition to represent the hierarchical structure of documents. (Thegeneric treetable view bean is pre-configured to present a visualrepresentation of the Domino view with categories, rows, andcolumns).

• Other generated beans

A connection specification bean is generated to hold the connectioninformation for the application.

Domino Access Builder 243

Page 264: Using VisualAge for Java To Develop Domino Applications

11.2 Usage Scenarios

The Domino Access Builder can be used to create a variety of applications inconjunction with Lotus Notes or Domino. Depending on the location of yourdatabases and the Domino server setup, the following options are available:

• Using Domino Access Builder to create applets

The Domino Access Builder is an ideal tool for creating Java applets thatconnect to Domino via IIOP. These applets provide the means tomanipulate data from a browser. Visual composition of the applets allowsrapid development, even for complicated database applications.

The HTTP and DIIOP server tasks must be running on your Domino serverfor this configuration.

• Using Domino Access Builder to enhance forms

Generated Domino Access Builder applets can be embedded in Dominoforms and pages, creating a UI that is fully controlled by the appletdeveloper. The applets function in the Notes client as well as duringbrowser access to the database via HTTP.

• Using Domino Access Builder to build stand-alone applications

Finally, the Domino Access Builder can be used to create access beansfor stand-alone applications. They can run on a Domino server, on a Notesclient, or on any other system that connects to a Domino server via IIOP.

11.3 Library

The Domino Access Builder library is a set of Java beans based on the LotusDomino Java front-end classes. The beans can be used for regular coding aswell as for visual composition. The generic library beans serve assuperclasses for customized beans generated by the Domino Access BuilderSmartGuide. There are two main categories of beans: model beans andvisual beans.

11.3.1 Model BeansModel beans implement core functionality and often represent entities thatcorrespond directly to elements of a Domino system. The following listcontains the most important generic beans. Please refer to the referencesection to get a complete overview of available components.

• Session bean

244 Using VisualAge for Java to Develop Domino Applications

Page 265: Using VisualAge for Java To Develop Domino Applications

The session bean represents a session to either a Domino server or to alocal Notes client. Databases, views and forms are always associated witha session bean.

• Database bean

The database bean represents a database. It can be used to querydocuments from that database, to create new documents in that databaseand to get and set some database attributes (for example the databasetitle). Other beans like the form bean and the view bean have a databasebean as a property.

• Document bean

The document bean is the representation of a document. A documentusually contains a variety of named field values (also known as items).The bean provides methods to get and set item values and to save adocument to a given database. The generic document bean allows thecreation of documents with an arbitrary structure and supports all itemtypes provided by the Domino Java classes. Rich text capabilities arelimited.

• Form bean

The form bean is mainly used as a superclass for generated form beans. Itserves as a document factory that determines the field names and fieldtypes contained in a document based on a given form.

• View bean

The view bean is a query tool based on a particular Notes view. It uses theselection and order imposed by the view's definition to define and presenta set of documents to the user. The view bean is, despite its name, anon-visual bean. It is mainly used in conjunction with a visual viewtablebean and can fire events important for visual programming.

• Connection specification bean

The connection specification bean is used to hold all informationnecessary to connect to a given database on a given server. It can containthe current user ID and password. The bean can be registered in a globalconnection registry and is identified by a connection alias. The connectionspecification bean can be used to connect applications to databases inlocations other than the development environment without changing thecode.

• Error handler bean

Domino Access Builder 245

Page 266: Using VisualAge for Java To Develop Domino Applications

The error handler bean can be used to visually construct error handlingfacilities. Error handlers can be connected to sessions, databases, forms,and views and are automatically propagated to new objects.

• Navigator bean

The navigator bean can be used to navigate the hierarchical structure of aDomino view. It implements properties to access the document on which itis currently positioned and events that indicate out of bounds conditions.

• Logon specification bean

The logon specification bean is used to hold user and passwordinformation. It is needed when creating an IIOP session to a Dominoserver

• Formswitch bean

The formswitch bean can fire events based on the form of a document.Therefore, it can be used to visually construct a control structure. Thesestructures test to which form a document belongs. Formswitch beans aregenerated by a SmartGuide.

11.3.2 Visual BeansThe non-visual form bean and view bean are complemented with quickformbeans to show the data-structures contained in these model beans. Thevisual beans are derived from Swing classes.

• Quickform bean

The quickform bean contains a JScrollPane that is used to hold labels anddata entry controls based on the fields in a particular form. Quickformbeans are usually generated by the Domino Access Builder and are rarelyused in their generic appearance.

• Treetable bean

The treetable bean can be used to show a Notes view (or a view beanrespectively) in a table-like structure. The treetable bean is capable ofdisplaying expandable categories and columnar rows that representdocuments within that view. The treetable bean is supplemented by atreetable model.

11.4 Generated Access Beans

The Domino Access Builder is a rapid development tool that features anumber of prefabricated beans and generates customized beans to accessDomino objects. During a SmartGuide session, the user specifies a target

246 Using VisualAge for Java to Develop Domino Applications

Page 267: Using VisualAge for Java To Develop Domino Applications

database. The database is analyzed and the user can choose to generatebeans based on forms and views available in the database. The generatedbeans can be used for coding or visual composition.

For each selected form, three beans are generated: a form bean, a documentbean and a quickform bean. The form bean is used as a document factory.The document bean features customized bean properties for each fielddefined in the selected form. The quickform bean helps to create a quickoverview of the documents.

For each selected view, a view bean is generated. The view bean representsthe selected Domino view and provides protocols for navigation anddocument selection. A treetable control can be used to display the view bean.

In case a form is generated, the SmartGuide also generates a formswitchbean. This bean is able to fire events based upon the form of a document. Itcan be used to visually construct a control structure that test which form isassociated to a particular document.

11.5 Domino Java Classes

Lotus provides the Domino Java class library. There are several differencesbetween this class library and the Domino Access Builder.

First, the Domino Java class library classes can only partially be used asJava beans. They cannot be easily used for visual composition. The DominoAccess Builder Library contains a set of Java beans based on these classes.They are designed to integrate with the IBM VisualAge for Java IDE.

In addition, the Domino Access Builder is more than just a bean library. It is arapid development tool that generates code for customized Java beansbased on Domino databases.

Domino Access Builder 247

Page 268: Using VisualAge for Java To Develop Domino Applications

248 Using VisualAge for Java to Develop Domino Applications

Page 269: Using VisualAge for Java To Develop Domino Applications

Chapter 12. Using the Builder

In this chapter we describe the development process of a simple Dominoapplication using the new VisualAge for Java Domino Access Builder.

This process is based on a beta version of the product so it may changewhen the product becomes available. It is also important to notice that weused the Domino Access Builder with VisualAge for Java Version 2 and somedifference may be found when using with VisualAge for Java Version 3.

12.1 Verifying the Installation

As we used a beta version of the Domino Access Builder with VisualAge forJava Version 2, we needed to verify our installation.

Prerequisite FeaturesFrom the development machine, you can access the Domino database on aDomino R5 server using either:

• IIOP and anonymous IIOP

In that case there is no need for a local Lotus Notes client installation onthe development machine. Make sure the HTTP and the DIIOP tasks arerunning, and that your user has sufficient access privileges to open anIIOP session.

• RPC

You need a Lotus Notes R5 client installed on the development machine,which is connected to the Domino server using the communicationprotocol set up for your Notes client.

You can also access a Domino database local to the development machine.In that case, you need a Lotus Notes R5 client installed.

Installing the Domino Access Builder FeatureAfter installing the Domino Access Builder features, you need to add theDomino Access Builder Library to your workspace from the repository. Youmay also add the Domino Access Builder Library Samples (see Figure 105 onpage 250).

© Copyright IBM Corp. 1999 249

Page 270: Using VisualAge for Java To Develop Domino Applications

Figure 105. Domino Access Builder Project

VisualAge for Java ClasspathUsing VisualAge for Java Version 2, we need to add the two Domino libraries.Select Window- Options - Resources and ensure that the workspaceclasspath contains the following files:

c\Notes\Data\domino\java\NCSO.jar;c:\Notes\Notes.jar;

In VisualAge for Java Version 3, this step is useless as the product is shippedwith a Domino library that contains all the local and remote Domino classes.

Verifying the ConnectionWe tested the environment using an IIOP connection. We used the followingcode in the Scrapbook to verify the installation:

com.ibm.ivj.domino.ab.model.NConnectionSpec cs=com.ibm.ivj.domino.ab.model.NConnectionSpecFactory.newForDominoViaIIOP();cs.setHostName("TcpIpHostName");com.ibm.ivj.domino.ab.model.NLogonSpec ls =

new com.ibm.ivj.domino.ab.model.NLogonSpec();ls.setUserId("UserName");ls.setPassword("Password");com.ibm.ivj.domino.ab.model.NSession s =

new com.ibm.ivj.domino.ab.model.NSession();s.setConnectionSpec(cs);s.setLogonSpec(ls);

250 Using VisualAge for Java to Develop Domino Applications

Page 271: Using VisualAge for Java To Develop Domino Applications

s.open(); s.close();

The Domino Access Builder documentation provides test code to verify theinstallation when using anonymous IIOP or a local Notes client.

12.2 ProductList Applet

In the following section we develop a sample Domino application using theDomino Access Builder. The eTrade Vendor application has a list of productsin a Domino database. We use the Domino Access Builder to create theProductList applet to list the products, create new products, and deleteobsolete products.

Using VisualAge for Java, we create or select the VAJ Domino project. In thisproject, we create the DominoAccessBuilderTest package. We are now readyto use the Domino Access Builder.

12.2.1 SmartGuide SessionDomino Server and Database SelectionThe first task is to connect to the server and select the Domino database.

We select the DominoAccessBuilderTest package and Selected - Tools -DominoAccessBuilder - Run to display the Domino Access BuilderSmartGuide. In this pane we have to define the Domino server and thedatabase we want to access.

Server DefinitionTo define the server, we click Change to display the Connection TypeProperties SmartGuide (see Figure 106 on page 252).

In the following description we are not going to give step-by-stepinstructions on how to create the sample application. We are, however,going to give all the information needed to re-create the example.

A similar example, the To Do List application, is described step-by-step inthe Domino Access Builder online help.

Note

Using the Builder 251

Page 272: Using VisualAge for Java To Develop Domino Applications

Figure 106. Connection Type Properties SmartGuide - Domino Access Builder

As we connect to the Domino server using IIOP, we select Remote and IIOPto display the Server Selection Properties SmartGuide (see Figure 107 onpage 252).

Figure 107. Server Selection Properties SmartGuide - Domino Access Builder

In this pane, we can set oxygen as the server name (the TCP/IP name of theserver) and supply a user ID and a password for the connection. We can alsotest the connection with the entered values.

252 Using VisualAge for Java to Develop Domino Applications

Page 273: Using VisualAge for Java To Develop Domino Applications

Database SelectionTo select the database on the Domino server, we click Browse to display theDatabase Browser, which allows us to select the eTradeVendor database onthe Domino server (see Figure 108 on page 253).

Figure 108. Database Browser

Form SelectionWhen the Domino server and the database are selected, the Domino AccessBuilder SmartGuide displays the Form Selection pane to select the forms thatare used to generate the beans (see Figure 109 on page 254).

In our example we select only the Product form that is used to display theproducts.

Using the Builder 253

Page 274: Using VisualAge for Java To Develop Domino Applications

Figure 109. Form Selection SmartGuide - Domino Access Builder

After we have selected the forms, we can edit the generation options such asthe name of the beans, the fields name and type to generate. In the Edit FormGeneration Options pane (see Figure 110 on page 254), we select all thefields.

Figure 110. Edit Form Generation Options - Domino Access Builder

View SelectionProduct documents are displayed in the Catalog view. The Domino AccessBuilder needs to generate a bean for that view. Using the View Selectionpane, we can select the Catalog view.

254 Using VisualAge for Java to Develop Domino Applications

Page 275: Using VisualAge for Java To Develop Domino Applications

Figure 111. View Selection SmartGuide - Domino Access Builder

After we have selected the views, we can edit the generation options such asthe columns to generate, its indexes, and the names of the beans. In the ViewForm Generation Options pane (see Figure 112 on page 255), we select allthe fields.

Figure 112. Edit View Generation Options - Domino Access Builder

Package SelectionAfter all the forms and views have been selected, we can specify the aliasname of the connection bean and the package where to create the bean (seeFigure 113 on page 256).

Using the Builder 255

Page 276: Using VisualAge for Java To Develop Domino Applications

Figure 113. Package Selection SmartGuide - Domino Access Builder

When the selection is done, the Domino Access Builder starts the codegeneration of all the corresponding beans.

Figure 114 on page 256 shows the beans generated by Domino AccessBuilder.

Figure 114. Generated Beans

256 Using VisualAge for Java to Develop Domino Applications

Page 277: Using VisualAge for Java To Develop Domino Applications

12.2.2 Product List View Visual CompositionFigure 115 on page 257 shows the visual composition of the Product List.

Figure 115. Product List: Visual Composition

We created the ProductList class that inherits from DominoAccessApplet inthe DominoAccessBuilderTest package.

We created the ProductDialog class that inherits from JDialog in theDominoAccessBuilderTest package.

Opening the visual composition editor of the ProductList class, we added theProductView bean, generated by the Domino Access Builder, to the free-formsurface.

We also added:

• The LogonSpec bean of the type NLogonSpec, to the free-form surface,and we provided the user name and password.

• The TreeTable bean of the type NTreeTable, to the JPanel, and we set theautoResizeMode to AUTO_RESIZE_OFF.

• The TreeTableModel bean of the type NTreeTableModel, to the free-formsurface.

1

2

3

4

68 5

7

9

Using the Builder 257

Page 278: Using VisualAge for Java To Develop Domino Applications

• Three buttons named Product, New, and Delete, to the JPanel.

Table 12 lists all the connections between the different beans of theProductView pane.

Table 12. ProductList Connections

12.2.3 Product Dialog Visual CompositionOpening the visual composition editor of the ProductDialog class, we addedto the free-form surface the ProductForm bean, generated by the DominoAccess Builder.

We also added:

• The Document variable of the type NDocument, to the free-form surface,and we provided the user name and password.

• Two buttons named SaveAndClose and Cancel, to the JDialog.

• JTextFields named ProductNameField, IdentifierField, PriceField, andMinimumOrderField and their corresponding JLabels.

ConnectionNumber(see Figure 115on page 257)

Connection Type Connection from Connection to Comments

1 PtoP ProductViewdatabase

ProductDatabasethis

Automatically generated by tearoff

2 PtoP ProductDatabasesession

ProductSessionthis

Automatically generated by tearoff

3 PtoP LogonSpecthis

ProductSessionlogonSpec

4 PtoP ProductListthis

ProductSessionrunninApplet

5 PtoP TreeTableModelthis

TreeTabletreeTableModel

6 EtoM ProductactionPerformed

ProductViewopen()

7 PtoP TreeTableModelsourceView

sourceView1this

Automatically generated by tearoff

8 EtoM ProductactionPerformed

sourceView1this

9 PfromP connection 8value

ProductViewthis

258 Using VisualAge for Java to Develop Domino Applications

Page 279: Using VisualAge for Java To Develop Domino Applications

We added the following two methods:

/*** this method should be used to open the dialog with a given document*/public void showWith(com.ibm.ivj.domino.ab.model.NDocument document) {

setDocument(document);super.show();

}

/*** this method should be used to open the dialog and create a new document*/public void showWithNew() {

getProduct_Form().open();showWith(getProduct_Form().createDocument());

}

Figure 116 on page 259 shows the visual composition of the Product Dialog.

Figure 116. Product Dialog: Visual Composition

1

2

3 4

5

6

7

8

910

11

Using the Builder 259

Page 280: Using VisualAge for Java To Develop Domino Applications

Table 13 lists all the connections between the different beans of theProductDialog pane.

Table 13. ProductDialog Connections

12.2.4 Combining View and FormWe now have a functional representation of the Domino view and a dialog toedit the product. We need to combine both components to finish theapplication.

Figure 117 on page 261 shows the final visual composition of the ProductView and Dialog.

ConnectionNumber(see Figure 116on page 259)

ConnectionType

Connection from Connection to Comments

1 PtoP Product_FormcurrentProductDocument

currentProductDocument1this

Automatically generated by tearoff

2 PtoP Product_Formdatabase

database1this

Automatically generated by tearoffPromote the this property of thedatabase1 bean

3 EtoM Documentthis

Product_FormeditDocument

Pass event data selected

4 EtoC currentProductDocument1documentSaved

documentSaved Promoted documentSavedmethodas a bean feature

5 EtoM CancelactionPerformed

ProductDialogdispose

6 EtoM SaveAndCloseactionPerformed

currentProductDocument1save

7 EtoM currentProductDocument1documentSaved

ProductDialogdispose

8 PtoP currentProductDocument1productName

ProductNameFieldtext

9 PtoP currentProductDocument1productId

IdentifierFieldtext

10 PtoP currentProductDocument1productPrice

PriceFieldtext

11 PtoP currentProductDocument1productMinOrder

MinimumOrderFieldtext

260 Using VisualAge for Java to Develop Domino Applications

Page 281: Using VisualAge for Java To Develop Domino Applications

Figure 117. Product View and Dialog: Visual Composition

Opening the visual composition editor of the ProductList class, we added tothe free-form surface the ProductDialog bean.

Table 14 lists all the connections between the different beans of theProductList and ProductDialog pane.

Table 14. ProductList and ProductDialog Connections

ConnectionNumber(see Figure 117on page 261)

ConnectionType

Connection from Connection to Comments

A EtoM TreeTableModeldocumentSelected

ProductDialogshowWith

Pass event data selected

B PtoP ProductDatabasethis

ProductDialogdatabase1This

C EtoM ProductDialogdocumentSaved

sourceView1refresh

This is the promoteddocumentSave event fromProductDialog

D EtoM NewActionPerformed

ProductDialogshowWithNew

E PtoP TreeTableModelcurrentDocument

currentDocument1this

Automatically generated by tearoff

B

CA

D F

E

G

Using the Builder 261

Page 282: Using VisualAge for Java To Develop Domino Applications

12.2.5 Testing the AppletBefore we start the Product List applet, we need to provide the IOR for theapplet. Refer to “CORBA Parameters” on page 186 for more explanation.

To start the application, we select it from the Workbench window and selectSelected - Run - In Applet Viewer.

Figure 118 on page 262 shows the Product View of the Product List applet inVisualAge for Java’s Applet Viewer.

Figure 118. Product List Applet

Clicking on Product displays the list of products.

When a product is selected, clicking on Delete deletes the selected productfrom the database.

Clicking on New displays the Product dialog (Figure 119 on page 263) wherethe user can enter the new product information and save it in the database.

F EtoM DeleteactionPerformed

currentDocument1remove

G EtoM currentDocument1documentRemoved

sourceView1refresh

ConnectionNumber(see Figure 117on page 261)

ConnectionType

Connection from Connection to Comments

262 Using VisualAge for Java to Develop Domino Applications

Page 283: Using VisualAge for Java To Develop Domino Applications

Figure 119. Product Dialog

Using the Builder 263

Page 284: Using VisualAge for Java To Develop Domino Applications

264 Using VisualAge for Java to Develop Domino Applications

Page 285: Using VisualAge for Java To Develop Domino Applications

Appendix A. The Sample Application

In this appendix we explain how to download the ACME Digital eTradeVendor sample application and set up the demonstration.

Please note that the sample application is not a complete customer solution;rather it is a demonstration of Domino Java features. Not all necessaryfunctions, application security, or even the desired look and feel have beenincorporated into the application. It is for demonstration purposes only.

A.1 Download

A Lotus Notes database containing the sample application is available fordownload on the IBM Redbooks Web site at www.redbooks.ibm.com.

Click on the Additional Materials button, select the SG245424 directory, andselect the files to download.

eTradeVe.nsf is the Lotus Notes database containing the sample application.

A.2 Environment

The sample application requires the following software:

• Domino Server R5

• VisualAge for Java V2

In our environment, we used Windows NT as the operating system. However,you can use any operating system that supports the required software. Thusthe demonstration can be installed on a single machine. We used aclient/server configuration with:

• On the server machine

• Domino Server R5

• On the development machine

• Domino Designer R5

• VisualAge for Java V2

• On the client machine

• Netscape Navigator 4.5

© Copyright IBM Corp. 1999 265

Page 286: Using VisualAge for Java To Develop Domino Applications

266 Using VisualAge for Java to Develop Domino Applications

Page 287: Using VisualAge for Java To Develop Domino Applications

Appendix B. JDK Layout Managers

Java uses layout managers to decide how components are positioned withintheir container. The choice of a layout manager for your container directlyaffects the size, shape, and placement of your components within thatcontainer. In addition, layout managers adapt dynamically to the dimensionsof the container, solving many problems related to display resolution or fontchanges.

You have five layout managers to choose from in JDK 1.1, ranging from thevery simple FlowLayout and GridLayout, to the special-purpose BorderLayoutand CardLayout and the flexible GridBagLayout. You can also choose not tohave any layout manager by using the null layout. The JFC implements twoother layout managers: BoxLayout and Overlay layout.

The classes implementing the layout managers are:

• FlowLayout that lays out components from left to right, starting new rows ifnecessary.

• BorderLayout that organizes components, using constraints based on thecompass directions: North, East, South, and West. The fifth direction isCenter. You do not have to use all directions in your programs if you do notneed them. A component in the Center will expand to fill any space in thecontainer.

• BoxLayout that arranges components along either an x-axis or y-axis. In ay-axis Boxlayout, components are arranged from top to bottom in theorder in which they are added. Unlike GridLayout, BoxLayout allowscomponents to occupy different amounts of space along the primary axis.

• CardLayout that simulates a deck of cards, or a notebook, in that you canput a number of pages on top of each other, and you can traverse thepages in several ways. In other words you can have an area that cancontain different components at different times.

• GridLayout that organizes components, using a predefined number ofrows and columns. It simply makes a number of components have equalsize, displaying them in the requested number of rows and columns. It ispossible to have a gap between cells. The components are added to cellsstarting from the top left corner, then going to the right. When a row is full,the next row is started from the left.

• GridBagLayout, the most sophisticated and flexible but also most complexof the layout managers. The advantage of using GridBagLayout instead ofGridLayout, which it resembles, is that the components do not have to be

© Copyright IBM Corp. 1999 267

Page 288: Using VisualAge for Java To Develop Domino Applications

of the same size. You can use several types of constraints when attachingcomponents to a container, including whether a component expandshorizontally or vertically.

• OverlayLayout that places each added component on top of one anotherand sizes the container large enough to hold the largest of itscomponents.

GridbagLayoutIn our example, the POApplet class uses the GridbagLayout which is themost powerful layout manager in the JDK.

The GridBagLayout allows you to lay out components in a grid. To set thelayout manager of a container call the setLayout() method with an instance ofthe chosen layout manager.

Components are placed in the grid based on the GridBagConstraintsparameter values passed to the containers add() method. GridBagLayoutcomponents can span over more than one call of the grid. Anchor andbehavior for resizing can be specified.

The properties of GridBagConstraints are:

• gridx to set the horizontal position

• gridy to set the vertical position

• gridwidth to set the number of horizontal cells

• gridheight to set the number of vertical cells

• anchor to set the anchor of the component within its place in the grid

• fill to set if the component is resized when the container is resized

• weightx to set the factor used to resize the component horizontally whenthe whole container is resized.

• weighty to set the factor used to resize the component vertically when thewhole container is resized.

• insets to set the external padding for the component

• ipadx to set the horizontal internal padding

• ipady to set the vertical internal padding

268 Using VisualAge for Java to Develop Domino Applications

Page 289: Using VisualAge for Java To Develop Domino Applications

Appendix C. Special Notices

This publication is intended to help information system architects, LotusNotes developers, and VisualAge for Java developers who want to useVisualAge for Java to develop Domino applications. The information in thispublication is not intended as the specification of any programming interfacesthat are provided byVisualAge for Java and Domino. See the PUBLICATIONSsection of the Lotus Programming Announcement for Domino and IBMProgramming Announcement for VisualAge for Java for more informationabout what publications are considered to be product documentation.

References in this publication to IBM products, programs or services do notimply that IBM intends to make these available in all countries in which IBMoperates. Any reference to an IBM product, program, or service is notintended to state or imply that only IBM's product, program, or service may beused. Any functionally equivalent program that does not infringe any of IBM'sintellectual property rights may be used instead of the IBM product, programor service.

Information in this book was developed in conjunction with use of theequipment specified, and is limited in application to those specific hardwareand software products and levels.

IBM may have patents or pending patent applications covering subject matterin this document. The furnishing of this document does not give you anylicense to these patents. You can send license inquiries, in writing, to the IBMDirector of Licensing, IBM Corporation, North Castle Drive, Armonk, NY10504-1785.

Licensees of this program who wish to have information about it for thepurpose of enabling: (i) the exchange of information between independentlycreated programs and other programs (including this one) and (ii) the mutualuse of the information which has been exchanged, should contact IBMCorporation, Dept. 600A, Mail Drop 1329, Somers, NY 10589 USA.

Such information may be available, subject to appropriate terms andconditions, including in some cases, payment of a fee.

The information contained in this document has not been submitted to anyformal IBM test and is distributed AS IS. The use of this information or theimplementation of any of these techniques is a customer responsibility anddepends on the customer's ability to evaluate and integrate them into thecustomer's operational environment. While each item may have beenreviewed by IBM for accuracy in a specific situation, there is no guarantee

© Copyright IBM Corp. 1999 269

Page 290: Using VisualAge for Java To Develop Domino Applications

that the same or similar results will be obtained elsewhere. Customersattempting to adapt these techniques to their own environments do so at theirown risk.

Any pointers in this publication to external Web sites are provided forconvenience only and do not in any manner serve as an endorsement ofthese Web sites.

The following terms are trademarks of the International Business MachinesCorporation in the United States and/or other countries:

The following terms are trademarks of other companies:

C-bus is a trademark of Corollary, Inc. in the United States and/or othercountries.

Java and all Java-based trademarks and logos are trademarks or registeredtrademarks of Sun Microsystems, Inc. in the United States and/or othercountries.

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

PC Direct is a trademark of Ziff Communications Company in the UnitedStates and/or other countries and is used by IBM Corporation under license.

ActionMedia, LANDesk, MMX, Pentium and ProShare are trademarks of IntelCorporation in the United States and/or other countries.

UNIX is a registered trademark in the United States and/or other countrieslicensed exclusively through X/Open Company Limited.

SET and the SET logo are trademarks owned by SET Secure ElectronicTransaction LLC.

IBM OS/390CICS OS/400DB2 RS/6000MQ S/390MQSerie SPOS/2 VisualAgeSystem/390 VM/ESAVisual Beans WebSphereXT 400

270 Using VisualAge for Java to Develop Domino Applications

Page 291: Using VisualAge for Java To Develop Domino Applications

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

Special Notices 271

Page 292: Using VisualAge for Java To Develop Domino Applications

272 Using VisualAge for Java to Develop Domino Applications

Page 293: Using VisualAge for Java To Develop Domino Applications

Appendix D. Related Publications

The publications listed in this section are considered particularly suitable for amore detailed discussion of the topics covered in this redbook.

D.1 International Technical Support Organization Publications

For information on ordering these ITSO publications see “How to Get ITSORedbooks” on page 275.

The books of the Lotus Solution for the Enterprise Collection are:

• Volume 1 - Lotus Notes: An Enterprise Application Platform, SG24-4837

• Volume 2 - Using DB2 in a Domino Environment, SG24-4918

• Volume 3 - Using the IBM CICS Gateway for Lotus Notes, SG24-4512

• Volume 4 - Lotus Notes and the MQSeries Enterprise Integrator,SG24-2217

• Volume 5 - NotesPump: The Enterprise Data Mover, SG24-5255

These publications are also relevant as further information sources:

• Programming with VisualAge for Java Version 2, SG24-5264

• Connecting Domino to the Enterprise Using Java, SG24-5425

• Lotus Domino Release 5: A Developer’s Handbook, SG24-5331

• Designing Web Applications Using Lotus Notes Designer for Domino 4.6,SG24-2183

• The Domino Defense: Security in Lotus Notes and the Internet,SG24-4848

• Java Network Security, SG24-2109

• Enterprise Integration with Domino for S/390, SG24-5150

• Using VisualAge for Java Enterprise Version 2 to Develop CORBA andEJB Applications, SG24-5276

© Copyright IBM Corp. 1999 273

Page 294: Using VisualAge for Java To Develop Domino Applications

D.2 Redbooks on CD-ROMs

Redbooks are also available on the following CD-ROMs. Click the CD-ROMsbutton at http://www.redbooks.ibm.com/ for information about all the CD-ROMsoffered, updates and formats.

D.3 Other Publications

This publication is also relevant as further information source:

• Programming Domino 4.6 with Java, Groupware for the Internet, by BobBalaban ISBN: 1558515836

CD-ROM Title Collection KitNumber

System/390 Redbooks Collection SK2T-2177

Networking and Systems Management Redbooks Collection SK2T-6022

Transaction Processing and Data Management Redbooks Collection SK2T-8038

Lotus Redbooks Collection SK2T-8039

Tivoli Redbooks Collection SK2T-8044

AS/400 Redbooks Collection SK2T-2849

Netfinity Hardware and Software Redbooks Collection SK2T-8046

RS/6000 Redbooks Collection (BkMgr) SK2T-8040

RS/6000 Redbooks Collection (PDF Format) SK2T-8043

Application Development Redbooks Collection SK2T-8037

IBM Enterprise Storage and Systems Management Solutions SK3T-3694

274 Using VisualAge for Java to Develop Domino Applications

Page 295: Using VisualAge for Java To Develop Domino Applications

How to Get ITSO Redbooks

This section explains how both customers and IBM employees can find out about ITSO redbooks,redpieces, and CD-ROMs. A form for ordering books and CD-ROMs by fax or e-mail is also provided.

• Redbooks Web Site http://www.redbooks.ibm.com/

Search for, view, download, or order hardcopy/CD-ROM redbooks from the redbooks Web site. Alsoread redpieces and download additional materials (code samples or diskette/CD-ROM images) fromthis redbooks site.

Redpieces are redbooks in progress; not all redbooks become redpieces and sometimes just a fewchapters will be published this way. The intent is to get the information out much quicker than theformal publishing process allows.

• E-mail Orders

Send orders by e-mail including information from the redbooks fax order form to:

• Telephone Orders

• Fax Orders

This information was current at the time of publication, but is continually subject to change. The latestinformation may be found at the redbooks Web site.

In United StatesOutside North America

e-mail [email protected] information is in the “How to Order” section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

United States (toll free)Canada (toll free)Outside North America

1-800-879-27551-800-IBM-4YOUCountry coordinator phone number is in the “How to Order”section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

United States (toll free)CanadaOutside North America

1-800-445-92691-403-267-4455Fax phone number is in the “How to Order” section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl/

IBM employees may register for information on workshops, residencies, and redbooks by accessingthe IBM Intranet Web site at http://w3.itso.ibm.com/ and clicking the ITSO Mailing List button.Look in the Materials repository for workshops, presentations, papers, and Web pages developedand written by the ITSO technical professionals; click the Additional Materials button. Employeesmay access MyNews at http://w3.ibm.com/ for redbook, residency, and workshop announcements.

IBM Intranet for Employees

© Copyright IBM Corp. 1999 275

Page 296: Using VisualAge for Java To Develop Domino Applications

IBM Redbook Fax Order Form

Please send me the following:

We accept American Express, Diners, Eurocard, Master Card, and Visa. Payment by credit card notavailable in all countries. Signature mandatory for credit card payment.

Title Order Number Quantity

First name Last name

Company

Address

City Postal code

Telephone number Telefax number VAT number

Invoice to customer number

Country

Credit card number

Credit card expiration date SignatureCard issued to

276 Using VisualAge for Java to Develop Domino Applications

Page 297: Using VisualAge for Java To Develop Domino Applications

Glossary

application programming interface (API). Aset of calling conventions defining how a serviceis invoked through a software package.

applet. A Java program designed to run within aWeb browser. Contrast with application.

application. In Java programming, aself-contained, stand-alone Java program thatincludes main() method. Contrast with applet.

bean. A definition or instance of a JavaBeanscomponent.

browser. An Internet-based tool that lets userbrowse Web sites.

class. An aggregate that defines properties,operations, and behavior for all instances of thataggregate.

client. As in client/server computing, theapplication that makes requests to the serverand, often, handles the necessary interactionwith the user.

client/server. A form of distributed processing,in which the task required to be processed isaccomplished by a client portion that requestsservices and a server portion that fulfills thoserequests. The client and server remaintransparent to each other in terms of locationand platform. See client and server.

Common Gateway Interface (CGI). A standardprotocol through which a Web server canexecute programs running on the servermachine. CGI programs are executed inresponse to requests from Web client browsers.

Common Object Request BrokerArchitecture (CORBA). A middlewarespecification which defines a software bus—theObject Request Broker (ORB)—that providesthe infrastructure

Data Access Builder. A VisualAge for JavaEnterprise tool that generates beans to accessand manipulate the content ofJDBC/ODBC-compliant relational databases.

© Copyright IBM Corp. 1999

database. (1) A collection of related datastored together with controlled redundancyaccording to a scheme to serve one or moreapplications. (2) All data files stored in thesystem. (3) A set of data stored together andmanaged by a database management system.

distributed processing. Distributedprocessing is an application or systems modelin which function and data can be distributedacross multiple computing resources connectedon a LAN or WAN. See client/server computing.

dynamic link library (DLL). A file containingexecutable code and data bound to a programat run time rather than at link time. The C++Access Builder generates beans and C++wrappers that let your Java programs accessC++ DLLs.

e-business Either (a) the transaction ofbusiness over an electronic medium such as theInternet or (b) a business that uses Internettechnologies and network computing in theirinternal business processes (via intranets), theirbusiness relationships (via extranets), and thebuying and selling of goods, services, andinformation (via electronic commerce.)

Enterprise Access Builders (EAB). InVisualAge for Java Enterprise, a set ofcode-generation tools.

file transfer protocol (FTP). The basic Internetfunction that enables files to be transferredbetween computers. You can use it to downloadfiles from a remote, host computer, as well as toupload files from your computer to a remote,host computer. See Anonymous FTP.

gateway. A host computer that connectsnetworks that communicate in differentlanguages. For example, a gateway connects acompany’s LAN to the Internet.

graphical user interface (GUI). A type ofinterface that enables users to communicatewith a program by manipulating graphicalfeatures, rather than by entering commands.Typically, a graphical user interface includes a

277

Page 298: Using VisualAge for Java To Develop Domino Applications

combination of graphics, pointing devices, menubars and other menus, overlapping windows, andicons.

hypertext markup language (HTML). The basiclanguage that is used to build hypertextdocuments on the World Wide Web. It is used inbasic, plain ASCII-text documents, but whenthose documents are interpreted (calledrendering) by a Web browser such as Netscape,the document can display formatted text, color, avariety of fonts, graphic images, special effects,hypertext jumps to other Internet locations, andinformation forms.

hypertext transfer protocol (HTTP). Theprotocol for moving hypertext files across theInternet. Requires an HTTP client program onone end, and an HTTP server program on theother end. HTTP is the most important protocolused in the World Wide Web (WWW). See alsoClient, Server, WWW.

HTTP request. A transaction initiated by a Webbrowser and adhering to HTTP. The serverusually responds with HTML data, but can sendother kinds of objects as well.

hypertext. Text in a document that contains ahidden link to other text. You can click a mouseon a hypertext word and it will take you to the textdesignated in the link. Hypertext is used inWindows help programs and CD encyclopediasto jump to related references elsewhere withinthe same document. The wonderful thing abouthypertext, however, is its ability to link—usingHTTP over the Web—to any Web document inthe world, yet still require only a single mouseclick to jump clear around the world.

Internet Inter-ORB Protocol (IIOP). An industrystandard protocol that defines how GeneralInter-ORB Protocol (GIOP) messages areexchanged over a TCP/IP network. The IIOPmakes it possible to use the Internet itself as abackbone ORB through which other ORBs canbridge.

integrated development environment (IDE). Asoftware program comprising an editor, acompiler, and a debugger. IBM's VisualAge forJava is an example of an IDE.

interface. A set of methods that can be accessedby any class in the class hierarchy. The Interfacepage in the Workbench lists all interfaces in theworkspace.

Internet. The vast collection of interconnectednetworks that all use the TCP/IP protocols andthat evolved from the ARPANET of the late1960’s and early 1970’s.

intranet. A private network inside a company ororganization that uses the same kinds of softwarethat you would find on the public Internet, but thatis only for internal use. As the Internet hasbecome more popular, many of the tools used onthe Internet are being used in private networks.For example, many companies have Web serversthat are available only to employees.

Internet protocol (IP). The rules that providebasic Internet functions.

See TCP/IP.

Java. Java is a new programming languageinvented by Sun Microsystems that is specificallydesigned for writing programs that can be safelydownloaded to your computer through theInternet and immediately run without fear ofviruses or other harm to your computer or files.Using small Java programs (called applets, Webpages can include functions such as animations,calculators, and other fancy tricks. We can expectto see a huge variety of features added to theWeb using Java, since you can write a Javaprogram to do almost anything a regularcomputer program can do, and then include thatJava program in a Web page.

Java archive (JAR). A platform-independent fileformat that groups many files into one. JAR filesare used for compression, reduced downloadtime, and security. Because the JAR format iswritten in Java, JAR files are fully extensible.

JavaBeans. In JDK 1.1, the specification thatdefines the platform-neutral component modelused to represent parts. Instances of JavaBeans(often called beans) may have methods,properties, and events.

Java Database Connectivity (JDBC). In JDK1.1, the specification that defines an API that

278 Using VisualAge for Java to Develop Domino Applications

Page 299: Using VisualAge for Java To Develop Domino Applications

enables programs to access databases thatcomply with this standard.

Java Development Kit (JDK) The JavaDevelopment Kit 1.1 is the latest set of Javatechnologies made available to licenseddevelopers by Sun Microsystems. Each releaseof the JDK contains the following: the JavaCompiler, Java Virtual Machine, Java ClassLibraries, Java Applet Viewer, Java Debugger,and other tools.

Java Foundation Classes (JFC) Developed byNetscape, Sun, and IBM, JFCs are buildingblocks that are helpful in developing interfaces toJava applications. They allow Java applicationsto interact more completely with the existingoperating systems.

LAN. Local area network. A computer networklocated at a user’s establishment within a limitedgeographical area. A LAN typically consists ofone or more server machines providing servicesto a number of client workstations.

method. A fragment of Java code within a classthat can be invoked and passed a set ofparameters to perform a specific task.

Multipurpose Internet Mail Extension (MIME).The Internet standard for mail that supports text,images, audio, and video.

online transaction processing (OLTP). A styleof computing that supports interactiveapplications in which requests submitted byterminal users are processed as soon as they arereceived. Results are returned to the requester ina relatively short period of time. An onlinetransaction-processing system supervises thesharing of resources to allow efficient processingof multiple transactions at the same time.

object. (1) A computer representation ofsomething that a user can work with to perform atask. An object can appear as text or an icon. (2)A collection of data and methods that operate onthat data, which together represent a logicalentity in the system. In object-orientedprogramming, objects are grouped into classesthat share common data definitions and methods.Each object in the class is said to be an instanceof the class. (3) An instance of an object class

consisting of attributes, a data structure, andoperational methods. It can represent a person,place, thing, event, or concept. Each instancehas the same properties, attributes, and methodsas other instances of the object class, though ithas unique values assigned to its attributes.

ODBC Driver. An ODBC driver is a dynamicallylinked library (DLL) that implements ODBCfunction calls and interacts with a data source.

ODBC Driver Manager. The ODBC drivermanager, provided by Microsoft, is a DLL with animport library. The primary purpose of the DriverManager is to load ODBC drivers. The DriverManager also provides entry points to ODBCfunctions for each driver and parameter validationand sequence validation for ODBC calls.

Open Database Connectivity (ODBC). AMicrosoft-developed C database applicationprogramming interface (API) that allows accessto database management systems callingcallable SQL, which does not require the use of aSQL preprocessor. In addition, ODBC providesan architecture that allows users to add modulescalled database drivers that link the application totheir choice of database management systems atrun time. This means applications no longer needto be directly linked to the modules of all thedatabase management systems that aresupported.

Object Request Broker (ORB). A CORBA termdesignating the means by which objectstransparently make requests and receiveresponses from objects, whether they are local orremote.

protocol. (1) The set of all messages to which anobject will respond. (2) Specification of thestructure and meaning (the semantics) ofmessages that are exchanged between a clientand a server. (3) Computer rules that provideuniform specifications so that computer hardwareand operating systems can communicate. It’ssimilar to the way that mail, in countries aroundthe world, is addressed in the same basic formatso that postal workers know where to find therecipient’s address, the sender’s return addressand the postage stamp. Regardless of the

279

Page 300: Using VisualAge for Java To Develop Domino Applications

underlying language, the basic protocols remainthe same.

proxy. An application gateway from one networkto another for a specific network application suchas Telnet of FTP, for example, where a firewall’sproxy Telnet server performs authentication of theuser and then lets the traffic flow through theproxy as if it were not there. Function isperformed in the firewall and not in the clientworkstation, causing more load in the firewall.Compare with socks.

Remote Method Invocation (RMI). In JDK 1.1,the API that allows you to write distributed Javaprograms, allowing methods of remote Javaobjects to be accessed from other Java virtualmachines.

server. A computer that provides services tomultiple users or workstations in a network; forexample, a file server, a print server, or a mailserver.

Socket Secure (SOCKS). The gateway thatallows compliant client code (client code madesocket secure) to establish a session with aremote host.

Transmission Control Protocol/InternetProtocol (TCP/IP). The basic programmingfoundation that carries computer messagesaround the globe via the Internet. The suite ofprotocols that defines the Internet. Originallydesigned for the UNIX operating system, TCP/IPsoftware is now available for every major kind ofcomputer operating system. To be truly on theInternet, your computer must have TCP/IPsoftware.

thin client Thin client usually refers to a systemthat runs on a resource-constrained machine orthat runs a small operating system. Thin clientsdon't require local system administration, andthey execute Java applications delivered over thenetwork.

Uniform Resource Locator (URL). Standard toidentify resources on the World Wide Web

virtual machine (VM) A software program thatexecutes other computer programs. It allows a

physical machine, a computer, to behave as if itwere another physical machine.

Web server The server component of the WorldWide Web. It is responsible for servicing requestsfor information from Web browsers. Theinformation can be a file retrieved from theserver's local disk or generated by a programcalled by the server to perform a specificapplication function.

workstation. A configuration of input/outputequipment at which an operator works. A terminalor microcomputer, usually one that is connectedto a mainframe or a network, at which a user canperform applications.

World Wide Web (WWW or Web). A graphichypertextual multimedia Internet service.

280 Using VisualAge for Java to Develop Domino Applications

Page 301: Using VisualAge for Java To Develop Domino Applications

List of Abbreviations

API applicationprogramming interface

ASP active server page

ACL access control list

APPC AdvancedProgram-to-ProgramCommunication

ASCII American NationalStandard Code forInformationInterchange

AWT abstract window toolkit

BOA basic object adapter

CGI Common GatewayInterface

CICS Customer InformationControl System

CORBA Common ObjectRequest BrokerArchitecture

DBMS database managementsystem

DECS Domino EnterpriseConnection Services

DLL dynamic link library

DNS domain name server

EBCDIC extended binary codeddecimal interchangecode

EJB Enterprise JavaBean

ERP enterprise resourceplanning

FTP file transfer protocol

GIOP General Inter-ORBProtocol

GUI graphical user interface

© Copyright IBM Corp. 1999

HTML Hypertext MarkupLanguage

HTTP Hypertext TransferProtocol

IBM International BusinessMachines Corporation

IDE integrated developmentenvironment

IDL interface definitionlanguage

IIOP Internet Inter-ORBProtocol

IMAP Internet MessageAccess Protocol

ITSO International TechnicalSupport Organization

JDBC Java databaseconnectivity

JDK Java Development Kit

JNDI Java naming anddirecory interface

JSDK Java ServletDevelopment Kit

JSP Java server page

JTS Java TransactionService

JVM Java virtual machine

LAN local area network

LC Lotus DominoConnector

LDAP Lightweight DirectoryAccess Protocol

LEI Lotus EnterpriseIntegrator for Domino

LS:DO LotusScript DataOption

LSX LotusScript Extension

281

Page 302: Using VisualAge for Java To Develop Domino Applications

MAPI messaging applicationprogram interface

MIME Multipurpose InternetMail Extension

MTA message transfer agent

NC network computer

NCF network computingframework

NDS NetWare DirectoryService

NetBIOS Network BasicInput/Output System

NNTP NetNews TransferProtocol

NOI Notes object interface

NOS Notes object store

NT Microsoft Windows NT(new technology)

ODBC open databaseconnectivity

OLAP online analyticalprocessing

OLE object linking andembedding

OLTP online transactionprocessing

OMG Object ManagementGroup

ORB object request broker

PC personal computer

PIM personal informationmanager

POP Post Office Protocol

RAD rapid applicationdevelopment

RMI remote methodinvocation

RPC remote procedure call

RSA Rivest Shamir Adleman

SDK software developer's kit

SET secure electronictransaction

SMTP Simple Mail TransferProtocol

SNMP Simple NetworkManagement Protocol

SMTP Simple Mail TransferProtocol

SQL structured querylanguage

SSL secure sockets layer

TCP/IP Transmission ControlProtocol/InternetProtocol

URL uniform resourcelocator

WAN wide area network

WAS WebSphere ApplicationServer

XML extended markuplanguage

282 Using VisualAge for Java to Develop Domino Applications

Page 303: Using VisualAge for Java To Develop Domino Applications

Index

Symbols$$Return 231$$WebClient 134<applet> 10@Command 132@Commands 37@DbLookup 139@Functions 36@GetDocField 139@IsDocBeingLoaded 135@IsDocBeingSaved 135@IsMember 134@IsNewDoc 135@Name 134@NewLine 136@Prompt 37@Subset 139@URLOpen 231@UserName 134@UserRoles 134[CN] 134[Compose] 132[PO Creators] 124, 138, 231[PO Evaluators] 124, 137

Numerics8080 port number 113

Aabstract window toolkit

See AWTaccess control list

See ACLAccess Modifiers 153Access with getter and setter methods option 153,159ACL 121ActionEvent 176ActionListener 172, 176actionPerformed method 176addActionListener method 178AddDialog class 160addItem method 159, 175addNewLine method 136agent

© Copyright IBM Corp. 1999

and VisualAge for Java 98, 234compared to servlet and CGI 235debugging 105, 202, 207DominoAgent 98in Domino 35, 234manager in Domino 204multi-class 217PreparePOforEvaluator 201running natively in Domino 217structure 57test run log 206writing 58, 61

AgentBase class 58, 108AgentContext document 99, 104, 207, 210AgentRunner 67, 99, 105, 202, 207AgentRunner.nsf 99alias 66align method 157, 158All new and modifed documents since last run op-tion 104Allow multiple values option 135, 139AMgr_DocUpdate EventDelay 204AMgr_DocUpdateAgent MinInterval 204Anonymous access 124appearance of form 128applet

a Domino sample 52and Domino 51, 233and Domino Access Builder 262and Notes client 200basic sample 9debugging 96DominoApplet 86enabling in Domino 52enabling the workstation 53export from VisualAge for Java 193HTML tag 10including in Domino 52, 53, 98, 194initial parameters 196Java definition 7parameters 55, 56, 185, 196POApplet 145ProductList 251test 181viewer 6writing 8, 51

Applet class 8

283

Page 304: Using VisualAge for Java To Develop Domino Applications

AppletBase class 51, 88, 89, 233application, Java definition 10archive attribute 10array 171ascending sort 138attribute 4, 5, 55authenticate method 221authentication 122Author access 121automatic code completion 70Automatically refresh fields option 143availability 31AWT 6, 81

Bback-end class 37backup 31BASIC 37basic object adapter

See BOAbean

classification 82generator 243in Domino Access Builder 241palette 162

behavior 4BOA 20BorderLayout 267BoxLayout 267breakpoint 79, 106, 189, 192, 209business rule

client 181enforcement 167server 210

BusinessRules class 168, 214BusinessRulesServer class 169BusinessRulesServer_Skel class 183BusinessRulesServer_Stub class 183button

bean 162hotspot 132

CC++ and Java 3CAB file 55CABBASE 55CardLayout 267Catalog

class 164Interface form 132, 231view 130

cc:Mail 31certificate 30CGI 235check method 169, 171, 172, 214class

AddDialog 160AgentBase 58, 108and agent 217Applet 8AppletBase 51, 88, 89, 233BusinessRules 168, 214BusinessRulesServer 169BusinessRulesServer_Ske 183BusinessRulesServer_Stub 183Catalog 164Connection 220CreditRule 214DebugAgentBase 105, 108, 202, 234DiscountRule 171DominoAgent 101DominoConnection 46DominoDatabaseMetaData 46DominoDriver 46DominoPreparedStatement 46DominoResultSet 46DominoResultSetMetaData 46DominoStatement 46DriverManager 18HttpServlet 12, 110LCConnection 48LCCurrency 48LCDatetime 48LCDatetimeParts 48LCFieldList 48LCSession 48LCStream 48Naming 181Newsletter 98NotesAppletContext 68NotesFactory 63, 165NotesThread 58Object 5PO 159POApplet 172POItem 150PreparePOforEvaluator 202, 210, 215

284 Using VisualAge for Java to Develop Domino Applications

Page 305: Using VisualAge for Java To Develop Domino Applications

ProductDialog 257ProductList 257RichTextItem 136ServletRequest 12ServletResponse 12Session 90StatusServlet 220StringTokenizer 157SubmittedPO 213UnicastRemoteObject 169unresolved 160

Classpath 229client component in CORBA 19code

assist 80attribute 10connection 83generation 256stepping 191

collaboration 28COM 31Common Gateway Interface

See CGICommon Object Request Broker Architecture

See CORBAcompanyName shared field 125comparizon of agent, servlet, and CGI programs235compilation , incremental 70compiler, RMI 24component, connecting 163Compose the class visually option 101composite bean 83Computed for display option 125, 139computing formula 135configuration of IIOP in Domino 49connectCORBA method 89connecting the components 163connection

class 220in VisualAge for Java 83specification bean 245with a database 17

constructor 5, 84, 154, 159, 161, 165, 169, 170convention, Java method name 203CORBA

and Domino 29, 39, 41, 233and the sample application 120ensuring a single user login 186

implementation of the Catalog class 165presentation 18

Create a new constructor option 155create documents with this form option 138createBody method 224createGUI method 177createHeader method 222createNewsletter method 103createSession method 62createSessionWithIOR method 63credit rule 213CreditRule class 214customization 14customized bean 241

Ddata, unstructured 30database

access in VisualAge for Java 71bean 245connection object 17connection with JDBC 220creation in Domino 123in Domino 33management system

See DBMSDebugAgentBase class 105, 108, 202, 234debugger 6, 70, 79, 188debugging

Domino agent 105, 202, 207, 234Domino applet 96Domino servlet 111, 226

DECSdescription 31Domino feature 29presentation 38

default read access for documents created with thisform option 137DemoServlet 13Depositor access 121Designer access 121, 125designing Web forms 128destroy method 9, 13, 62, 221development environment in Domino 31diiop task 43diiop_ior.txt 96, 186directory and Domino 30DiscountRule class 171

285

Page 306: Using VisualAge for Java To Develop Domino Applications

DisplayItemList subform 141dispose method 162doclink 98document

a Domino object 34and Computed for display field 125bean 245used as test case 129

doGet method 12, 110, 224, 226domain name 123Domino

access builder library 242Administrator R5 28agent creation 204Agent manager 204AgentRunner 67and agent 234and applet 233and CORBA 39, 41, 233and Java 39and security 121and servlet 234and VisualAge for Java 85, 234, 237applet installation 52, 98Application Server R5 28database 33, 123debugging a servlet 111, 226debugging an agent 105, 202, 207debugging an applet 96deploying servlets 228Designer R5 28, 39, 128developping a servlet in VisualAge for Java 109developping an agent in VisualAge for Java 98developping an applet in VisualAge for Java 86Directory 49document 34enabling Java applet 53IIOP server set up 182implementing servlet 114including an applet 52, 53, 194Initialization file 49Java agent creation 59Java library 43, 247Java Toolkit 67LotusScript 36object 39, 41, 44ODBC driver 16R4.6 agent development 99R5 agent development 100

running the debugged agent 217server family 27servlet installation 65servlet manager in R4.6 64servlet manager in R5.0 65servlet sample 63set up development in VisualAge for Java 87testing the elements 143using CORBA classes 55writing a servlet 62writing an agent 58writing an applet 51

Domino Access Builderand the Domino Java class library 247library 244main components 242presentation 241sample application 251

Domino Driver for JDBC 16, 44, 219, 220, 229,237Domino Enterprise Connection Services

See DECSDominoAgent agent 98DominoAgent class 101dominoagentpackage package 101DominoApplet applet 86dominoappletpackage package 88DominoConnection class 46DominoDatabaseMetaData class 46DominoDriver class 46DominoEnableJavaServlets 65DominoPreparedStatement class 46DominoResultSet class 46DominoResultSetMetaData class 46dominoservletpackage package 110DominoStatement class 46doPost method 12do-while clause 37downloading the sample application 265DriverManager class 18dynamic code loading 25

EEditable option 139EditItemList subform 138editor

access 121source code 70

286 Using VisualAge for Java to Develop Domino Applications

Page 307: Using VisualAge for Java To Develop Domino Applications

visual composition 71, 81elapsed time 204embededding element 132enabling

Java applet 52Java servlet support 64, 66JavaScript 124

ensuring a single user login for a CORBA session186Enterprise JavaBean

See EJBenterprise resource planning

See ERPerror handler bean 245eTrade Vendor application 117eTradeVendor packages 149event

JavaBean 14triggering LotusScript program 38

Event-to-Code connection 163Event-to-Method connection 83, 261Event-to-Property connection 83examining field value 191exception 110, 193executeQuery method 223explorer, repository 73exporting

class files 97Java code 77

expression in Java 191extended markup language

See XMLextension 37

Ffield

a Domino document object 34Computed for display 125examining value 191refreshing 143shared 125

file transfer protocolSee FTP

fillEmployeeList method 90final 5fix-on-save 70FlowLayout 267form 34, 127, 128, 132, 133, 230

form bean 245format of code 70formatMsgWithDocslinks method 103formswitch bean 246formula

computing 135language 36

for-to clause 37frameset 36free-form surface 92, 257front-end user interface class 37fully qualified typename 152function in Domino 36

GGeneral Inter-ORB Protocol

See GIOPgenerated code 84generated customized bean 246generated Domino bean 243GET 12get--- method 223getAgentContext method 103getAgentOutput method 58getConnection method 18getDatabase method 90get---Document method 90getDocumentbyKey method 166getEffectiveUserName method 103getEmployeeFirstName method 91getFirstDocument method 91getIOR method 63, 186getItem method 166getItems method 222getItemsOrdered method 173getItemValue--- method 90getItemValueType method 166getQuantitiesOrdered method 174getSession method 42, 51, 56, 103getSubtotal method 160getter method 14, 153getTotal method 156, 160getUnprocessedDocuments method 103getView method 90, 165GIOP 20GridBagConstraints 268GridBagLayout 267GridBagLayout layout manager 177

287

Page 308: Using VisualAge for Java To Develop Domino Applications

GridLayout 267GUI, creation 177

HHEAD 12Header subform 126height attribute 10helper method 157Hide paragrah from Notes R4.6 or later option 197Hide paragrah from Web browsers option 197Hide When tab 140hotspot 132HTTP

Domino task 30password 221

HttpServer 112, 227HttpServlet class 12, 110HttpServletRequest 13HttpServletResponse 13, 226Hypertext Markup Language

See HTMLHypertext Transfer Protocol

See HTTP

IIBM Java implementation 73IBM Redbooks Web site 265IBM VisualAge for Java 39IBM’s WebSphere Application Server 66IDE and LotusScript 38identifier 34, 139IDL 19, 42If Documents Have Been Created or Modified option204IIOP 20, 49, 249IMAP4 31implementation repository 20imported Java 59importing

an applet 53Java code 74

incremental compilation 70InfoBus 42inheritance 5init method 8, 12, 62, 84, 111, 220initConnections method 84initialization

argument 66

file 49initialize method 84initList method 175, 176inner class 71inserting a subform 132inspector 79, 186installation

Domino applet 52, 98Domino servlet 65

instance 4integrated development environment

See IDEinterface

ActionListener 172definition 5java.io.Serializable 181java.rmi.Remote 22, 168POChecker 168Servlet 12SingleRule 167, 168, 172

interface definition languageSee IDL

Internet Inter-ORB ProtocolSee IIOP

introspection 14invalidData method 164IOException 110IOR 63, 186ivj.dat 73IVJAgentRunner.jar 99

JJApplet 83JAR file 55Java

agent creation 59and Domino 39and Domino Objects 31class library 6, 73definition 3Domino agent sample 58Domino console 105enabling applet in Domino 52evaluating expression 191interpreter 184method name convention 203performance 157program types 7

288 Using VisualAge for Java to Develop Domino Applications

Page 309: Using VisualAge for Java To Develop Domino Applications

servlet support enabling in Domino 64, 66writing the agent code 61

Java database connectivitySee JDBC

Java Development KitSee JDK

Java naming and direcory interfaceSee JNDI

Java server pageSee JSP

Java Servlet Development KitSee JSDK

Java Transaction ServiceSee JTS

Java virtual machineSee JVM

java.applet package 6, 8java.awt package 6java.exe 184java.io package 6java.io.Serializable interface 181java.lang package 6java.net package 6java.rmi.Remote interface 22, 168java.rmi.RemoteException 168java.sql package 6java.sql.Driver package 46java.util package 6JavaBean

and VisualAge for Java 71definition 14

JavaScript 31, 39, 124, 137, 198JavaUserClasses 229javax.servlet package 12javax.servlet.http package 12javax.servlet.http.HttpServlet 220JDBC

connection to a Domino database 220Domino driver 44ODBC bridge 16package 6presentation 15URL 18using the server ID 120writing a program 17

JdbcDomino.jar 229JDBC-ODBC bridge 16JDialog 257JDK 6

JFC 73JFrame 83JLabel 258JPanel 83, 257JS Header 198JSDK 11, 110, 219jsdk.jar 110JTextField 258JVM

and Domino Designer 39and servlets 11definition 4

Kkeyword change 135

Llanguage

formula 36national 71

layout manager 177, 267LC Java classes 47LCConnection class 48LCCurrency class 48LCDatetime class 48LCDatetimeParts class 48LCFieldList class 48LCSession class 48LCStream class 48LDAP 30library, Domino Access Builder 244life-cycle 236Lightweight Directory Access Protocol

See LDAPlinking to an applet 53login 230Login form 230logon specification bean 246lookup method 181Lotus Domino Connector

See LCLotus Domino Toolkit for Java/CORBA

See Domino Java ToolkitLotus Enterprise Integrator for Domino

See LEILotus Notes

classe 38formula language 36

289

Page 310: Using VisualAge for Java To Develop Domino Applications

lotus.domino package 39, 44, 58, 87lotus.domino.corba package 44, 87, 233lotus.jdbc.domino package 46lotus.lcjava package 48lotus.notes package 39, 58LotusScript

agents 234and Domino Objects 31description 37Domino development language 36

LotusScript Data OptionSee LS:DO

LotusScript ExtensionSee LSX

lower case letter convention 203LSX 36, 38

Mmacro 36Manager access 121, 125MAPI 31memory address 151, 158message

transfer agentSee MTA

messaging 28, 30messaging application program interface

See MAPImethod

actionPerformed 176addActionListener 178addItem 159, 175addNewLine 136align 157, 158authenticate 221check 169, 171, 172, 214connectCORBA 89createBody 224createGUI 177createHeader 222createNewsletter 103createSession 62createSessionWithIOR 63definition 4destroy 9, 13, 62, 221dispose 162doGet 12, 110, 224, 226doPost 12

executeQuery 223fillEmployeeList 90formatMsgWithDocslinks 103get--- 223getAgentContext 103getAgentOutput 58getConnection 18getDatabase 90get---Document 90getDocumentbyKey 166getEffectiveUserName 103getEmployeeFirstName 91getFirstDocument 91getIOR 63, 186getItem 166, 222getItemsOrdered 173getItemValue--- 90getItemValueType 166getQuantitiesOrdered 174getSession 42, 51, 56, 103getSubtotal 160getter 14, 153getTotal 156, 160getUnprocessedDocuments 103getView 90, 165init 8, 12, 62, 84, 111, 220initConnections 84initialize 84initList 175, 176invalidData 164lookup 181newInstance 63next 223nextToken 157notesAppletEnd 51notesAppletInit 51, 173, 180notesAppletStart 51notesAppletStop 51NotesMain 58, 103, 203, 210, 214openSession 89paint 9rebind 170service 12, 62setItems 198setLayout 268setter 14signature 155sinitThread 62start 9

290 Using VisualAge for Java to Develop Domino Applications

Page 311: Using VisualAge for Java To Develop Domino Applications

stermThread 62stop 9super 154toString 151, 158validate 175

MIME 31model

and JDBC 15bean 244

MTA 31multi-class agent 217multiline text field 136Multipurpose Internet Mail Extension

See MIMEmultithread 57, 234

NNaming class 181naming registry 24national language 71navigator

bean 246in Domino 34

ncso.cab 233NCSO.jar 42, 44, 55ncso.jar 233ncsoc.jar 233NDocument 258New Line option 135newInstance method 63Newsletter class 98next method 223nextToken method 157NLogonSpec 257NOI 40NOI_COOKIE 57NOI_COOKIE_URL parameter 186NOI_IOR 56NOI_IOR parameter 96, 186nonvisual bean 82NORB.DLL 44Notes client 28Notes object interface

See NOI and also DOMnotes.ini 43Notes.jar 43, 44, 87NotesAppletContext class 68notesAppletEnd method 51

notesAppletInit method 51, 173, 180notesAppletStart method 51notesAppletStop method 51NotesException 166NotesFactory class 63, 165NotesMain method 58, 103, 203, 210, 214NotesThread class 58NSCO.jar 87, 110NTreeTable 257NTreeTableModel 257

O-O option 157object

interfaceSee also NOI

model and Domino 31store 30

Object class 5Object Management Group

See OMGobject request broker

See ORBobtaining an unique identifier 139obtainning the IOR 186ODBC 16, 38OLE 31OMG 18onClick event 137online analytical processing

See OLAPonline transaction processing

See OLTPopen database connectivity

See ODBCopenSession method 89ORB 20, 39

in Domino 42outline 35, 126OutputStream 226OverlayLayout 268

Ppackage

applet 6dominoagentpackage 101dominoappletpackage 88dominoservletpackage 110

291

Page 312: Using VisualAge for Java To Develop Domino Applications

I/O 6in Java 6java.applet 8java.awt 6java.net 6java.sql 6java.sql.Driver 46javax.servlet 12javax.servlet.http 12language 6lotus.domino 39, 44, 58, 87lotus.domino.corba 44, 87, 233lotus.jdbc.domino 46lotus.lcjava 48lotus.notes 39, 58used in the sample application 149utility 6

padding 154page 35paint method 9palette 162param attribute 10parameter

applet 55, 185, 196connection 84

password 221PATH environment variable 99performance 157, 158persistence 14ping command 111PO class 159POApplet 145POApplet class 172POChecker interface 168POItem class 150POP3 31port 8080 113POST 12Post Office Protocol

See POP3PreparedPO view 140PreparedStatement 223PreparePOforEvaluator agent 201PreparePOforEvaluator class 202, 210, 215PreviousOrder view 138PrintInfo 109PrintWriter 58private 153private attribute 5

product document 129Product form 127ProductDialog class 257ProductList applet 251ProductList class 257project 70, 72, 151properties

applet 55box 55JavaBean 14servlet 66

Property-to-Property connection 83, 258, 260, 261protected attribute 5proxy 24public attribute 5, 153PurchaseOrder form 133

Qquickform bean 246

RReader access 121, 130real-time connection 38rebind method 170refreshing field 143registering a Domino servlet 65registering object to the RMI registry 170relation , universal 47remote

method call 181method invocation

See RMIobject 22session 165

repositoryand VisualAge for Java 70, 72CORBA implementation 20definition 73explorer 73

RichTextItem class 136RMI

and the sample application 120business rule server 167client 181compiler 24connecting the security manager 215implementing in the agent 215naming registry 24

292 Using VisualAge for Java to Develop Domino Applications

Page 313: Using VisualAge for Java To Develop Domino Applications

presentation 21registration of objects 170registry 180, 215security manager 181separating rules from server 168set up 182start registry 184stub and skeleton 183writing a program 22

rmic 24rmiregistry 184, 200RMISecurityManager 24roles

determination 134in ACL 121

RPC 249ruler 128rules, business 167

SS/MIME 30sample application

downloading 265ressources creation 125

SaveOptions editable text field 230scrapbook 78, 186, 250Search engine 30secure sockets layer

See SSLsecurity

agent and servlet comparizon 236and Domino 30, 121and Domino Driver for JDBC 229and Domino R5 client ORB 42and Web users 124in a form 137level 121RMI manager 24, 181, 215

serializable 181server

CORBA component 20ID 120name 123sockets 120

ServerTasks command 49service method 12, 62servlet

and Domino 234

basic sample 13compared to agent and CGI 235debugging 111, 226deploying on a Domino server 228description 11developping in VisualAge for Java 109Domino R4.6 manager 64Domino R5.0 manager 65Domino sample 63enabling in Domino 64, 66implementing in Domino 114installation in Domino 65interface 12properties 66registering in Domino 65runner 111, 227StatusServlet 219writing 11, 62

servlet.cnf 65ServletException 110ServletRequest class 12ServletResponse class 12servletrunner 111servlets.properties 66, 229session

bean 244class 90

session management 241setItems method 198setLayout method 268setter method 14setting

applet parameter 55Domino servlet properties 66field name 152

sharedfield 125view 130

Show values in this column as links option 131signature of a method 155Simple Mail Transfer Protocol

See SMTPSingleRule interface 167, 168, 172sinitThread method 62skeleton 20, 183SmartGuide 73, 243SMTP 31sockets 120software developer’s kit

293

Page 314: Using VisualAge for Java To Develop Domino Applications

See SDKsource code editor 70SQL and Java 15SQLJ 239SSL 30, 122start method 9Statement 223static 4StatusServlet class 220StatusServlet servlet 219stepping through the code 191stermThread method 62stop method 9stored procedure 239StringBuffer 158StringTokenizer class 157structured query language

See SQLstub 19, 183subform 126, 138, 141SubmittedPO class 213Sun class libraries 73super method 154Swing 71, 81

Ttable

controling the form appearance 128properties box 128

tearoff 258template 34test Domino elements 143testing an applet 181text field multiline 136TextField bean 162this prefix 156three-tier model 15token 157toString method 151, 158transaction

logging 31treetable bean 246two-tier model 15type of JDBC driver 16

UUniCastRemoteObject 23UnicastRemoteObject class 169

uniform resource locatorSee URL

unique identifier 139universal relation 47unresolved class 160unstructured data 30URL

and Domino 32extension mapping 66for JDBC 18

Use JavaScript when generating pages option 124user

authentication 221, 230ID 121login 186role determination 134

Vvalidate method 175variable 4view 34, 130, 138, 140view bean 245Visible Variables pane 191visual bean 82, 246visual composition editor 71, 81, 161VisualAge for Java

and Domino 85and Domino agent 98, 234and Domino application 237and the servlet runner 227connection 83developping a Domino applet 86developping a Domino servlet 109exporting files 193presentation 69set up for Domino development 87test of an applet 181Version 3.0 239

VisualServlet 83

WWeb

designing form 128Web user

and security 124What should this agent run? option 59Which document(s) should it act on ? option 104Who can Run unrestricted Java/Javascript option

294 Using VisualAge for Java to Develop Domino Applications

Page 315: Using VisualAge for Java To Develop Domino Applications

182width attribute 10workaround to unresolved class 161workbench 71workflow 28, 30, 242workspace 71

Xx.400 31X.509 30

ZZIP file 55

295

Page 316: Using VisualAge for Java To Develop Domino Applications

296 Using VisualAge for Java to Develop Domino Applications

Page 317: Using VisualAge for Java To Develop Domino Applications

© Copyright IBM Corp. 1999 297

ITSO Redbook Evaluation

Using VisualAge for Java To Develop Domino ApplicationsSG24-5424-00

Your feedback is very important to help us maintain the quality of ITSO redbooks. Please completethis questionnaire and return it using one of the following methods:

• Use the online evaluation form found at http://www.redbooks.ibm.com/• Fax this form to: USA International Access Code + 1 914 432 8264• Send your comments in an Internet note to [email protected]

Which of the following best describes you?_ Customer _ Business Partner _ Solution Developer _ IBM employee_ None of the above

Please rate your overall satisfaction with this book using the scale:(1 = very good, 2 = good, 3 = average, 4 = poor, 5 = very poor)

Overall Satisfaction __________

Please answer the following questions:

Was this redbook published in time for your needs? Yes___ No___

If no, please explain:

What other redbooks would you like to see published?

Comments/Suggestions: (THANK YOU FOR YOUR FEEDBACK!)

Page 318: Using VisualAge for Java To Develop Domino Applications

Printed in the U.S.A.

SG24-5424-00

Using

VisualA

gefor

JavaT

oD

evelopD

omin

oA

pplicationsS

G24-5424-00