Legal Notices. The information contained in this documentation is subject to change without notice

HP-AS Developer's Guide Legal Notices The information contained in this documentation is subject to change without notice. Hewlett-Packard makes no ...
Author: Lorin Watts
1 downloads 2 Views 2MB Size
HP-AS Developer's Guide

Legal Notices The information contained in this documentation is subject to change without notice. Hewlett-Packard makes no warranty of any kind with regard to this material, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. Hewlett-Packard shall not be liable for errors contained herein or for incidental or consequential damages in connection with the furnishing, performance, or use of this material. Java™ and J2EE is a U.S. trademark of Sun Microsystems, Inc. Microsoft® and Windows NT® are registered trademarks of Microsoft Corporation. Oracle® is a registered U.S. trademark and Oracle8™, Oracle8 Server™ Oracle8 Enterprise Edition™ are trademarks of Oracle Corporation. IONA and Orbix are registered trademarks of IONA® Technologies. CORBA and the Object Management Group (OMG) are trademarks or registered trademarks of the Object Management Group, Inc in the US and other countries. SonicMQ® is a registered trademarks of Sonic Software Corporation in the U.S. and other countries. Unix is used here as a generic term covering all versions of the UNIX® operating system. UNIX is a registered trademark in the United States and other countries, licensed exclusively through X/Open Company Limited. SequeLink® is a registered trademark of MERANT Solutions Inc. Software Version HP Application Server 8.0 HP RadPak 1.0 Restricted Rights Legend Use, duplication, or disclosure is subject to restrictions as set forth in contract subdivision (c)(1)(ii) of the Rights in Technical Data and Computer Software clause 52.227-FAR14. Hewlett-Packard Company 3000 Hanover Street Palo Alto, CA 94304, USA © Copyright 1999-2001 Hewlett-Packard Company

ii

HPAS01DV10-11/13/01

Contents

Content Preface What This Guide Contains .....................................vii Audience ................................................................vii Prerequisites...........................................................vii Organization..........................................................viii Conventions Used .................................................viii Additional Documentation ......................................ix Contact Us...............................................................ix

Chapter 1: Introduction Overview..................................................................1 HP-AS Editions....................................................1 Developer Tools...................................................1 Third-Party Software............................................2 J2EE Overview ........................................................3 J2EE Multi-Tier Applications ..............................4 Application Scenarios ..........................................5 J2EE Application Technologies...........................7 Packaging J2EE Applications ............................10 J2EE Platform Roles ..........................................12 MVC Design Model...............................................13 Struts ..................................................................14

Chapter 2: Getting Started Overview................................................................15 Viewing HP-AS Trail Maps...................................15 Starting HP-AS Trail Maps................................16 Starting HP-AS ......................................................16 Defining HP-AS's Classpath ..............................16 Starting HP-AS Using a Script File ...................17 Contacting HP-AS..............................................18 HP-AS Modes ........................................................19 HP-AS System Text Console Mode...................19 HP-AS System Console Mode ...........................20 Setting HP-AS Logging Levels..............................23 Configuration Files ................................................24 HP-AS Proprietary Deployment Descriptors .....26

HPAS01DV10-11/13/01

Chapter 3: Assembling and Deploying J2EE Applications Overview................................................................27 Assembling an Enterprise Application...................27 Resolving components’ class dependencies.......28 Deploying an EAR .................................................30 Deploying an EAR using RadPak ......................31 Manually Deploying an EAR.............................33 Deploying Using the Deploy Command ............34 Drag-and-Drop Deployment ..............................35 Deploying Standalone JARs WARs and RARs .....37 Verifying a Deployed Application .........................38 Inter-Application Communication .........................39 Example .............................................................39 Deployment Checklist............................................39

Chapter 4: Developing Web Components Overview................................................................41 Writing Servlets .....................................................41 Common Servlet Structure.................................42 Using HttpServlet...............................................43 Request and Response Interface.........................44 Writing Output ...................................................45 Servlet Tutorial ......................................................46 Part 1 – Creating a Web Application Directory .46 Part 2 – Creating the Servlet ..............................46 Part 3 – Creating the Deployment Descriptor ....47 Part 4 – Deploying the Web Application ...........48 Part 5 – Contacting the Application ...................49 Writing JSPs...........................................................50 Constructing a JSP .............................................50 Packaging JSPs ..................................................51 JSP Directive Elements ......................................51 JSP Action Elements..........................................52 JSP Scripting Elements ......................................56 JSP Object Scope ...............................................57 Implicit JSP Objects...........................................58 JSP Web Application Tutorial ...............................59

iii

HP-AS Developer's Guide

Part 1 – Creating a Web Application Directory .59 Part 2 – Creating the JSP....................................60 Part 3 – Creating the Deployment Descriptor ....60 Part 4 – Deploying the Web Application ...........61 Part 5 – Contacting the Application ...................61 Writing JSP Tag Extensions...................................62 Creating a Tag Handler ......................................62 Creating a TLD ..................................................63 Using a Custom Tag...........................................64 Taglib Web Application Tutorial ...........................65 Part 1 – Creating a Web Application Directory .65 Part 2 – Creating the Tag Handler......................65 Part 3 – Creating the TLD..................................66 Part 4 – Creating the JSP Page...........................67 Part 5 – Creating the Deployment Descriptor ....67 Part 6 – Deploying the Application....................68 Part 7 – Contacting the Application ...................68 Adding Security to a Web Component ..................69 Roles ..................................................................69 Authentication....................................................70 Security Constraints ...........................................70 Form-based Security Tutorial ................................71 Part 1 – Registering Your Credentials................71 Part 2 – Creating a Web Application Directory .71 Part 3 – Creating the Application Source...........72 Part 4 – Creating the Deployment Descriptor ....76 Part 5 – Deploying the Application....................78 Part 6 – Contacting the Application ...................78

Chapter 5: Developing EJB Components Introduction............................................................83 CORBA and the Interoperable Naming Service 83 Iona Orbix2000 Integration................................84 EJB CMP 2.0 .....................................................84 Local Interfaces..................................................85 Home Methods...................................................85 Improved support for JMS and Message Driven Beans..................................................................85 Enhanced Deployment Capabilities ...................85 HP RadPak .........................................................86 HP Deployment Descriptor ....................................87 Aliasing the Name for an EJB............................87 Assembly and Deployment ................................87 Stateless Session Beans..........................................87 Coding Basics ....................................................87 Home and Remote Interfaces .............................88 Stateless Session Bean Configuration ................89 Stateful Session Beans ...........................................91 Coding Basics ....................................................91 Home and Remote Interfaces .............................91 HP-AS Stateful Session Bean Settings...............91 HP EJB JAR Deployment Descriptor ................92 Entity Beans ...........................................................92

iv

Coding Basics ....................................................92 Home and Remote Interfaces .............................93 Design Considerations .......................................95 EJB 2.0 CMP .........................................................96 The EJB QL Language.......................................97 Finder and Select Methods.................................97 Read-Only Entity Bean ......................................99 Deploying an Entity Bean ..................................99 Message-Driven Beans ........................................100 Coding Basics ..................................................100 Message-Driven Beans in HP-AS ....................101 Message-Driven Beans and EJB Security........102 MDB Deployment............................................102 Accessing Enterprise Java Beans Using Local Interfaces..............................................................102 Coding Basics ..................................................102 Looking Up an EJB With a Local Interface .....103 EJB Security.........................................................103 EJB Security at Run time .................................103 Using the HP-AS Security Framework with EJBs .................................................................104 RadPak Code Generation .....................................104 Co-Located Client Access....................................105 Remote Client Access ..........................................106 Application Client Container Access ...............106 Client Access Outside the Application Client Container..........................................................107 Access with the HP JNDI SPI..........................107 Access with the Conventional JNDI SPI..........108 Inter-Container EJB Access .............................109 Firewall Issues .....................................................109 Remote Client using CORBA ..........................109 Failover and the Load Balance Broker.................109 Configuration Procedure ..................................110

Chapter 6: Developing Application Clients Overview..............................................................111 Assembling and Deploying an Application Client111 Using HP RadPak ............................................112 Manual Assembly of Application Client..........117 Running the Application Client Container.......117 Tailoring the Application Client Container......118 Contacting Remote EJB References ....................118

Chapter 7: Connecting to Resources Overview..............................................................119 Database Connections ..........................................119 Setting Up a Datasource...................................119 Getting a Connection .......................................122 Mail Session Connections ....................................123 Getting a Mail Session .....................................123

HPAS01DV10-11/13/01

Contents

URL Connections.................................................123 Getting a URL..................................................123 Creating a Custom Resource Provider .................124 Getting a Connection to a Custom Provider.....125

Chapter 8: Using J2EE Services Overview..............................................................127 Using JAXP .........................................................127 Extending the JAXP Service............................127 Using Parsers ...................................................128 Requesting a Parser or Transformer.................129 Service Configuration ......................................144 There are also configuration attributes for each tag based on its type (DocumentBuilder or SAXParser). Attributes Specific to DocumentBuilder parsers...............144 Attributes Specific to DocumentBuilder parsers145 Attributes Specific to SAXParser parsers ........145 Custom Attributes ............................................146 Sample Configuration File ...............................146 JAXP Service Management .............................147 Adding a New DocumentBuilder, SAXParser or Transformer Node to the Configuration File....148 Using Connectors.................................................149 Resource Adapter Archives..............................149 Setting Up the Connector Service ....................150 Loading the Connector Service........................150 Configuring Adapters.......................................152 Using JDBC in HP-AS.........................................156 Configuring Adapters in the hp-ra.xml File .....157 Deploying RAR Files Through the J2EE Partition Service...............................................157

Chapter 9: Using HP-AS Base Services Overview..............................................................161 URIRegistry Service ............................................161 Implementing a URIRegistry ...........................162 Using the Registry Service...............................162 Registry Service Configuration........................170 File Store Configuration...................................173 Managing the URIRegistry Service .................174

Chapter 10: Advanced Services Overview..............................................................179 Using the XML Transformation Framework .......179 XTF Convenience Components .......................180 XTF Configuration...........................................184 Core Transformers (Transformlets) .................186 XSLTTransformlet...........................................186 XTF Usage Example........................................189 Internationalizing Applications............................189

HPAS01DV10-11/13/01

Outgoing Data ..................................................189 Incoming Data (from the Client to the Servlet Container) ........................................................192

Chapter 11: HP-AS Developer Tools Overview..............................................................195 HP RadPak ...........................................................195 Overview..........................................................195 RadPak Features...............................................195 RadPak’s Main Interface..................................196 HP RadPak Configuration Options ......................197 Servers .............................................................197 External Application Mapping Utility..............198 Map Extensions to External Applications ........198 Edit External Application Mappings................201 Remove External Application Mappings .........202 Templates.........................................................202 Datasources ......................................................203 Connections......................................................205 JAR Management.................................................206 RadPak File Browser .......................................206 Drag-and-Drop JAR Management ...................208 The Search Utility ............................................208 Class Indexing Utility ......................................210 J2EE Component Verifier ................................212 Remote File System .........................................213 XML Schema Editor ........................................215 XML Editor Views...........................................215 Manifest Editor ................................................216 Enterprise ARchive Projects (EARs) ...................218 EAR Editor.......................................................218 EAR Assembly.................................................222 Enterprise JavaBean Projects (EJBs) ...................222 New EJB Project Wizard .................................222 EJB Editor........................................................224 EJB Discovery .................................................235 Copying Enterprise JavaBean (EJB) Beans .....236 Web Archive Projects (WAR) .............................237 WAR Editor .....................................................237 The WAR editor XML view displays the project's web.xml file within RadPak's XML Schema Editor, allowing direct editing of the XML.................................................................238 Click Save on the main toolbar, or select File | Save to save changes and reformat the XML...238 Sharing Project Folders....................................239 Developing a Simple Web Application............240 Ant Projects..........................................................242 Jakarta Ant .......................................................242 Ant Editor.........................................................242 Custom Ant Tasks............................................243 RadPak Code Generation .....................................249 Enterprise JavaBean (EJB) Projects.................249

v

HP-AS Developer's Guide

Web ARchive (WAR) Projects ........................250 Enterprise ARchive (EAR) Projects.................250 Code Generator Execution ...............................250 Command Line Execution ...............................250 Deployment..........................................................252 Copy and Paste Deployment ............................252 Menu Deployment............................................252 Drag and Drop Deployment .............................252 Generation and Deployment ............................253 Removing a Deployed Application ..................253 HP WebGain Integration Plug-in and Quick Start Guide....................................................................254 Creating a Project Using the Enterprise Bean Wizard..............................................................254 Creating a Client Co-project ............................255 Configuring WebGain and HP-AS...................256 Configuring an Entity Bean With the Plug-in ..258 Deploying an EJB to the application server .....260 Debugging an EJB ...........................................260 Quick Start Guide.................................................261 Verifying Installed Components ......................261 Setting the default for HP-AS ..........................261 Creating a new EJB project..............................262 Create Enterprise Bean – Select name .............263 Setting up HP-AS deployment target properties264 Project Options.................................................265 Manage Deployment Target.............................265 Adding Simple Code........................................266 Modifying the sample client code to access HPAS ....................................................................266 Compiling and Deploying EJBs.......................267 Adding the Bank EJB JAR file ........................267 Executing the Banking Bean EJB Application.267 Starting HP-AS ................................................267 Setting Breakpoints on the calls.......................268 Starting applications.........................................268 Deployment Configuration...............................268 JSPcompile Utility ...............................................269 Defining the Environment Variable .................269 Running the Utility...........................................270 Including Pre-Compiled JSPs in an Application271

vi

Appendix A: Native Java Product Launcher Appendix B: HSQL Database Appendix C: Web Application Deployment Descriptor Appendix D: Tag Library Deployment Descriptor Appendix E: EJB Deployment Descriptor Appendix F: Connector Deployment Descriptor Appendix G: Application Client Deployment Descriptor Appendix H: Enterprise Application Deployment Descriptor Appendix I: HP-AS Proprietary Deployment Descriptors

HPAS01DV10-11/13/01

Preface What This Guide Contains The Hewlett-Packard Application Server (HP-AS) Developer’s Guide provides detailed information on how to develop and deploy Java 2 Enterprise Edition (J2EE)-based applications when using HP-AS. It also points out many precepts and best practices that should be considered when designing web applications. The guide does not discuss the HP-AS architecture in detail, but does mention architectural constructs where applicable. Users interested in detailed architectural information should consult the HP-AS Technical Guide. Web applications hosted in HP-AS may use many different application components. For example, an application may use application clients, Applets, EJBs, servlets, JavaServer Pages (JSPs) XHTML, XML, DHTML, and client-side Java Script. In addition, Java Technology offers other technologies that are leveraged, such as JDBC for connecting to databases, JNDI for creating a naming environment, or JMS for incorporating messaging. While this guide discusses many of these technologies, it does not attempt to address all of the fundamentals of these components. However, basic concepts are provided where necessary. Because HP-AS is primarily focused on hosting J2EEbased applications, which utilize Java Technology, the guide focuses on these technologies in more detail.

Audience This guide is most relevant to application developers interested in creating J2EE-based applications. The guide is also useful for system analysts, IT managers, and project managers who may not be familiar with J2EE components and how they are implemented.

Prerequisites The HP-AS is predominately based on Java and J2EE Technology. Familiarity with the Java programming language and a general understanding of J2EE is required to use this guide. If you are new to Java and J2EE, we encourage you to visit the Sun Microsystems web site www.java.sun.com/j2ee. This is the best source for everything Java and J2EE. In particular, you should become familiar with the J2EE 1.3 Specification, the J2EE Blueprints, the Servlet Specification, the JavaServer Pages Specification, and the Enterprise JavaBean Specification.

HPAS01DV10-11/13/01

vii

HP-AS Developer's Guide

Organization This guide contains the following chapters: •

Chapter 1, Introduction – presents a brief view of HP-AS, including three-tier web applications. The chapter also presents fundamental concepts that are important when developing J2EE applications.



Chapter 2, Getting Started – provides basic information about using HP-AS when developing applications.



Chapter 3, Deploying J2EE Applications – presents instructions on deploying J2EE enterprise applications in HP-AS.



Chapter 4, Developing Web Components – presents a detailed look at the components commonly associated with web applications. In particular, the chapter provides information on servlets, JSPs, and Custom Tag Extensions.



Chapter 5, Developing EJB Components – presents instructions on developing EJB components, including session, entity, and Message-Driven Beans (MDB).



Chapter 6, Deploying Application Clients – presents instructions on developing stand-alone application clients used in distributed applications.



Chapter 7, Connecting to Resources – presents instructions on how to connect to resource providers using JNDI from within your application components.



Chapter 8, Using J2EE Services – presents instructions on how to use J2EE services in your application. In particular, the chapter include using JAXP and connectors (JCA).



Chapter 9, Using HP-AS Base Services – presents instructions on using the HP-AS URIRegistry service.



Chapter 10, Advanced Services – presents instructions on using the HP-AS XML Transformation Framework (XTF). This chapter also includes internationalization considerations when developing applications.



Chapter 11, HP-AS Developer Tools – presents instructions on using RadPak, the WebGain plug-in, and the jspcompile utility.



Appendices – The appendices present information on the Native Java Product Launcher, HSQL Database, and all the J2EE required deployment descriptors.

Conventions Used The following conventions are used in this guide: Convention Italic

viii

Description In paragraph text, italic identifies the titles of documents that are being referenced. When used in conjunction with the Code text described below, italics identify a variable that should be replaced by the user with an actual value.

HPAS01DV10-11/13/01

Preface

Convention

Description

Code

Text that represents programming code.

Function | Function

A path to a function or dialog box within an interface. For example, “Select File | Open.” indicates that you should select the Open function from the File menu.

( ) and |

Parentheses enclose optional items in command syntax. The vertical bar separates syntax items in a list of choices. For example, any of the following three items can be entered in this syntax: persistPolicy (Never | OnTimer | OnUpdate | NoMoreOftenThan)

Note: and Caution:

A note highlights important supplemental information. A caution highlights procedures or information that is necessary to avoid damage to equipment, damage to software, loss of data, or invalid test results.

Additional Documentation In addition to this guide, the following guides are available in the HP-AS documentation set: •

HP-AS Installation Guide – provides instructions for installing HP-AS.



HP-AS Release Notes – details new features and the latest information about HP-AS.



HP-AS Technical Guide – details the architecture and configuration of HP-AS.



HP-AS Administrator's Guide – details how to configure HP-AS in your enterprise environment.



EJB Tutorials – a set of comprehensive tutorials that outline all the major features of the HP-AS EJB implementation.



HP-AS Migration Guide – details how to port applications from Total-e-Server 7.3.



HP Middleware Total-e-Transactions documentation set – a complete set of documentation that details HP Middleware's transaction software.



HP Performance Tuning Guide – details how to tune your environment and applications for optimal performance.

For additional documentation and up-to-date release information, you can access the documentation home page at the HP Middleware development gallery http://gallery.bluestone.com/scripts/SaISAPI.dll/Gallery.class/docs/index.jsp.

Contact Us Questions or comments about HP-AS should be directed to the HP-IS list server, [email protected].

HPAS01DV10-11/13/01

ix

HP-AS Developer's Guide

x

HPAS01DV10-11/13/01

Chapter 1

Introduction Overview Hewlett-Packard Application Server (HP-AS), a Netaction Product, is a Java-based middleware server comprised of Sun Microsystems' Java 2 Enterprise Edition (J2EE) technology, HP Middleware services, and many industry-leading technologies. The server provides an extensible enterprise environment that is used to create, test, and host distributed multi-tiered applications. Middleware servers, such as HP-AS, have become the platform of choice for hosting distributed applications, because they provide a neutral environment that allows developers the most flexibility when developing applications and integrating applications with legacy systems. In general, HP-AS is designed to host J2EE-based applications. J2EE-based applications are built using application components such as servlets, JavaServer Pages (JSP), Enterprise JavaBeans (EJB), and J2EE enterprise services. All J2EE technologies are built using the Java2 Standard Edition (J2SE); therefore, developers can use the full power of Java when creating their applications. Because J2EE is central to HP-AS, this Introduction contains a J2EE Overview. If you are not familiar with J2EE, you can access additional information on the java.sun.com website. In addition to J2EE technologies, HPAS supports the use of many industry standard technologies, such as XML, HTML, and CORBA. These technologies are used in conjunction with J2EE application components and are essential to many applications. Lastly, you can customize the HP-AS environment to include any functionality required by your enterprise platform or business solutions. For example, libraries can be automatically loaded by the server, making them available to applications that are hosted in HP-AS. Furthermore, you can create customized services that can be managed by HP-AS's Core Services Framework (CSF) and made available to your applications or other services that are part of the HP-AS environment.

HP-AS Editions HP-AS is available in a single edition. HP-AS can be augmented with additional features provided in option packs that can be purchased separately. For more information on option packs, please see hpmiddleware.com/hp-as.

Developer Tools HP-AS includes a variety of development tools that simplify packaging, deploying, and managing applications. These tools are used in addition to your favorite IDEs that support the J2EE application component model.

HPAS01DV10-11/13/01

1

HP-AS Developer’s Guide

The following developer tools are available: Tool

Description

HP-AS System Console

This Java-based console allows you to start and stop HP-AS, use drag-and-drop functionality to deploy applications, manage and configure the server, and view log messages. This console is primarily used by developers, administrators, and service developers.

HP-AS Configuration Console

This web-based console is used to configure the HP-AS Load Balance Broker (LBB) and Security services. This console is primarily used by administrators.

RadPak

This Java-based application provides developers with the following functionality:

WebGain VisualCafé plug-in



Edit, package, and deploy J2EE applications.



Deploy applications both locally and on remote servers.



Launch 3rd-party development tools and create command-line automation scripts.



Compile EJBs and CMP 1.1 mapping support.



Edit Java, XML, and Apache ANT files.



Drag-and-drop support and wizards to simplify common development tasks.

The WebGain plug-in enables developers to: •

Create, deploy, and debug EJBs from within VisualCafé.



Locally and remotely debug EJBs deployed on HP-AS.



Generate client projects to test EJBs.



Map EJB 1.1 CMP descriptors.

Third-Party Software HP-AS provides many industry-leading APIs that can be leveraged by application components. These APIs are located in the HP-AS /lib/ext directory. In addition, some third-party products are included with HP-AS as either part of the HP-AS install, or as a separate install. •

Orbix 2000 IONA Orbix 2000 is bundled with HP-AS and can be installed during the HP-AS installation. Orbix 2000 is an enterprise CORBA platform that supports CORBA version 2.3 and elements of version 2.4 and 3.0. The product supports Portable Object Adapters (POA). While HP-AS bundles Orbix, any ORB that supports POA can be used.



MERANT HP-AS incorporates MERANT SequeLink Oracle JDBC drivers. MERANT SequeLink drivers are designed to integrate and manage multiple databases across a variety of data access interfaces;

2

HPAS01DV10-11/13/01

Chapter 1: Introduction

moreover, these drivers support XA datasources. MERANT software is provided in the HP-AS option pack. For additional information on the option pack, please see hpmiddleware.com/hp-as. •

SonicMQ Sonic Software SonicMQ 3.5 Limited Edition is tightly integrated with HP-AS. SonicMQ is a JMS server that supports both point-to-point and publish/subscribe MQ paradigms. In addition, SonicMQ provides XA support, enabling advanced transaction models.



TopLink TopLink 4.0, from WebGain, provides Container Managed Persistence (CMP) and EJB 2.0 support for use with HP-AS 8.0. A free evaluation of Toplink is available at www.webgain.com/products/toplink.



Xerces HP-AS integrates the Apache Software Foundation’s Xerces API. Xerces is a general purpose XML parser designed to be suitable for a wide range of applications. Xerces implements the W3C XML and DOM (Level 1 and 2) standards, as well as the de facto SAX (version 2) standard.



Xalan HP-AS integrates the Apache Software Foundation’s Xalan API. Xalan is an XSLT processor for transforming XML documents into HTML, text, or other XML document types. It implements the W3C Recommendations for XSL Transformations (XSLT) and the XML Path Language (XPath).



HSQL Database Engine HSQLDB (version 1.6), hosted on the SourceForge web site, is bundled with HP-AS as a JAR file located in the /lib/ext directory. HSQL is a relational database engine written in Java, with a JDBC driver supporting a subset of the ANSI-92 SQL. It offers a small (about 100KB), fast database engine, which offers both in-memory and disk based tables.

J2EE Overview J2EE is an enterprise platform offered by Sun Microsystems and created using its Java Community Process (JCP). The JCP ensures open standards are created with compatibility and best practices in mind. HP Middleware supports the J2EE standard and is committed to implementing it as the application platform in HP-AS. J2EE has its own set of standards and terminology. As you become more familiar with the J2EE standard, you will realize that the standard has been created in a simplified manner that is easily integrated into your enterprise solutions. The following sections provide a brief overview of standard J2EE terminology and concepts. If you are not familiar with J2EE, you should visit the java.sun.com website for more information after reading the topics presented here. In addition, many books and web sites are dedicated to J2EE education and resources. If you are familiar with J2EE applications, you can skip this section.

HPAS01DV10-11/13/01

3

HP-AS Developer’s Guide

J2EE Multi-Tier Applications HP-AS is used to host distributed multi-tiered applications. A multi-tier model simplifies distributed applications by separating application components onto different computers that reside in different locations. A common approach to multi-tiered applications is to use three tiers: a client tier for interfacing with a user, a business tier for carrying out business processes, and a resource tier for storing data. Applications deployed in this manner are easy to maintain and benefit from increased performance since the application is spread across different computers and split along functional boundaries. J2EE leverages a multi-tiered architecture and provides components and services that are targeted to different tiers. The J2EE multi-tier standard is presented in Sun Microsystems’ J2EE Blueprints- a set of recommendations that facilitate creating and developing J2EE applications. In general, applications are divided into the following three tiers: •

Client Tier – The client tier is usually comprised of a computer or device running a browser, an application client, or applets. Applets are supported by most browsers using a plugin; however, if your browser does not support applets, you can download an applet plugin from Sun Microsystems.



Middle Tier – The middle tie is usually comprised of one or more computers that host an application’s presentation and business logic. The application components of this tier are hosted in either a web container or an EJB container. The components generally associated with these containers are Servlets, JSP, and EJBs. HP-AS provides these containers and is responsible for managing the middle tier.



Enterprise Information System (EIS) Tier – The EIS tier is a computer that hosts a database or legacy system.

Typically, a development environment includes the three tiers co-located on the same computer, simulating a three-tier environment. This allows developers to quickly create and test applications before deploying them in a production environment. However, when an application is deployed in a production environment, the tiers are located on different computers. Figure 1.1 illustrates a typical application split among three tiers.

4

HPAS01DV10-11/13/01

Chapter 1: Introduction

Figure 1.1

Multi-Tier Applications

Application Scenarios A J2EE multi-tiered environment is flexible because it supports any number of application scenarios, which may use many different application components. Ultimately, the application scenario you select for your application should be based on your business requirements. However, as requirements change, application components can be reused or migrated into new application scenarios. For example, a relatively simple application may grow in complexity over time, requiring a more complex application scenario. Instead of recoding a new application, much of the code can be reused with little or no change. The following sections look at some of the application scenarios identified in the J2EE Blueprints documentation. The scenarios are reconstructed here to demonstrate how HP-AS is used in a J2EE multi-tiered environment. Most of your applications can be created using one of these scenarios; however, you need not force all applications into these models. You can create many scenarios based on your business requirements that may not resemble the scenarios discussed in this section.

HPAS01DV10-11/13/01

5

HP-AS Developer’s Guide

Web-Based Applications Web-based applications are currently very common. In a web-based application, users interact with a computer or device that is capable of running a browser. Since browsers are commonplace, you are assured that a large number of users can access an application without having to be concerned about a proprietary client being installed on their computer. Moreover, web-based applications create a natural division of labor. Developers that are skilled at creating presentation logic can work separately from developers that are creating business logic. In web-based scenarios, presentation logic often changes more rapidly than business logic. Because these tasks are separated, applications are easy to update and can rapidly change with new market trends. Moreover, the same business logic can be accessed using different types of clients promoting application reuse. Typically, clients access application components hosted by HP-AS over the Internet or through a private Intranet. Connection to the server is handled by HTTP(S) and can either use the services of a web server or can directly connect to HP-AS. On the server, an application's presentation logic is hosted in the web container using servlets and JSPs. An application's business logic can be hosted by either the web container or the EJB container. If your applications do not require complex business logic, you can choose to bypass the EJB container. However, complex transactional applications should use EJBs. The EJB container frees the developer from having to manage security, transactions, concurrency, and session storage. Figure 1.2 illustrates the common scenarios associated with web-based applications.

Figure 1.2

Web-based Application Scenarios

Standalone Applications Standalone applications connect with components hosted in HP-AS using either an application client or an EJB client. Standalone clients are Java swing applications that run in their own JVM on a client's computer. Clients use RMI-IIOP to communicate with HP-AS components, and JDBC and connectors to access data on the EIS tier. Typically, standalone clients interact with EJBs hosted in the HP-AS EJB container. However, some scenarios might use the application client to interact with the web container (e.g., retrieving an XML file from a URL). Figure 1.3 illustrates the common scenarios associated with standalone applications. 6

HPAS01DV10-11/13/01

Chapter 1: Introduction

Figure 1.3

Standalone Application Scenarios

Standalone applications are usually hosted on private networks in controlled environments where a small to moderate amount of users are required. Maintaining large amounts of users is undesirable because updates to the client must be done locally on the client machine. However, standalone applications can provide complex client interfaces because they use the well-defined Java swing library. In addition, directly accessing EJBs in the EJB container allows you to create complex applications that are secure, transactional, and concurrent.

J2EE Application Technologies In general, J2EE-based applications are created using J2EE components and services. These components and services leverage the full functionality of the Java language. The following sections provide a brief description of many of the technologies that are discussed in detail throughout this book.

J2EE Application Components J2EE components and services are supported by HP-AS and used to create applications. Components are hosted in containers that provide services to the components. There are four J2EE containers supported in HP-AS: Applet, Application Client, Web, and EJB. The containers also allow components to use additional J2EE technologies. The component and technologies are: •

Servlets Servlets are Java classes that extend the functionality of a server (usually a web server). Servlets use HTTP requests and responses to interact with applications hosted on the web server. Because Servlets are Java classes, you can incorporate many different Java technologies in your Servlet code.



JSP JavaServer Pages allows you to create dynamic web pages by including predefined tag elements (JSP elements) that allow you to include Servlet and Java code in the JSP. In fact, JSPs are compiled into Servlets at run time. While most JSPs contain HTML as static template data (data

HPAS01DV10-11/13/01

7

HP-AS Developer’s Guide

ignored by the compiler), JSPs can use any text-based format such as XML or WML as template data. JSP also allows you to define your own JSP tag extensions. •

EJB The Enterprise JavaBeans components encapsulate an application's server-side business logic. They perform calculations, interact with a database and are transactional. There are three types of EJBs: session, entity, and Message-Driven Beans (MDB). In general, session beans perform calculations, entity beans represent persistent data, and MDBs perform tasks when JMS messages are received.

Common Application Files J2EE applications may be composed of many different components that use different file types. Depending on the type of application you are developing, you will need to use some or all of these components. Many of these components are further defined throughout this book. A typical J2EE application may include:

8



Servlets (.class)



JSP (.jsp)



Web application module (.war) which organizes web components and includes a deployment descriptor (.xml) that defines behaviors of web components



EJB (.class)



EJB module (.jar) which organizes EJB components and includes a deployment descriptor that defines behaviors of EJB components (.xml)



JavaBeans and other utility classes (.class)



HTML and/or other static documents (.htm, .html, .xml, .wml, etc.)



Multimedia files (.gif, .jpeg, .mpeg, etc.)



Client side applets, beans, and classes (.class)



Application client module (.jar) that packages application client classes and includes a deployment descriptor that defines the behaviors of application clients (.xml)



J2EE enterprise application packages (.ear) that includes all of the above files and includes a deployment descriptor that defines the behaviors of a J2EE application (.xml)



A connector module (.rar) which organizes resources adapters and includes a deployment descriptor for defining the behaviors of the adapters (.xml)

HPAS01DV10-11/13/01

Chapter 1: Introduction

J2EE Services The J2EE platform includes a number of services that are used by applications and by HP-AS to provide enterprise functionality. These technologies are discussed throughout this guide. Additional information can be found on the java.sun.com website. •

JDBC JDBC allows you to connect to any number of data sources including virtually any database type. Most likely, you will use JDBC to connect to databases that store application data or authentication credentials. In addition, JDBC extensions are included to allow advanced services like connection pooling and distributed transaction support.



JNDI The Java Naming and Directory Interface allows you to create standard directory and naming contexts, which you can then use to store and find Java objects. In addition, JNDI allows you to access additional directory services such as LDAP.



JavaMail The JavaMail API provides a set of abstract classes that models a mail system. The API allows you to incorporate Java-based mail and messaging into your applications.



JAF The JavaBeans Activation Framework provides support for MIME data types and is primarily used by JavaMail to handle email data.



JMS The Java Messaging Service allows your applications to use and integrate enterprise messaging systems. HP-AS integrates with the SonicMQ JMS server that allows you to use both message topics and message queues. In addition, and JMS compliant messaging server can be used with HP-AS.



JTA The Java Transaction API provides your applications with a standard way of accessing transactions by managing all parts of the transaction process: the resource manager, HP-AS, and the application. In addition, HP-AS integrates HP Total-e-Transactions, a Java Transaction Service (JTS) implementation.



JAAS The Java Authentication and Authorization Service (JAAS) API is an optional Java package that is included with J2EE. However, JAAS is currently being implemented as a basic feature of J2SE. JAAS is a set of packages that enable services to authenticate and enforce access controls upon users.



JCA The Java Connector Architecture allows your applications to use a standard architecture for accessing resources in diverse Enterprise Information Systems (EIS). This architecture helps solve

HPAS01DV10-11/13/01

9

HP-AS Developer’s Guide

the problem of integrating legacy and future systems built on different platforms, using different programming languages, different data sources, etc. •

JAXP The Java API for XML parsing is an optional Java package that is included with J2EE. JAXP allows applications developers to plug any SAX or DOM parser into HP-AS as well as XSLT transformation engines.

Packaging J2EE Applications J2EE has a common methodology for packaging J2EE applications. A common packaging convention makes it possible to create portable applications that can be assembled and even customized without having to modify code. This is especially important if you are developing applications that are sold or licensed as third party software. J2EE packaging is also an easy way to keep your applications logically organized. In general, a J2EE application is packaged as an Enterprise ARchive file (EAR), which may contain any of the following J2EE modules: a Java ARchive file (JAR), a Web ARchive file (WAR), or a Resource adapter ARchive (RAR) file.

EAR files An Enterprise ARchive file is a compressed file that contains a J2EE application's modules. EAR files are created using the Java jar command or using a ZIP utility and then changing the extension to .ear. The EAR file may contain JAR, WAR, and RAR packages. In addition, the EAR must contain the deployment descriptor META-INF/application.xml. This deployment descriptor lists all of the J2EE modules that are part of the application. RadPak, the HP Middleware deployment tool, allows you to modify and package EAR files.

JAR files All class libraries in Java are packaged as JAR files. In J2EE, JAR files are also used to package EJBs. JAR files are created using the Java jar utility included with the JDK, or using a ZIP utility and changing the extension to .jar. An EJB JAR file may contain session beans, entity beans and MDBs as well as utility classes. In addition, the EJB JAR file must contain the deployment descriptor METAINF/ejb-jar.xml. The EJB deployment descriptor defines all of the beans available in the JAR and contains elements for defining the behavior of the beans. RadPak, the HP Middleware deployment tool, allows you to modify and package JAR files. In addition to EJBs, application clients that run in an application client container are also packaged as a JAR file. The application JAR file must contain the deployment descriptor META-INF/applicationclient.xml). This application client deployment descriptor describes the EJBs and external resources referenced by the application client. During run time, you should always deploy your EJB JAR packaged in an EAR file; however, during development it may be convenient to deploy the EJB JAR file standalone.

RAR files Not to be confused with WinRAR (RAR) a compression utility similar to WinZip, J2EE RAR files are packages for resource adapters. A Resource adapter is a J2EE component that implements the J2EE Connector Technology for a specific EIS. The resource adapter makes it possible for an application to communicate with an EIS. In addition, a RAR file must contain the deployment descriptor METAINF/ra.xml. RadPak, the HP Middleware deployment tool, allows you to modify and package RAR files. 10

HPAS01DV10-11/13/01

Chapter 1: Introduction

WAR files Web components are packaged as a Web ARchive (WAR) file. A WAR file is a compressed archive file that has a .war file extension. WAR files are created using the Java jar command or using a ZIP utility and then changing the extension to .war. In general, a WAR file contains HTML, multimedia, Servlets, JSPs and additional utility classes. If your J2EE application does not make use of EJBs, your WAR file can implement server-side business logic using JavaBeans. Many J2EE applications that are strictly web-based applications use only WAR files. During run time, you should always deploy your WAR packaged in an EAR file; however, during development it may be convenient to deploy the WAR file standalone. Because a complete web application can be deployed as a singular WAR, there are some additional rules to follow when creating WARs. The following sections describe WAR files in a little more detail. As part of the servlet specification, web components are organized into a specific directory structure that facilitates creating applications. This can be extremely important if you have a large development team working on different parts of the application simultaneously. The structure also insures portability when distributing your application and encourages reuse of components among applications. Figure 1.4 illustrates the directory structure of a sample application. Because HP-AS understands and expects an application to be in this structure, it can offer functionality that is leveraged by your applications. For example, HP-AS contains class loaders that automatically find and place an application’s classes in the classpath, alleviating this responsibility from the developer. This guarantees that all the classes needed by an application are found at runtime.

Figure 1.4

Web Application Directory Structure

Each web application requires a root directory (usually referred to as the document root). The document root is the top-level folder that contains HTML, JSP, image files, etc. There are no restrictions on how these files are organized. As Figure 1.4 illustrates, a web application directory requires a WEB-INF sub-directory that is always capitalized and is restricted from being accessed by a browser. This directory contains the application’s deployment descriptor (web.xml). Web.xml contains configuration information for your application. All web applications should contain a web.xml file; however, to what extent you use web.xml depends on your application (for example, if you are using Servlets or container-provided security). In many ways, web.xml acts as a contract between an application’s components and the HP-AS web container. Components declaratively state the services they need, and the HP-AS web container provides those services.

HPAS01DV10-11/13/01

11

HP-AS Developer’s Guide

You may have noticed WEB-INF contains two sub-directories: lib and classes. These subdirectories are used to include Servlets and Java class files required by the application. The /lib directory is used if you are including class files packaged as a Java Archive (.jar) file. The /classes directory is used if you do not want to package and compress your class files (a real time saver during development). Classes placed in the /classes directory must be placed in subdirectories that match their package structure, as demonstrated in Figure 1.4. WAR files make deploying web components in HP-AS very easy. At runtime, the server automatically searches the contents of the WAR file and makes it available for requests. However, during development it may be impractical to repackage your web components as a WAR file after every change that is made. To alleviate a considerable amount of added time and effort, HP-AS allows you to deploy WAR files, unpackaged, in an open filesystem. RadPak, the HP Middleware deployment tool, allows you to modify and package WAR files.

J2EE Platform Roles The J2EE specification identifies a number of roles that correlate to different phases in the development and deployment lifecycle of a J2EE-based application. In each phase, there are persons or organizations with expertise that make them naturally suited to carry out the tasks of that phase. It is impossible to assume that you or your company fits into a certain role; however, J2EE roles do make it easy to identify what tasks need to be completed. Who completes these tasks is based on your environment and business processes. The following table lists these roles and provides a brief description of each role. J2EE Platform Role

12

Description

J2EE Product Provider

Usually, a vendor that implements the containers, services, and APIs of the J2EE specification. In addition to these services, the product provider may implement other services not specified by J2EE. HP Middleware is a product provider. HP-AS is an application server that implements J2EE components and containers allowing persons to host their applications.

Application Component Provider

Usually, persons who create application components that are hosted in a product provider’s containers. This provider covers presentation developers who program using HTML and JSP, and Java or business logic programmers who program using servlets, Java, and EJBs.

Application Assembler

Usually, persons that integrate application components provided by the component provider.

Deployer

Usually, persons who deploy the application in an operational environment and make sure that the application has the resources it requires (i.e. database).

System Administrator

Usually, persons who are responsible for maintaining the infrastructure of an operational environment. These persons are also responsible for maintaining the application during runtime.

Tool Provider

Usually a vendor that provides tools that assist component providers, assemblers, deployers, and administrators. HP Middleware is a tool provider.

HPAS01DV10-11/13/01

Chapter 1: Introduction

MVC Design Model The MVC (Model-View-Control) design pattern is a way of separating applications into three logical functional units: the model, the view, and the controller. The model contains code that handles business logic. The view contains presentation logic. The controller contains code that handles request processing which ties the view and the model together. The design pattern was originally designed to facilitate the development of GUI-based applications, but web applications that run in a multi tier webbased environment can also leverage the benefits of this design pattern. If possible, design your J2EE applications using MVC. Applications that are designed using MVC are easy to maintain for several reasons. First, MVC delegates responsibility to developers who have skills pertinent to a specific functional unit. A developer can concentrate on a specific unit and, with minimal communication, develop a part of the application that other developers can then use. Second, as applications change in scope, each unit can be modified without affecting the other units. For example, if presentation pages change, developers need not worry of tampering with the other units that are not changing. Finally, an application may need to present data to different clients in different ways. For example, the same application may be accessed using a browser or a cell phone and may be available in several different languages. In both instances, code that is not dependent on presentation need not be modified and can be reused. Figure 1.5 illustrates the MVC design architecture.

Figure 1.5

HPAS01DV10-11/13/01

MVC Architecture

13

HP-AS Developer’s Guide

Struts Struts is an open source initiative from the Jakarta Project, which is sponsored by the Apache Software Foundation. The framework was created by Craig McClanahan in May of 2000, after which the code was donated to the Apache Software Foundation and into the hands of the development community. The charter of Struts is to provide an open source framework that facilitates building applications based on the J2EE Servlet and JSP technologies. The primary functionality provided by Struts includes request dispatching, tag libraries to accelerate GUI development, internationalization and automatic form population. Struts can be used in application development as the underlying architecture on which you develop your web based applications. For more information, see the Struts trail map included with HP-AS.

14

HPAS01DV10-11/13/01

Chapter 2

Getting Started Overview This chapter provides basic information for using HP-AS. The topics include: •

Viewing HP-AS Trail Maps



Starting HP-AS



HP-AS Modes



Setting HP-AS Logging Levels



HP-AS Configuration files



HP-AS Proprietary Deployment Descriptors

Viewing HP-AS Trail Maps HP-AS includes several trail maps. The trail maps provide you with a quick overview of HP-AS and demonstrates some of its core functionality. You should use the trail maps if you are new to HP-AS, middleware application servers, or J2EE web components. The trail maps are also a great place to see some sample web applications running in HP-AS without having to find or create any code. Note: Trail maps are only installed if you selected to complete a full HP-AS installation.

Each trail map is a set of trails (steps) that you can browse. The trails in the beginning of a trail map are simple and informative, while later trails demonstrate advanced functionality. The goal of the trail maps is not to explain complicated concepts, but to quickly introduce you to HP-AS and its functionality. After you have browsed the trails, you can access detailed information and procedures within this document, as well as the full documentation set. HP-AS includes three trail maps: •

Beginner – These trails are designed to teach basic HP-AS functionality. For example, you will learn how to start and stop HP-AS, deploy applications, and work with the HP-AS XML transformation framework. In this trail map, you will also get a chance to try servlets, JSPs, and EJBs that are deployed in HP-AS.



Intermediate – These trails present additional information about HP-AS as well as intermediate concepts. For example, you will learn about HP-AS configuration, deploying applications using RADPAK, MDBs, and porting applications to HP-AS.

HPAS01DV10-11/13/01

15

HP-AS Developer’s Guide



Advanced – These trails present some advanced features that are included with HP-AS. Some highlights of this trail map include: load balancing, Using Cocoon II with HP-AS, using Jetspeed with HP-AS, Struts, I18n, transactions, and advanced EJB concepts.

Starting HP-AS Trail Maps To start a trail map, Windows users can use Start | Programs | HP Middleware | HP Application Server | Trail Maps. Unix users can change directories to the HP-AS /bin directory which contains scripts for each trail map. Example code from the trail map can be found in the HP-AS /trail maps directory. Note: During installation, you can select to have the trail map automatically start, along with HP-AS after the installation is complete.

Starting HP-AS HP-AS can operate in either of two modes: system console mode, or system text console mode. In system console mode, HP-AS starts in a window environment, allowing you to interact with different HP-AS services. In particular, you can start and stop the server, deploy applications, view server log messages, and modify the behavior of different HP-AS services using Java Management Extension (JMX). This mode is primarily used in a development environment. In system text console mode, the server is started from the command-line, and log messages are displayed to the command-line. System text console mode is primarily used in a production environment after development is completed or for performance testing applications. Depending on your operating system, the HP-AS /bin directory contains executables for both modes. •

hpas.exe (hpas) – starts the server in system text console mode.



hpasw.exe (hpasw) – starts the server in system console mode.

Note: Scripts that start HP-AS have also been included. See Starting HP-AS Using Scripts below.

On the Windows platform, shortcuts to the HP-AS executables are available for both system text console and system console mode. From the Windows Start menu, select Programs | HP Middleware | HP Application Server | System Text Console or System Console. On the Unix platform, you must start the server from the HP-AS /bin directory using the following procedure: 1

Open a command window.

2

Change directories to the HP-AS /bin directory.

3

Choose one of the following options: •

To start the server in system console mode, type hpasw and press enter.



To start the server in system text console mode, type hpas and press enter.

Defining HP-AS's Classpath HP-AS executables are configured to load all the resources that are necessary for operating the server out-of-box. However, you can specify additional resources (directories and JAR/ZIP archives) that you 16

HPAS01DV10-11/13/01

Chapter 2: Getting Started

want loaded into the classpath. Additional resources can be either appended or prepended to the HPAS classpath. To add resources to the HP-AS classpath: 1

From the HP-AS /bin directory, open hpas.cfg using a text editor.

2

Modify the configuration file using the following arguments: •

-cp:p

This argument prepends the specified directory, directories, and/or JAR/ZIP archives to HP-AS's classpath. •

-cp:a

This argument appends the specified directory, directories, and/or JAR/ZIP archives to HP-AS's classpath. •

-exclude [,[,...]

This argument excludes one or more archives from HP-AS's classpath. The specified archives must be unqualified. The exclusion is done on a name basis only; directories cannot be included. 3

Save and close the file.

4

Start the server. Note: For a complete list of the arguments available when using HP-AS executables, see the appendix Using the Java Product Launcher.

Starting HP-AS Using a Script File HP-AS includes a script file that can be used to start HP-AS. Depending on your operating system, the HP-AS /bin directory contains the following script: • hpas-launcher.sh – used to start HP-AS in Unix environments. • hpas-launcher.cmd– used to start HP-AS in Windows environments. When running the script, all JARs that are in the HP-AS /lib, /lib/ext, and the lib/ext for the JRE are loaded into the classpath. If you want to add additional JARs, you can place them in any of these directories. Note: When starting the server within a debugging environment or IDE, all the resources in the /lib directory should be in the classpath.

To run the script: 1

From the command line, change directories to the HP-AS /bin directory.

2

Type the name of the script file and press enter. hpas-launcher

You can specify three options when using the script file:

HPAS01DV10-11/13/01

17

HP-AS Developer’s Guide

Option

Description

-t

Starts HP-AS in system text console mode using the class com.hp.mwlabs.hpas.embeddors.text.Server. This is the default behavior of the script.

-g

Starts HP-AS in system console mode using the class com.hp.mwlabs.hpas.embeddors.swing.Server. It you do not specify this option, the server starts in system text console mode using the class com.hp.mwlabs.hpas.embeddors.text.Server.

-d

Allows you to define a different deployment URL and deployment descriptor. The URL must point to a valid deployment descriptor. If you do not specify this option, /config/hpas/hpas-deploy.xml is used. To use this option, you must include a valid URL path. For example, on Windows you would specify: file:///d:/hpmw/hpas/config/hpas/hpas-deploy.xml

Contacting HP-AS After you start HP-AS, you can contact the server to verify that it is running and listening for HTTP requests. To contact the server you must send an HTTP request to the port HP-AS is listening on. By default, HP-AS listens on port 9090. If port 9090 is unavailable, the server tries 9091, 9092, and 9093. If none these ports are available, HP-AS uses the first available port. You can set HP-AS to listen on any port using the /config/hpas/http-service-config.xml file. For a complete description of this file, see Appendix A in the HP-AS Administrator's Guide. Note: Before attempting the following procedures, make sure that port 9090 is not in use.

To contact HP-AS: 1

Start the server using any of the procedures discussed in the preceding sections.

2

Start an Internet browser.

3

In the address field, type the following URL to display the HP-AS index page: http://localhost:9090 Note: you can also substitute localhost with the name of the computer where you installed HP-AS.

18

HPAS01DV10-11/13/01

Chapter 2: Getting Started

HP-AS Modes HP-AS includes two modes: a system text console mode and a system console mode. The HP-AS modes represent an implementation of a CSF embeddor. The role of the embeddor is to create, initialize, start, stop, and destroy the kernel, which contains all HP-AS services. The embeddor provides a stable environment, extracting information from the surrounding environment and providing it to the kernel without the kernel or its components needing to be adapted in any way. Both the HP-AS system console mode and the system text console mode perform these tasks; moreover, additional features have been added to each mode.

HP-AS System Text Console Mode The HP-AS system text console mode is designed for production environments, where all unnecessary overhead must be eliminated. In addition, the console window displays log messages being emitted by HP-AS. When using this mode you must manually deploy applications using RadPak or modify HPAS services using HP-AS configuration files. The following screen capture shows HP-AS running in system text console mode on a Windows-based operating system.

HPAS01DV10-11/13/01

19

HP-AS Developer’s Guide

Note: HP-AS includes many different log levels that allow you to control the type of log messages that are emitted. To configure the log browser to emit different log levels, see Setting HP-AS Logging Levels below.

HP-AS System Console Mode The HP-AS system console mode is designed for a development environment. This mode also includes a number of browsers that you can use to receive and display information in a user interface environment and interact with the HP-AS’s containers and services. The following screen capture shows HP-AS running in system console mode on a Windows-based operating system. Note: When HP-AS is started in system console mode, the log browser is automatically started.

20

HPAS01DV10-11/13/01

Chapter 2: Getting Started

System console mode accommodates a broad range of developers who use it in different ways. For example: •

An application developer uses the system console mode to interact with services used for deploying and hosting applications.



A service developer uses the system console mode to develop, install, and troubleshoot services.



A system administrator uses the system console mode to verify that services are running properly at runtime and to possibly modify the runtime behavior of services.

This guide primarily focuses on using the system console mode to deploy applications and administer HP-AS services. For more information on using the system console mode to develop and install services, see the CSF Service Developers Guide, included with the CSF product. The following sections provide a brief overview of HP-AS's browsers that are available in system console mode. As a web application developer, you primarily use the Log Browser, JMX Browser and the Deployment Window. However, all browsers are defined below.

Log Browser The Log Browser displays log messages that are emitted by HP-AS and its services while the server is running. HP-AS includes many different log levels that allow you to control the type of log messages that are emitted. To configure the log browser to emit different log levels, see Setting HP-AS Logging Levels below.

HPAS01DV10-11/13/01

21

HP-AS Developer’s Guide

JMX Browser The JMX Browser interacts with Managed Beans (Mbeans) that are registered for each HP-AS service. MBeans are public methods of the services. From the JMX Browser, you can deploy applications and modify service behaviors.

JNDI Browser The JNDI Browser is used to view a list of the services that are currently registered in the Service Registry. A service must be visible in the JNDI Browser in order for other services to find and use it. The JNDI Browser is mainly used by service developers.

22

HPAS01DV10-11/13/01

Chapter 2: Getting Started

Setting HP-AS Logging Levels HP-AS allows you to set different log levels. Log levels determine what type of messages will be emitted by the server. In system console mode, log messages are displayed in a Log Browser. In console mode, log messages are displayed in the console window. By default, HP-AS is set to emit status messages; however, during development you may want HP-AS to emit detailed messages, such as debug messages. Log levels are set in /config/hpas/log-manager-config.xml, using the level attribute of the LogChannel element. To change the log levels for HP-AS: 1

Open /config/hpas/log-manager-config.xml using a text editor.

2

Modify the level attribute.

Any of the following log levels can be used: Log Level

Description

NONE

No output will be emitted.

FLOW

Emits output that is used to track method invocations. This log level is not currently used in HP-AS.

DEBUG

Emits output that is used to track events that are occurring in the server. The output includes problems and non-problems.

INFO

Emits output that is used to track any non-problem events.

HPAS01DV10-11/13/01

23

HP-AS Developer’s Guide

Log Level

Description

STATUS

Emits output that is used to track system startup events. This is the default log level.

WARNING

Emits output that is used to track errors that have occurred. The server catches the exception and is able to continue.

ERROR

Emits output that is used to track errors that may result in reduced functionality.

CRITICAL

Emits output that is used to track errors that are non-recoverable, meaning the server will not function properly.

3

Save and close the file.

4

Start the server.

Configuration Files The HP-AS /config/hpas directory contains all configuration files. The configuration files are standard XML documents and can be modified using a text editor or, in some cases, using the HP-AS JMX browser. In addition, schemas or DTDs for each configuration file have been included in the /xml directory. This allows you to use a validating parser to insure you have added entries properly. Configuration files are discussed throughout this book and the HP-AS Technical Guide, which also includes a configuration reference in the appendix. The following table lists the configuration files included with HP-AS and provides a brief description of each file. Configuration File

24

Description

access-provider-service-config.xml

Used to define security realms that HP-AS uses to authenticate and authorize users. HP-AS includes a realm for authenticating and authorizing users using an XML-based realm.

application-classloader-serviceconfig.xml

Used to configure the application class loader service. Entries in this file allow you to define libraries that you want loaded into the classpath at runtime.

arjuna-service-config.xml

Used to configure the HP transaction service. The service is responsible for creating and distributing the JTA transaction facilities.

connector-service-config.xml

Used to configure the connector service. Entries in this file allow you to define connector, datasource connection factories, and connection pool behavior.

corbaloc-service-config.xml

Used to configure the CORBA locator service. This service advertises the location of the Interoperable Naming Service.

cosnaming-resolver-serviceconfig.xml

Used to configure the COS Naming Service. This service supports the lookup of EJB objects.

ejb-service-config.xml

Used to configure the EJB service and EJB container.

HPAS01DV10-11/13/01

Chapter 2: Getting Started

Configuration File

Description

ejb-service-config-corba.xml

Used to configure the EJB service and EJB container when using CORBA.

hpas-deploy.xml

Used by the Core Services Framework (CSF) kernel to load services that run within its framework. This configuration file does not need to be modified.

http-service-config.xml

Used to configure the HTTP listener service. Entries in this file will control how, and on what port, HP-AS will listen for requests.

j2ee-partition-service-config.xml

Used to deploy J2EE applications. In this file, you define the application's EAR, which can contain WAR, JAR and RAR files.

java-mail-service-config.xml

Used to configure the JavaMail service. This service supports the lookup of JavaMail sessions.

jaxp-service-config.xml

Used to configure the JAXP service. Entries in this file allow you to map JAXP 1.1 compliant parsers to logical JNDI lookup names.

jdbc-realm-config.xml

Used to configure the JDBC realm. This realm authenticates users against a database.

jms-service-config.xml

Used to configure the JMS service. Entries in this file define JMS providers, JMS connections, connection factories, destinations, JMS connection pool, and dead connection detection.

jmx-access-provider-serviceconfig.xml

Used to configure the access provider service. This service provides the facilities for configuring and managing the JAAS implementation and is utilized by the MBean Server.

jmx-xml-realm-data.xml

Used to define users, groups, and roles. Entries in this file are used to authenticate users at runtime. jmx-xml-realmdata.xml is an implementation of a realm configuration file.

log-manager-config.xml

Used to configure the log manager and set different log levels that HP-AS will emit.

orb-service-config.xml

Used to configure the ORB service. This service is responsible for creating and distributing an ORB instance.

protocol-mapper-service-config.xml

Used to configure the protocol-mapper service. This service maps incoming requests to appropriate containers.

reference-resolver-service-config.xml

Used to configure the JNDI reference resolver service. This service supports the JNDI lookups for resources and ejb references.

sapphire-service-config.xml

Used to configure the sapphire protocol listener. This service will listen on a given port for Sapphire requests.

servlet-service-config.xml

Used to configure the servlet container service.

session-manager-service-config.xml

Used to configure the session manager service. This service provides an in memory session manager for the servlet container.

HPAS01DV10-11/13/01

25

HP-AS Developer’s Guide

Configuration File

Description

transaction-recovery-serviceconfig.xml

Used to configure the transaction recovery service. This service is used by the HP transaction service.

uri-registry-file-store-data.xml

Used to specify URIs that will be registered with the URI registry service.

uri-registry-service-config.xml

Used to configure the Uniform Resource Identifier (URI) registry service. This service resolves any JAXP URI requests.

url-service-config.xml

Used to configure the URL provider service. This service supports the lookup of URLs.

xmlrealm-data.xml

Used to define users, groups, and roles. Entries in this file are used to authenticate users at runtime.

xtf-service-config.xml

Used to configure the XML Transformation Framework (XTF) service. This service provides a configurable framework for controlling and defining XML/content transformations

HP-AS Proprietary Deployment Descriptors In addition to standard J2EE module deployment descriptors, HP-AS uses a set of proprietary deployment descriptors. HP-AS descriptors have the same name as their J2EE equivalents except they are preceded by "hp-". For example, the HP-AS proprietary deployment descriptor for web.xml is hpweb.xml. When using HP-AS proprietary deployment descriptors, they must be placed in the same directory as their J2EE counter parts. For example, hp-ejb-jar.xml must be placed in the META-INF directory of an EJB JAR. In addition, proprietary deployment descriptors take precedence over the J2EE deployment descriptor and may override settings in a container service's configuration file. HP-AS proprietary deployment descriptors provide additional features than those offered by the J2EE deployment descriptors. For example, inter-application communication can be defined using HP-AS proprietary deployment descriptors. Schemas for these deployment descriptors are located in the /xml/schemas directory and should be consulted for proper usage. For detailed information about the elements in the proprietary descriptors, see Appendix A in the HP-AS administrator's Guide. Note: If you are developing applications that have portability requirements, you should use HP-AS proprietary deployment descriptors with care.

26

HPAS01DV10-11/13/01

Chapter 3

Assembling and Deploying J2EE Applications Overview A J2EE application is generally composed of a number of components: •

Web Components – HTML pages, Servlets, JavaServer Pages, and related files.



Enterprise JavaBean Components – entity beans, session beans, message-driven beans.



Connector components – resource adapters.

Once a J2EE application is assembled, it is deployed to the HP Application Server. When you deploy an application, the server loads the various components and the application is made available to external clients, such as web browsers or standalone Java clients. During development, an application can be deployed on your local computer or it can be deployed on a central server where many developers can access the application to test or modify it (i.e. a development server that has restricted access to development team members only). Once the application is deployed into the development environment, you do not need to stop and restart the server in order to work on the application or modify its configuration options. When development is complete, you package the application as an .ear file, which makes moving the application between environments very easy. In a production environment, HP-AS is installed on an accessible runtime computer or farm of computers. These computers are either available on an intranet (for intranet-based applications) or publicly available and open to request through a firewall. The application must be moved to these computers and deployed into the HP-AS environment. Once the application is deployed, you can update it on a regular basis without having to restart the server, which mitigates downtime.

Assembling an Enterprise Application A J2EE enterprise application contains web and EJB components assembled into an Enterprise Archive (.ear file). The META-INF/application.xml deployment descriptor of the .ear file has an entry for each web and EJB module as well as some additional optional entries to describe security roles and application resources. For more on assembling an .ear archive file please refer to Chapter 11, HP Developer Tools. The dependencies between application components must be accounted for by packaging the associated classes in such a way that all class dependencies can be resolved at runtime.

HPAS01DV10-11/13/01

27

HP-AS Developer’s Guide

Resolving components’ class dependencies An enterprise application deployed to the HP Application Server is composed of many different classes such as Enterprise Beans, Servlets, JavaBeans, utility classes, and database drivers. The HP Application server creates multiple classloaders to maintain application isolation as well as facilitate dynamic application redeployment and undeployment. It is therefore very important that the applications you deploy are packaged and assembled such that any component can find the classes on which it depends. This section will detail the classloading strategy within the HP Application Server.

Classloader Overview A Java classloader is a component that locates and loads a requested class into the Java Virtual Machine (JVM). Generally, Java applications utilize the default system classloader to access classes defined in the JVM’s classpath. However, the HP Application Server makes use of custom classloaders in order to isolate applications in separate namespaces and facilitate dynamic addition and removal of classes associated with enterprise components. Java 2 classloaders initially delegate class loading to their parent. A classloader parent can be either the bootstrap classloader or another custom classloader. In the event the parent classloader can't load a class, the custom classloader is responsible for loading the classes not available to the parent.

Figure 3.1

28

Classloader Hierarchy

HPAS01DV10-11/13/01

Chapter 3: Assembling and Deploying J2EE Applications

Application Classloaders During the deployment of an enterprise application, a parent application classloader is created. This classloader serves as the parent classloader for all component classloaders (EJB classloader, servlet classloader, etc.) in the given application. In addition, a library classloader that facilitates access to shared application archives is created and set as the parent of the application classloader. The application classloader is actually a composite of the various component classloaders; it loads no classes itself but rather defers the loading of classes to the component classloaders. When a request for a class reaches an application classloader it will query each of its constituent component classloaders in an attempt to load the given class. Consider the common scenario of a servlet acquiring and utilizing an Enterprise JavaBean. The servlet will generally require the loading of the home and remote interfaces of that EJB. The request for a particular EJB class will propagate up the classloader hierarchy and ultimately reach the Application classloader. The application classloader will subsequently query its component classloaders for the class. The EJB classloader associated with the application will return the EJB class requested and the class will be loaded into the JVM successfully.

Component Classloaders EJB Classloader The EJB container creates a custom classloader that facilitates access to all classes contained within all EJB archives registered with the container. The application classloader serves as the parent classloader to the EJB classloader. Web Application Classloader Each web archive loaded into the HP Application Server’s servlet container triggers the creation of a web application classloader. This web application class loader is responsible for providing access to all classes available in the web archive (.war file) including the servlet classes, archives deployed in the WEB-INF/lib folder, and classes found in the WEB-INF/classes folder (and its sub-folders). The application classloader is set as the parent of the web application classloader thus facilitating access to the web archive’s classes from other application associated components (component classloaders are essentially peers of the web classloader given that the application classloader delegates classloading to the component classloaders). Connector Classloader The connector classloader creates a custom classloader that facilitates access to all classes contained within all registered RARs. The application classloader serves as the parent classloader to the connector classloader.

Library Classloader All classes within the archives registered in the application classloader service’s configuration file are retrieved by the library classloader. The library classloader serves as the parent classloader for all the created application classloaders. It therefore facilitates access to classes that will be shared by all application components across multiple applications (e.g. database driver classes).

HPAS01DV10-11/13/01

29

HP-AS Developer’s Guide

Assembling Application components When packaging and deploying the components of an enterprise application it is important to understand the implications of Java 2 classloading and its implementation in the HP Application Server. The most important thing to remember is that a classloader will initially defer to its parent to load a class; only when the class is not returned by its parent will the actual classloader attempt to load the class from the resources (directories, archive files, etc.) it manages. As a consequence, a class must be able to find all dependent classes from its parent class loaders or the same classloader from which it was loaded; a class will not be found lower in the classloader hierarchy. Some general guidelines for class packaging: •

If possible, package classes and their dependencies in the same archive; distributing dependent classes across multiple archives can ultimately lead to runtime difficulties in loading or finding the given classes.



Register shared resources with the application classloader service. Make sure the classes in these archives have no dependencies on component classes since classes cannot be found lower in the classloading hierarchy.



It is generally not advisable to make a class available in more than one location (e.g. the library classloader AND the system classpath); such deployment can lead to class finding and casting issues.



Any archives/directories added to the classpath by setting the CLASSPATH environment variable are returned by the topmost classloaders in the hierarchy (remember that the CLASSPATH is amended with information in the bin/hpas.cfg file). The Library Classloader returns classes from the archives and/or directories configured in the application-classloaderservice-config.xml file. Finally, the classes in the various component archives are managed by the associated component classloaders.

Deploying an EAR An application that is ready to be deployed to a production platform should be assembled as an Enterprise ARchive (.ear file). The .ear file should include all J2EE modules that are required for the application to operate (i.e., .war, .jar, .rar). In addition, the .ear file should contain a valid deployment descriptor (application.xml) located in the META-INF folder. This deployment descriptor can be created and modified by the HP-AS development tool (RadPak), which can also be used to assemble the .ear file. The deployment descriptor is responsible for defining all J2EE modules that are included in the .ear file. There are a number of advantages to assembling an enterprise application into an .ear file and deploying it to the HP Application Server: •

Manageability – The application is combined into one archive file that is easily deployed to multiple platforms. All application components are maintained within one archive.



Redeployment – Applications deployed to the application server as enterprise archives are deployed and undeployed as a unit. When a new version of the application replaces an existing version the older version of the application is phased out gradually so that no existing clients lose application data.

Application archives are deployed to the HP Application Server via the J2EE Partition. When you deploy an .ear file the partition distributes the J2EE modules to the appropriate containers. For example, .war files are deployed to the servlet container and EJB .jars are deployed to EJB container. 30

HPAS01DV10-11/13/01

Chapter 3: Assembling and Deploying J2EE Applications

Each .ear you deploy, and its J2EE modules, are associated with a namespace. By default, the namespace is the file name of the .ear archive (without the .ear suffix). The assigned namespace allows for application isolation so that the classes associated with the application as well as the component JNDI lookups do not cross application boundaries. In addition, a digest of the deployed archive is calculated in order to assign a version id to the deployed archive. J2EE applications that are deployed in HP-AS will have an entry in /config/hpas/j2ee-partition-serviceconfig.xml file. HP-AS offers a number of tools for creating j2ee-partition-service-config.xml entries and the associated deployments. In addition, the file can be edited by hand in order to trigger an archive deployment. The following sections describe the available methods for deploying applications.

Deploying an EAR using RadPak RadPak is an HP-AS developer tool that is used to assemble and deploy applications in HP-AS. There are several ways to deploy EJB Java ARchives (JARs), Web ARchives (WARs) and Enterprise ARchives (EARs) in RadPak:

Menu Deployment 1

Launch a Browser. Select the Application to be deployed. Right-click and select Deploy to Server or select Deploy to Server from the Project menu on the main interface. The Select Server box launches.

2

Select the deployment server from the list of configured servers. Click OK.

3

See Generation and Deployment below.

Drag and Drop Deployment 1

Launch a Browser. Browse to Remote File Systems. Expand the tree to view the server to be used for deployment. Select the Application to be deployed and drag it to the correct server.

2

See Generation and Deployment below.

Generation and Deployment 1

If the EAR being deployed contains an EJB JAR, the EJB code generation options box will launch. Provide any necessary configuration information and Click OK.

HPAS01DV10-11/13/01

31

HP-AS Developer’s Guide

2

The application is processed for deployment. If the application contains an EJB JAR, RadPak's HPEJBC.exe runs. If the application contains a WAR, the project's JSPs are pre-compiled.

The Deploy to Server box indicates the outcome of the deployment process:

32



A failed deployment is indicated by the failed deployment icon. Error messages offer details about the reason for the failure.



A successful deployment is indicated by the deployment completed icon:

HPAS01DV10-11/13/01

Chapter 3: Assembling and Deploying J2EE Applications

Manually Deploying an EAR When manually deploying an EAR into HP-AS, you must open /config/hpas/j2ee-partition-serviceconfig.xml with a text editor and manually create an entry for the EAR. EAR entries must be nested within the element. When manually entering entries in j2ee-partition-serviceconfig.xml, use the following form:

HPAS01DV10-11/13/01

55

HP-AS Developer’s Guide

JSP Scripting Elements Scripting elements allow you to add script directly in a JSP page. The script must be defined by the language attribute in the page directive. There are three scripting elements: Scriptlet, Expression, and Declaration.

Scriptlet A scriptlet is a code fragment that can contain any code that is valid for the language that is designated with the language attribute of the page directive. Scriptlets are processed at request processing time. Code within a scriptlet is placed in the resulting servlet's generated _jspService() method. Scriptlets can access any variable or bean that has been defined. Implicit objects are also available to scriptlets from the servlet environment. Example: Good Morning Good Afternoon

Expression An expression is a complete expression in the language that is specified by the language attribute of the page directive. An expression is evaluated, converted into a String, and then placed into the page's output; the current out of the JspWriter object. This means that everything between the tags is converted into a String and then displayed. String conversion is done automatically. They are evaluated at HTTP processing time. Example:

Declaration Declarations are used to define page-wide methods and variables. Defined items are available to other code within the page and optionally define the jspInit() and jspDestroy() methods. Declarations do not produce output. Example: Note: Lines end in semicolons, just as if they were part of a Java source file.

56

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

JSP Object Scope JSPs are frequently implemented using a compilation phase that is done once, followed by request processing phases that can be performed any number of times. The compilation phase creates a JSP implementation class that implements the javax.servlet.Servlet interface. The translation of a source JSP can occur at any time between the deployment of the page into the runtime environment and the receipt of a client request for the page. JSPs can access and create Java objects when processing a request. Some objects are created implicitly, while others are created through action or scripting elements. A created object has a scope attribute that defines when there is a reference to it and when the reference is removed. Objects can also be visible to scripting elements through scripting-level variables. JSP Actions and Declarations define objects and their scope and whether they are available to scripting elements.

Page Scope Objects with the page scope are accessible only within the page where they are created. References to them are released after the response is sent back to the client or when the request is forwarded somewhere else.

Request Scope Objects with the request scope are accessible from pages processing the same request where they were created. References to them are released after the request is processed, unless the request is forwarded to a resource in the same runtime. In this case the object persists.

Session Scope Objects with the session scope are accessible from pages processing requests within the same session. References to them are released when the session ends. Session or state information can be placed in, or retrieved from, objects with this scope. Typically, applications consisting of several pages use these objects. For example, a shopping cart application might have a page that places user selections into an object with session scope, enabling subsequent pages to access the information.

Application Scope Objects with the application scope are accessible from pages processing requests that are in the same application as the one in which they were created. References are released when the runtime environment reclaims the ServletContext.

HPAS01DV10-11/13/01

57

HP-AS Developer’s Guide

Implicit JSP Objects Several objects are always available without first having to be declared. They can be used within any scriptlet or declaration. The following table lists implicit objects. Object request

Description Contains information about the current request. Scope: request Type: javax.servlet.http.HttpServletRequest

response

Contains methods for sending information in a response (i.e. cookies). Scope: request Type: javax.servlet.http.HttpServletResponse

pageContext

Page context for the JSP. The pageContext object is used by the _jspService( ) method to obtain the other implicit objects for the page. Scope: page Type: javax.servlet.jsp.PageContext

session

Session or state information can be placed in, or retrieved from, session objects. Typically, these objects are used by applications consisting of several pages. Scope: session Type: javax.servlet.http.HttpSession

application

The servlet context obtained from the servlet configuration object. This is generally used by a JSP page to communicate with the web container. Scope: application Type: javax.servlet.ServletContext

out

The object that writes to the output stream. Scope: page Type: javax.servlet.jsp.JspWriter

config

The ServletConfig for this JSP page. ServletConfig contains information that is passed from the web container to the JSP page. Scope: page Type: javax.servlet.ServletConfig

page

The instance of the page implementation class processing the current request. For Java, "page" is a synonym for this. page. Scope: page Type: java.lang.Object

58

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

Object exception

Description The uncaught exception resulting in an error page being invoked. Scope: page Type: java.lang.Throwable

JSP Web Application Tutorial The following tutorial walks you through creating a JSP page that outputs the current time on the server. The tutorial demonstrates how a JSP page is used to include dynamic content

Part 1 – Creating a Web Application Directory In this part of the tutorial, you will create a web application directory structure. The web application directory structure is a set of defined directories that make up every web application. In addition, the web application must contain a deployment descriptor (web.xml). To create a web application directory: 1

Create a document root directory called time. For example, D:\time. This directory can be located anywhere on your file system; however, you should select a central location within the HP-AS installation directory for all your web applications. A central location facilitates development and makes porting the application into a runtime environment more efficient.

2

Create a subdirectory called WEB-INF. You must have this directory when using the standard deployment descriptor (web.xml). Note: As per the servlet specification, WEB-INF must be entered in all capitals.

3

Create two subdirectories under WEB-INF called lib and classes. These are standard directories found in all web applications. Your web application directory should appear as follows: time /WEB-INF /WEB-INF/lib /WEB-INF/classes

HPAS01DV10-11/13/01

59

HP-AS Developer’s Guide

Part 2 – Creating the JSP The following JSP uses java.util.Date to determine the time on the server. The results are obtained using the JSP action element useBean and getProperty. To create the time JSP: 1

Create a new text file using a text editor.

2

Type the following code into the text file. Time JSP Time Example This example uses java.util.Date and the JSP useBean and getProperty action elements The time on the server Hours: Minutes:

3

Save the file as time.jsp in the time web application root directory.

4

Close the file.

Part 3 – Creating the Deployment Descriptor A deployment descriptor (web.xml) is used to define configuration items for a web application that the container must implement (i.e., security, servlet mappings). For this sample, the web.xml only defines the welcome file element. The welcome file element allows the application to automatically start on time.jsp. To create a deployment descriptor for the time application: 1

Create a new text file using a text editor.

2

Type the following code into the text file. time.jsp

60

3

Save the file as web.xml in the WEB-INF directory.

4

Close the file.

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

Part 4 – Deploying the Web Application In this part of the tutorial, you will deploy the application. In a production environment, your applications are packaged as EAR files. However, for this tutorial you will be deploying the web component as a standalone web component. For more information on deploying applications, see Chapter 3, Assembling and Deploying J2EE Applications. To deploy the web application: 1

Using a text editor, open the j2ee-partition-service-config.xml file from HP-AS's /config/hpas directory.

2

Create the following entry within the node, substituting the URL attribute with the full path to your time web application directory. The URL must include the document root directory (i.e. D:/myapps/time/).

3

Save and close j2ee-partition-service-config.xml. Note: you can also deploy applications using RadPak or the HP-AS System Console. Both of these tools automatically create entries in j2ee-partition-service-config.xml as well as provide additional deployment features.

Part 5 – Contacting the Application The web application is contacted using a browser. From the browser, you will enter a URL to the application using the context path you entered in j2ee-partition-service-config.xml. In addition, the URL will contain the host where the application is located and the port that HP-AS is listening for HTTP messages. To contact the time application: 1

Start the server using the procedures detailed in Chapter 2.

2

In the Log Browser or the console window's log output, search to find which port the HP-AS is listening on. By default, HP-AS listens on port 9090. If port 9090 is unavailable, HP-AS tries ports 9091and 9092 before searching for the first available port. You can also specify a specific port in httpservice-config.xml, located in the HP-AS /config/hpas directory.

3

Start your browser.

4

In the browser’s address field, type the following URL substituting with the port number that HP-AS is listening on. Make sure you include the colon between the host and port. In addition, the URL contains the context path /time that was defined for this application in j2ee-partition-serviceconfig.xml. http://localhost:/time The following page displays:

HPAS01DV10-11/13/01

61

HP-AS Developer’s Guide

Writing JSP Tag Extensions In addition to using standard JSP tags, the JSP component technology allows you to define your own action tags for common tasks in a JSP. Action tags are JSP elements that affect the current output stream and may create objects. Custom tags are organized into a tag library (taglib). Taglibs define declarative, modular functionality that can be reused by any JSP. Taglibs reduce the necessity to embed large amounts of Java code in your JSPs by moving the code into special implementation classes, which are then referred to from a JSP using customized tags. Taglibs make authoring JSPs easier for both web page authors and tools that expose the functionality that is encapsulated by the library to the author. Following the JSP convention, taglibs separate tasks between developers who create the tag libraries and the authors that utilize them, making development more efficient. If you are a web page author, you may need a Java programmer to create tag handlers; however, with minimal Java knowledge, you can start creating your own tag handlers. In addition, there are many web sites offering taglibs that you can download. A tag library consists of the Tag Library Definition (TLD) and a set of tag handlers, which are Java classes. The tag syntax that you use in your JSP is defined in the TLD. This file also maps the syntax to the correct tag handler.

Creating a Tag Handler Tag Handlers are Java classes that are executed by the container when a defined tag is encountered on a JSP page. Generally, a tag handler is created to execute for code that is frequently repeated throughout a JSP, like SQL statements for accessing a database. The package javax.servlet.jsp.tagext contains the classes and interfaces needed to implement a tag handler. In particular, tag handlers implement either the Tag interface or the BodyTag interface. However, there are default class implementations of each of these interfaces (TagSupport and BodyTagSupport) that facilitate creating tag handlers. The Tag interface defines the basic protocol between a Tag handler and JSP implementation class and is required for every action you create. The BodyTag interface extends Tag by defining additional methods that let a Tag handler access the body 62

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

of an action element. Because all tag handlers implement the javax.servlet.jsp.tagext.Tag interface (either directly or indirectly), the web container knows how to execute the tag handler. The following sample code is a simple tag handler that implements TagSupport: package com.hpbluestone.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** * A simple Tag that displays a Hello World message. */ public class HelloWorld extends TagSupport { /** * Method called at end of Tag * @return either EVAL_PAGE or SKIP_PAGE */ public int doEndTag() throws JspException { try { pageContext.getOut().write("Hello World!"); } catch(java.io.IOException e) { throw new JspException("IO Error: " + e.getMessage()); } return EVAL_PAGE; } }

This tag handler implements TagSupport and overrides the doEndTag method. Tag handlers usually override this method to carry out their processes. Tag handler are compiled and placed in the WEBINF/classes directory of your web application. The package structure you use for the handler must match the package structure in the classes directory. There is a certain order of method calls, defined in the JSP specification, that determines what methods of the tag handler are called, and in what order they are executed. As a result, your tag handlers can be very complex; however, you must write your code within the specification. For more information on supported methods and the order in which they are executed, see the JSP specification and JSP Javadocs from Sun Microsystems.

Creating a TLD To use a tag handler in your JSP, you must create a TLD. TLD documents are XML documents that define the syntax ( and ) of your action element and map it to the appropriate tag handler. The syntax that you choose in the TLD is then used in your JSP. At runtime, the tag names in your JSP are matched to the names in the TLD and the appropriate tag handler is executed. A single TLD may include many custom actions. Each TLD that you create is considered a Tag Library. It is usually a good idea to organize custom actions according to functionality and create a separate TLD for each functionality group. TLDs are saved with a .tld file extension. Like JSPs, TLDs can be edited using text editor or an IDE that supports tag extensions. There are no restrictions for where TLDs are saved in a web application directory structure. However, TLDs are often placed in a directory called tlds under the WEB-INF directory (WEB-INF/tlds). The following is a sample TLD file that was created for the Hello World tag handler created in the previous section: 1.0 1.1 hw My first Tag library hello com.hpbluestone.tags.HelloWorld

This TLD describes a hello world tag library. The library consists of only one tag (), for which the execution is handled by the com.hpbluestone.tags.HelloWorld tag handler. Note: Only one short name is used for a single TLD.

Using a Custom Tag Custom tags are implemented in a JSP after you have created a TLD document and Tag handlers. To implement a custom tag, you need to include a taglib directive on your JSP. The taglib directive gives the URI location of the TLD file, which maps tag names to tag handlers. In addition, the taglib directive must appear before you use custom tags in a JSP. The taglib directive appears as follows.

This directive includes a URI attribute that points to a TLD file and specifies the prefix that will be used for each custom tag. Since the TLD file contains information on which class handles which tag, when the JSP engine encounters a custom tag, it knows what class to call to execute the tag. As defined in the TLD, the custom action has a . When you use a custom tag, you can supply both the directive prefix, and the name separated by a colon. For example: Note: When using a custom tag, you must specify the same prefix that is defined in the directive. In addition, you can use multiple directives on a single JSP.

The following example demonstrates a JSP that includes a taglib directive and uses the custom hello world action. Hello World Tag Library Tutorial was sent from the Hello World Tag Library Hours: Minutes:

64

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

Taglib Web Application Tutorial In this tutorial, you will create a custom tag and then deploy a web application that contains a JSP that uses the custom tag. The tag handler for the tag simply prints out a message.

Part 1 – Creating a Web Application Directory In this part of the tutorial, you will create a web application directory structure. The web application directory structure is a set of defined directories that make up every web application. In addition, the web application must contain a deployment descriptor (web.xml). To create a web application directory: 1

Create a document root directory called hellotlb. For example, D:\hellotlb. This directory can be located anywhere on your file system; however, you should select a central location within the HP-AS installation directory for all your web applications. A central location facilitates development and makes porting the application into a runtime environment more efficient.

2

Create a subdirectory called WEB-INF. You must have this directory when using the standard deployment descriptor (web.xml). Note: As per the servlet specification, WEB-INF must be entered in all capitals.

3

Create two subdirectories under WEB-INF called lib and classes. These are standard directories found in all web applications.

4

Create a directory under WEB-INF called tlds. This is the directory where your tld will be saved. Your web application directory should appear as follows: hellotlb /WEB-INF /WEB-INF/lib /WEB-INF/classes /WEB-INF/tlds

Part 2 – Creating the Tag Handler In this part of the tutorial, you will create a tag handler that executes every time a custom tag is found in the JSP. This tag handler outputs a hello world message. To create the hello tag handler: 1

Create a new text file using a text editor.

2

Type the following code into the text file. package com.hpbluestone.tags; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; /** * A simple Tag that displays a Hello World message. */ public class HelloWorld extends TagSupport {

HPAS01DV10-11/13/01

65

HP-AS Developer’s Guide

/** * Method called at end of Tag * @return either EVAL_PAGE or SKIP_PAGE */ public int doEndTag() throws JspException { try { pageContext.getOut().write("Hello World!"); } catch(java.io.IOException e) { throw new JspException("IO Error: " + e.getMessage()); } return EVAL_PAGE; } }

3

Save the file as HelloWorld.java in the classes directory in the com.hpbluestone.tags package.

4

Compile the file using javac.

Part 3 – Creating the TLD In this part of the tutorial, you will create the Tag Library Definition (TLD). TLD documents are Extensible Markup Language (XML) documents that define each tag in a library. The sample TLD file that you will create describes a HelloWorld tag library. The library consists of only one custom tag () for which the execution is handled by the com.hpbluestone.tags.HelloWorld tag handler created in Part 2. To create the TLD: 1

Create a new text file using a text editor.

2

Type the following code into the text file. 1.0 1.1 hw My first Tag library hello com.hpbluestone.tags.HelloWorld

66

3

Save the file as helloworld.tld in the WEB-INF/tlds directory of the hellotlb web application.

4

Close the file.

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

Part 4 – Creating the JSP Page In this part of the tutorial, you will create the JSP that uses the tag defined in Part 3. To create the JSP: 1

Create a new text file using a text editor.

2

Type the following code into the text file. Hello World Tag Library Tutorial was sent from the Hello World Tag Library Hours: Minutes:

3

Save the file as helloworld.jsp in the root directory of the hellotlb web application directory.

Part 5 – Creating the Deployment Descriptor In this part of the tutorial, you will create the Deployment Descriptor (web.xml) for the application. web.xml is used to define configuration items (init parameters, servlet mappings, welcome file, security, tag libraries, etc.) for a web application. To create a deployment descriptor for the hellotlb application: 1

Create a new text file using a text editor.

2

Type the following deployment descriptor code into the text file. helloworld.jsp /WEB-INF/tlds/helloworld.tld /WEB-INF/tlds/helloworld.tld

3

Save the file as web.xml in the WEB-INF directory of the web application directory created in Part 1.

HPAS01DV10-11/13/01

67

HP-AS Developer’s Guide

Part 6 – Deploying the Application In this part of the tutorial, you will deploy the application. In a production environment, your applications are packaged as EAR files. However, for this tutorial you will be deploying the web component as a standalone web component. For more information on deploying applications, see Chapter 3, Assembling and Deploying J2EE Applications. To deploy the web application: 1

Using a text editor, open the j2ee-partition-service-config.xml file from HP-AS's /config/hpas directory.

2

Create the following entry within the node, substituting the URL attribute with the full path to your hellotlb web application directory. The URL must include the document root directory (i.e. D:/myapps/hellotlb/).

3

Save and close j2ee-partition-service-config.xml. Note: you can also deploy applications using RadPak or the HP-AS System Console. Both of these tools automatically create entries in j2ee-partition-service-config.xml as well as provide additional deployment features.

Part 7 – Contacting the Application The taglib web application is contacted using a browser. From the browser, you will enter a URL to the application using the context path you entered in j2ee-partition-service-config.xml. In addition, the URL will contain the host where the application is located and the port that HP-AS is listening for HTTP messages. To contact the application: 1

Start the server using the procedures detailed in Chapter 2.

2

In the Log Browser or the console window's log output, search to find which port the HP-AS is listening on. By default, HP-AS listens on port 9090. If port 9090 is unavailable, HP-AS tries ports 9091 and 9092 before searching for the first available port. You can also specify a specific port in httpservice-config.xml, located in the HP-AS /config/hpas directory.

3

Start your browser.

4

In the browser’s address field, type the following URL, substituting with the port number that HP-AS is listening on. Make sure you include the colon between the host and port. In addition, the URL contains the context path /hellotlb that was defined for this application in j2ee-partition-serviceconfig.xml. http://localhost:/hellotlb The following page displays:

68

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

Adding Security to a Web Component The HP-AS Servlet Container implements all of the security requirements container in the servlet 2.3 and J2EE 1.3 specifications. The following sections describe how these requirements have been implemented and how they can be used to add security to HP-AS web components.

Roles The Servlet Container does not use logical mappings for roles. The roles that are specified in the deployment descriptor are the actual roles from the operational environment. In order to implement these roles, the and nodes must be used, as follows: manager NONE manager

HPAS01DV10-11/13/01

77

HP-AS Developer’s Guide

Notice that you must associate the previously defined role with the resource collection. This is accomplished through the element. Following the above example, only users that have a manager role can access the /index directory. In addition, the element can be used to define that SSL is a requirement. If INTEGRAL or CONFIDENTIAL is defined, users must be using SSL in order to access the resource. The final elements defines the login process: FORM /login/login.jsp /login/loginFailed.jsp

Using the node, you can define that the application is using a form to login. Forms are very popular; however, you can also use "BASIC", "DIGEST", or "CLIENT-CERT". See the servlet specification for definitions of these login types. Using the node, we can also define the form login page and the form error page. Our application uses both of these pages. These pages are registered with the web container and are automatically displayed when a user tries to access a restricted resource or when an invalid username and/or password are supplied.

Part 5 – Deploying the Application In this part of the tutorial, you deploy the application. In a production environment, your applications are packaged as EAR files. However, for this tutorial you will be deploying the web component as a standalone web component. For more information on deploying applications, see Chapter 3, Assembling and Deploying J2EE Applications. To deploy the web application: 1

Using a text editor, open the j2ee-partition-service-config.xml file from HP-AS's /config/hpas directory.

2

Create the following entry within the node, substituting the URL attribute with the full path to your FormSecurity web application directory. The URL must include the document root directory (i.e. D:/myapps/FormSecurity/).

3

Save and close j2ee-partition-service-config.xml. Note: you can also deploy applications using RadPak or the HP-AS System Console. Both of these tools automatically create entries in j2ee-partition-service-config.xml as well as provide additional deployment features.

Part 6 – Contacting the Application The FormSecurity web application is contacted using a browser. From the browser, you enter a URL to the application using the context path you entered in j2ee-partition-service-config.xml. In addition, the

78

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

URL will contain the host where the application is located and the port that HP-AS is listening for HTTP messages. To contact the application: 1

Start the server using the procedures detailed in Chapter 2.

2

In the Log Browser or the console window's log output, search to find which port the HP-AS is listening on. By default, HP-AS listens on port 9090. If port 9090 is unavailable, HP-AS tries ports 9091 and 9092 before searching for the first available port. You can also specify a specific port in httpservice-config.xml, located in the HP-AS /config/hpas directory.

3

Start your browser.

4

In the browser’s address field, type the following URL, substituting with the port number that HP-AS is listening on. Make sure you include the colon between the host and port. In addition, the URL contains the context path /FormSecurity that was defined for this application in j2ee-partitionservice-config.xml. http://localhost:/FormSecurity The following page displays:

5

Click the link to the restricted Hello World page. The login page displays.

HPAS01DV10-11/13/01

79

HP-AS Developer’s Guide

80

6

Enter your username and password and click Log in. The Hello World JSP displays.

7

Click the link to log out of the application.

HPAS01DV10-11/13/01

Chapter 4: Developing Web Components

HPAS01DV10-11/13/01

81

Chapter 5

Developing EJB Components Introduction The HP-AS allows you to develop and deploy applications that use Sun Microsystems' Enterprise JavaBeans (EJB) technology. This technology is a server-side component model that is part of the J2EE architecture. The EJB Container Service supports most features from the EJB 2.0 specification while continuing to comply with the J2EE 1.2 specification. This chapter provides the information that you will need to: •

Deploy applications containing EJBs that are compliant with Sun’s specification using the EJB Container. The container can be used in a client-server environment or in process with other J2EE containers.



Develop and deploy EJBs using HP RadPak. This tool creates EJB modules, deployment descriptors, and database mappings for Container Managed Persistence (CMP) entity beans and the EJB JAR file. RadPak also provides facilities to package EJB JARs into Enterprise ARchive (EAR) files.



Incorporate role-based security for EJBs using the HP-AS security framework.



Incorporate transactioning using the HP Transaction Service (HPTS).

CORBA and the Interoperable Naming Service In HP-AS, EJBs are exposed as CORBA objects. HP-AS also provides an implementation of the Interoperable Naming Service (INS). EJBs are registered by name during deployment. The INS is read-only from outside the EJB Container. Other clients cannot bind to the INS. The INS has dependencies on other HP-AS services and, therefore, needs to operate inside of HP-AS. The INS is located using corbaloc URLs. The corbaloc URL is typically specified as an initialization parameter to the ORB. For additional information about the Corbaloc Service and load balancing client requests, refer to the HP-AS Technical Guide.

HP-AS01DV10-11/13/01

83

HP-AS Developer’s Guide

Iona Orbix2000 Integration Iona Orbix2000 is bundled with the HP-AS product. Orbix2000 is a high-performance, CORBA ORB. It fully supports the CORBA 2.3 specification and supports a number of significant elements of the CORBA 2.4 and 3.0 specifications. The EJB Container uses the ORB as the default transport for remote clients.

EJB CMP 2.0 Support for CMP 2.0 is an early access feature. Early access features are significant, completed features that are stable enough to be included with the product but have not been fully tested and/or documented. The EJB 2.0 specification defines a new model for CMP. EJB 2.0 is not backward-compatible with EJB 1.1. The most important goals of the new model are as follows: •

More robust functionality.



Additional portability.



Opening up the EJB platform to more active participation from object-relational mapping vendors.

EJB 2.0 also requires that EJB servers continue to support deployment of their 1.1 CMP implementations so that existing applications can be ported to new software releases.

Features and Advantages of CMP 2.0 The following is a list of the features that are new to CMP 2.0:

84



Increased ease of porting a CMP implementation between application server vendors. Mapping tools are not as tightly integrated with each application server platform.



Better definition of bean relationships, especially for scenarios where a CMP bean has references to other CMP beans that must be persisted on an update.



CMP beans are coded as abstract classes and further specified by the information in the deployment descriptor. Abstract methods for accessors and mutators are specified and used by the bean developer in the business methods of the bean.



A bean instance does not define any persistent data members. The Persistence Manager is responsible for providing the concrete implementation of the CMP bean, including an internal representation of the persistent data, the mapping to the back-end datastore, and implementations for query methods.



Query methods are defined using a new query language, EJB-QL, which is based on SQL 92.



CMP vendors can use lazy and partial object graph loading as well as more sophisticated data caching and dirty data detection. The inherent complexity of these mechanisms is hidden from application developers.

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

Local Interfaces Local and local home interfaces have been introduced in the EJB 2.0 specification and can be defined for session beans and entity beans. The container wraps the methods defined in local interfaces in an analogous fashion to the way the remote and home interfaces are used. Both local and remote views can be defined for the same bean. These interfaces reduce the overhead of access by using pass-byreference semantics. Changes made by a business method using pass-by-reference semantics to a parameter object will effect the state of the object in the caller. Any EJB that is acting as a client to another EJB, including message-driven beans, session beans and entity beans, can use local interfaces. Servlets and JavaServer Pages (JSPs) can also make calls to EJBs using local and local home interfaces if both the client and target EJB are located within the same JVM.

Home Methods Home methods are implemented according to the EJB 2.0 specification and apply only to entity beans. These methods expose business methods that are not specific to any entity bean instance. The following code listing provides an example of a home method defined in a bean implementation class. In this example, ejbHome is pre-appended to the corresponding name of the method in the home interface. public float ejbHomeLivingIndex (String state, float salary) { ... }

The corresponding method declared in the home interface would be as follows: public float livingIndex(String state, float salary);

Improved support for JMS and Message Driven Beans HP-AS includes a tighter integration between message-driven beans and JMS. New features in this release include: •

Both SonicMQ, which is bundled with HP-AS, and the container-supported XA transactions for JMS. SonicMQ includes a XAResource API, which increases transactional capabilities and allows the JMS server to be integrated into global transactions as a participant in the two phase commit protocol..



Both SonicMQ and the container now support the JMS ConnectionConsumer interface, which allows for the concurrent processing of messages.

Enhanced Deployment Capabilities The HP-AS can deploy EAR files and Web ARchive (WAR) files. Deployment can be performed through the J2EE Partition Service or using the RadPak tool. The System Console's JMX Browser can be used to specify the deployment of an EJB JAR, WAR, or EAR file. All files are deployed to a given application space. In the case of EJBs, the application name is assigned based on the name of the EAR file.

HP-AS01DV10-11/13/01

85

HP-AS Developer’s Guide

Re-deployment of an EJB An EJB can be deployed at any time after the EJB Service has initialized. If the EJB is packaged in an EAR file there are no restrictions on how it can be modified. If an EJB JAR is deployed outside of an EAR the client facing interfaces cannot be modified.

Individually-Configurable Beans Some EJB properties can be configured individually using an HP EJB deployment descriptor (i.e., hpejb-JAR.xml). This descriptor is maintained inside the EJB JAR file in the META-INF folder. The individually-configurable bean information takes precedence over the default configuration information. For additional information about individually configurable beans, refer to the HP-AS Administrator's Guide. Note: The EJB deployment descriptor is not required in addition to the standard EJB deployment descriptor (i.e., ejb-JAR.xml).

HP RadPak HP-AS provides a new J2EE tool called HP RadPak. RadPak provides EJB generation that can be used both from the command line and through a graphical interface. In addition to EJB generation, RadPak includes several new features including JAR file browsing and editing. When a JAR file is opened in the RadPak File Browser, various editors and third party tools can be specified for working with Java source code, XML files, or any other file type. The HP RadPak tool provides the following features for working with EJBs. •

Automatic discovery of EJBs that are given a root directory. This greatly reduces user input.



EJB JAR file editing.



An EJB Project Wizard that steps the user through EJB packaging, including compilation of EJB source code.



Creation of an EJB JAR deployment descriptor using the EJB Project Wizard.



An XML DOM presentation of the EJB JAR deployment descriptor, for easier viewing and editing of the descriptor.



86

c

Integration with the Jakarta Ant project to perform EJB generation; the Ant build file can be edited for a customized build process, and/or transferred to the EJB command line generation tool for automated build processes. There are two new Ant tasks available for the developer involving generation and deployment. Please reference the RadPak help system documentation.

c

CMP mapping according to the EJB 1.1 specification.

Ability to deploy and manage EJB JAR and EAR files.

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

HP Deployment Descriptor The standard EJB JAR deployment descriptor defines the component and provides the information necessary for the container to deploy it. In some cases, the standard descriptor does not provide enough information for all deployment scenarios. The HP EJB deployment descriptor, hp-ejb-JAR.xml provides the ability to configure beans individually. The entries made in hp-ejb-JAR.xml will override default settings in the EJB Service configuration file. Except for message-driven-beans, an HP EJB deployment descriptor is not required to deploy an EJB JAR. For message-driven beans, the HP EJB deployment descriptor specifies a destination topic or queue and a connection factory for each MDB. The HP EJB JAR deployment descriptor, hp-ejb-JAR.xml, can be packaged inside each EJB JAR file. For detailed information about the XML schema for this deployment descriptor, refer to Appendix A: HP-AS Configuration Files in the HP-AS Administrator's Guide.

Aliasing the Name for an EJB It is a common requirement for an external client to require an alternative to the ejb-name to link client lookups to deployed beans. A legal ejb-name (e.g., com.hp.mw.ejb.MyBean) does not map to a valid name for binding object references into CORBA COSNaming implementations. The HP proprietary deployment descriptor allows clients to specify an alternative advertised-name, which can be used to identify a deployed EJB.

Assembly and Deployment For detailed information about assembling and deploying J2EE components, refer to Chapter 3 of this guide.

Stateless Session Beans Coding Basics Session beans are intended to encapsulate business logic. Stateless beans do not maintain conversational state and are not specific to any one client. Session beans can handle two transaction types. Session beans can make use of Container-Managed Transactions (CMT). Business methods are marked using the EJB deployment descriptor with transaction attributes that the container uses to control transaction boundaries. Session beans can also use Bean-Managed Transactions (BMT). The container has minimal control over the transaction when using BMT. The bean developer must explicitly handle the start and close of transactions as well as the commit or rollback on a transaction.

HP-AS01DV10-11/13/01

87

HP-AS Developer’s Guide

Home and Remote Interfaces Home Interface When a client performs a JNDI lookup on an EJB, the lookup returns a reference to a home object which implements a home interface. The interface exposes the following: •

Methods for the creation and removal of an EJB instance



A method to access the EJBMetaData interface for the session bean



A method to obtain a handle for the home interface

Create Methods A stateless session home contains one create method. The create method defined in the home interface corresponds to the same method name in the implementation class except that “ejb” is pre-appended to the implementation method and the “C” in create becomes a capital letter. The return type of a create method for a home interface is the session bean’s remote interface or, for a local home interface, the return type is a local interface. The throws clause of a create method on the home interface should include the java.rmi.RemoteException and the javax.ejb.CreateException. The throws clause for a create method on the local home interface is only required to throw a javax.ejb.CreateException. The following illustrates a home interface example for a remote client: public Account create() throws CreateException, RemoteException;

The following illustrates a local home interface example: public EmployeeLocal create() throws CreateException;

Note that the local home interface does not throw a RemoteException. The following illustrates how a client obtains a stateless session bean reference: AccountHome accountHome = ...; Account account = accountHome.create();

Remove Methods for Home and Local Home Interfaces There is no mapping between an interface remove method and the ejbRemove method on the bean instance. ejbRemove is only called by the container, in order to remove a bean instance, based on the container’s resource management protocol. Bean instances are discarded when system exceptions occur but ejbRemove is not called at this time.

88

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

Remote Interface The remote interface declares the business methods that are written by the developer and contained in the bean instance class. During the generation of an EJB Jar file, an implementation class is created for the remote interface. The implementation class is used by the EJB Container at runtime, and is called the EJB object. After a reference to the home object has been obtained (see the “Home Interface” section), create can be called on the home object, which in turn calls ejbCreate on the bean instance. Around the same time, an EJB object is also created. A reference to the EJB object is returned to the client (true for non-CORBA clients). The client never accesses the bean instance directly, but operates on the EJB object, which calls corresponding methods on the bean class. In addition to developer-supplied business methods, the remote interface extends javax.ejb.EJBObject, which contains the following methods: getEJBHome is used to obtain the remote home object: public EJBHome getEJBHome() throws java.rmi.RemoteException

getPrimaryKey will generate an exception for stateless session beans: public java.lang.Object getPrimaryKey() throws java.rmi.RemoteException

remove has no mapping to the bean instance ejbRemove method for stateless session beans: public void remove() throws java.rmi.RemoteException, RemoveException

getHandle is used to obtain a handle to the EJBObject. The handle can be used to re-create a reference to the EJBObject: public Handle getHandle() throws java.rmi.RemoteException

isIdentical(EJBObject obj) is used to test if both references were created for the same EJB deployment: public boolean isIdentical(EJBObject obj) throws java.rmi.RemoteException

The local interface, which extends EJBLocalObject, contains methods that provide the same relative functionality as the remote interface, except that no method is provided to obtain a handle to the EJBLocalObject.

Stateless Session Bean Configuration Pooling Stateless Session Beans Each stateless session bean home maintains a pool of bean instances that are wrapped by the container. A wrapper-instance pair is removed from the pool for the duration of a method invocation on the EJB. The EJB service configuration, ejb-service-config.xml, file has the following settings to control the bean pool size:

HP-AS01DV10-11/13/01

89

HP-AS Developer’s Guide

When the pool is empty or no bean is available to service a request, a new wrapped bean instance is created by the container. Stateless session EJBs are not created when create is called on the home. Instances are created on demand as business methods are called. For additional information about the ejb-service-config.xml file, refer to Appendix A: HP-AS Configuration Files in the HP-AS Administrator's Guide.

Deploying a Stateless Session Bean A session bean uses the EJB JAR deployment descriptor, and can optionally use the HP EJB JAR deployment descriptor. The HP EJB JAR deployment descriptor (i.e., hp-ejb-JAR.xml) can be packaged inside each EJB JAR file. This descriptor overrides any general stateless session bean settings in the EJB Service configuration file, ejb-service-config.xml. When a session bean is deployed, HP EJB JAR descriptor information is checked against an XML schema. It is recommended that EJBs should be deployed using an EAR file. This enables the session bean to be associated with an application name. The application name used is the name of the EAR file minus the .EAR extension. The application name serves as a way to partition naming contexts. An EJB deployed with an application name of “X” cannot lookup an EJB deployed with an application name of “Y” without providing mapping information in hp-ejb-JAR.xml. Applications collocated in the same JVM that contain inter-application EJB relationships must be configured to use CORBA as the transport mechanism due to class loading constraints in the JVM. An EAR file can also contain a servlet or JSP. The servlet/JSP is also associated with an application name. If the application name is different than that of the EJB, then the servlet/JSP will not be able to find the EJB within the same name space. Refer to the documentation about the HP proprietary servlet XML for an explanation of mapping from servlets to EJBs in other applications. The following code listing shows an hp-ejb-JAR.xml for two stateless session beans:

The bean pool size is configurable on a per-bean basis as shown.

90

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

Stateful Session Beans Coding Basics Stateful session beans are allocated to a specific client. Requests are always routed to the same bean on the server. State information is retained for the client across multiple method calls to the bean. In general, the length of a client’s session determines the life of a session bean. If a client times out, the EJB Container will remove the session bean. Session beans support both CMT and BMT.

Home and Remote Interfaces Home Interface When a client performs a JNDI lookup on an EJB, the lookup returns a reference to a Home object. The Home object implements either the EJBHome or EJBLocalHome interface. The interface exposes the following: •

Methods for the creation and removal of an EJB instance



A method to access the EJBMetaData interface for the session bean



A method to obtain a handle for the Home interface



Stateful session beans differ from stateless session beans in two important respects. Create methods can be defined with parameters and can be overloaded. The remove method results in an invocation to ejbRemove on the bean instance and invalidates the object. Subsequent access attempts will result in a NoSuchObjectException.

The following illustrates a home interface example with overloaded create methods for a remote client: public Account create(String name) throws CreateException, RemoteException; public Account create(String name, boolean repeatCustomer) throws CreateException, RemoteException;

Remote Interface The remote and local interfaces for stateful session beans have the same behavior as those defined for stateless session beans except for the remove method. The same semantics for the remove on the home apply to the remove methods in the remote and local interfaces.

HP-AS Stateful Session Bean Settings Stateful session beans can be passivated at the discretion of the container. Stateful session bean instances can be serialized to a local hard drive, in order to release resources when a client is not actively using the bean. The ejbPassivate and ejbActivate methods allow the container to instruct the bean to release critical and/or limited resources like file descriptors or database connections. The EJB service configuration file allows user control of the passivation policies as well as other settings. Refer to the EJB section of the HP-AS Administrator's Guide for additional information.

HP-AS01DV10-11/13/01

91

HP-AS Developer’s Guide

Note: Stateful session EJBs will not be garbage collected automatically if all client handles go away. Instead, they will be eligible to be reacquired with the handle until the timeout specified in the deployment descriptor. This thread will check at the user specified interval for timed out session beans and make them eligible for garbage collection. After they have been timed out, the beans are no longer accessible through the handle mechanism.

HP EJB JAR Deployment Descriptor A HP EJB JAR deployment descriptor (i.e., hp-ejb-JAR.xml) can be packaged inside each EJB JAR file. This descriptor overrides any general settings in the EJB Service configuration file. The following shows an example of an hp-ejb-JAR.xml for a stateful session bean:

As indicated above, passivation of stateful session beans is configurable on a per-bean basis. The session timeout setting is also configurable on a per-bean basis. Stateful session bean passivation is enabled. In this case, once the threshold limit of 1000 beans is reached, the container attempts to passivate eligible beans. The session timeout is set to 120 seconds. Note: Stateful session EJBs will not be garbage collected automatically if all client handles go away. Instead, they will be eligible to be reacquired with the handle until the timeout specified in the deployment descriptor. This thread will check at the user specified interval for timed out session beans and make them eligible for garbage collection. After they have been timed out, the beans are no longer accessible through the handle mechanism.

Entity Beans Coding Basics While session beans are intended to encapsulate business logic, entity beans are intended to encapsulate business data. Entity bean data can be persisted using either EJB 1.1 BMP or CMP in HPAS. CMP 2.0 is also available in as an early access feature through integration with Webgain’s Toplink for HP-AS.

BMP Entity Bean The persistence of an entity bean’s state to a persistent store is the responsibility of the bean provider using BMP. An entity bean synchronizes its state with the underlying data store through the ejbLoad and ejbStore methods. The bean provider must provide the implementation of these methods for a BMP bean.

92

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

CMP Entity Beans With CMP entity beans, the code required for persistence and the mapping of the bean to a persistent store is managed by the container and is not the responsibility of the bean provider. HP-AS currently provides two persistence options for CMP. For CMP 1.1, HP-AS has its own persistence engine and an HP RadPak mapping tool. For CMP 2.0, there is an integration with WebGain’s TopLink persistence engine and suite of mapping / persistence tools. Refer to the Employee Trail Map for examples of both types of entity bean code.

Entity Bean Primary Key (PK) Class The primary key class uniquely identifies an entity in the database. The primary key object can be a primitive type or a composite key of a compound data type. The primary key class must implement java.io.Serializable, and must follow all rules of a serializable object. Refer to the BMP or CMP tutorial in the EJB Tutorials Guide for an example of a primary key class.

Home and Remote Interfaces Home Interface When a client performs a JNDI lookup on an EJB, the lookup returns a home object. The home object implements either the EJBHome or EJBLocalHome interface. In addition to the previously discussed methods, entity beans expose the following in the entity bean home interface: •

Finder Methods



Home Business Methods

Create Methods An entity bean home interface can contain zero or more create methods, with the syntax of: create(…)

where, is optional. The name of a create method in a home or local home interface always starts with the prefix "create." Create methods generate a representation of entity data in a persistent store. The create method defined in the home interface corresponds to the same method name in the implementation class (for a given number of method parameters) except that “ejb” is pre-appended to the implementation method and the “C” in create becomes a capital letter. For example, if create(String myName, String yourName) is defined in the home interface, the corresponding method in the implementation class would be ejbCreate(String myName, String yourName). The return type of a create method for a home interface is the entity bean’s remote interface or, for a local home interface, the return type is a local interface. The throws clause of a create method on the Home interface for a remote client must include the java.rmi.RemoteException and the javax.ejb.CreateException. The throws clause for a create method on the local home interface for a local client is only required to throw a javax.ejb.CreateException. Additional user-defined, application level exceptions can be thrown.

HP-AS01DV10-11/13/01

93

HP-AS Developer’s Guide

The following illustrates a home interface example for a remote client: public interface AccountHome public Account create(String throws RemoteException, public Account create(String throws RemoteException, ... }

extends javax.ejb.EJBHome { myName, double balance) CreateException; accoundID, double balance) CreateException, maxBalanceExceededException;

The following illustrates a local home interface example: public EmployeeLocal create( int arg0, java.lang.String arg1) throws javax.ejb.CreateException;

Note: That the local home interface does not throw a RemoteException.

Remove Methods for Home and Local Home Interfaces Remove methods allow a client to remove an entity object. When remove is called, the data in the persistent store associated with the entity bean is deleted. Remove methods are defined by the javax.ejb.EJBHome interface for remote home interfaces or the javax.ejb.EJBLocalHome interface for local home interfaces.

Finder Methods Finder methods provide a way to locate an entity or collection of entities for a given home. The following illustrates two examples of finder methods in a home interface: public EmployeeLocal findByPrimaryKey( EmployeePK key ) throws javax.ejb.FinderException; public java.util.Collection findByName( java.lang.String name ) throws javax.ejb.FinderException;

Finders that return a single object will throw a javax.ejb.ObjectNotFoundException if the data does not exist. Finders that return collections will return an empty collection.

Home Methods Home methods apply only to entity beans, and expose business methods through the home interface that are not specific to any entity bean instance. The following illustrates a home method declared in the remote home interface: public float livingIndex(String state, float salary);

The corresponding method is defined in the bean implementation class. Note that ejbHome is preappended to the corresponding name of the method in the home interface: public float ejbHomeLivingIndex (String state, float salary) { … // apply business data to a set of entities }

94

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

Remote Interface The following methods have behavior that is unique to entity beans. getPrimaryKey is used to obtain the primary key of the EJBObject: public java.lang.Object getPrimaryKey() throws java.rmi.RemoteException

remove removes the entity data from the persistent store: public void remove() throws java.rmi.RemoteException, RemoveException

Design Considerations Re-entrance Entity beans can be configured to allow re-entrance through the EJB deployment descriptor. The indicator specifies whether the call chain originating with this entity bean for a given primary key can include a call to a business method on the same entity with the same primary key in the same transaction context. In general, entity beans should not be marked as re-entrant.

Valid CMP 1.1 Field Types The following field types are supported when using HP-AS CMP 1.1 implementation: Field Type

Description

Java Primitive Types

All Java primitive types are allowed, as well as java.lang.String, java.util.Date, the java.lang wrapper classes (Integer, Byte, etc.), the java.math types (BigDecimal, BigInteger), and the java.sql date/time types (Date, Time, Timestamp).

Collection Types

Collection types that are assignable from java.util.Vector, java.util.Hashtable or java.util.Enumeration are allowed. During the CMP mapping process, you will be prompted for the actual class to be held in the collection.

Other Classes

Classes that are mapped directly to an attribute in the database must provide a constructor that takes a single String value and a toString method that returns a String object representing the object's value as in java.lang.Integer. These classes have no public, non-static members.

Classes that are not mapped directly to an attribute in the database (e.g., are decomposed into more "primitive" types) must provide a no-argument constructor. These are classes that have public, nonstatic members of the above types.

HP-AS01DV10-11/13/01

95

HP-AS Developer’s Guide

Valid BMP Field Types In general, there are no restrictions for BMP field types other than that the field type must be supported by the database vendor or else converted to a supported type before use in a SQL statement.

EJB 2.0 CMP EJB 2.0 defines a new model for CMP. It is not backward compatible with EJB 1.1. Instead, it's a complete break with the old CMP model. The new model has several goals; most importantly, to provide more robust functionality, to add additional portability, and to open up the EJB platform to more active participation from object-relational mapping vendors. These objectives were not met within the EJB 1.1 model for CMP, however EJB 2.0 requires that EJB servers continue to support deployment of their 1.1 CMP implementations, so existing applications can be ported to new software releases. In EJB 2.0, a CMP bean is created with a complete abstract persistent schema. This schema provides a detailed description of the relationships between beans. An example is given below: Customer-Orders customer-has-orders one Customer orders java.util.Collection order-owned-by-customer many Order customer Order-Item order-has-item one Order item item-has-order one Item 96

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components



The EJB QL Language The CMP implementations of previous EJB iterations have suffered from a lack of portability; the definitions of the finder methods' query syntax and semantics were unique to each vendor's EJB Container. The EJB 2.0 specification addresses this limitation with the creation of EJB QL, an SQLlike query language that allows the bean provider to specify the finder query in a portable way. Once a bean developer defines the finder queries for the finder methods, it is the responsibility of the persistence manager to translate the query to the native language facilities of the data store being used. For example, the query can be translated into a SQL query that executes against a relational database. Thus, the finder method definitions are portable across containers and persistence managers. For example, a bean developer can create a findByCity(String city) finder method for a home interface of an EJB representing an employee. The developer would then define the query for the given method: FROM address WHERE address.city = ?1

This query translates to "select all employees that reside in the city indicated by the city argument." The EJB QL uses the abstract schema of the entity beans. In other words, the queries are defined in terms of the entity beans and their relationships to each other. In addition, the developer can use EJB QL to navigate to both locally defined and remote entity beans. The developer also has the option of traversing the abstract schema of any bean that is defined in the same EJB JAR file.

Finder and Select Methods Select methods are a new addition in EJB 2.0. They are special-purpose finder methods defined by the bean provider within a CMP entity bean instance. A developer writes them as abstract methods in the entity bean's implementation class and defines their semantics with an EJB QL query string. Select methods differ from finder methods in several ways. They are not specified in the entity bean's home interface and are therefore not available to client invocations. Rather, these methods are to be used by the bean developer internally as components of that bean's business logic. Unlike finder methods, the entity beans can return any value that can result from an EJB QL query (remember that finder methods return single or multiple remote interfaces to the entity bean). There are two types of select methods: Method

Description

ejbSelect

Executes a query that is not bound to a particular instance of the entity bean for which the select method is defined.

ejbSelectInEntity

Executes within the scope of a specific bean instance and with the identity of that particular instance.

The select methods a developer creates can return single or multiple values. If a select method is defined as returning only a single value, the bean developer must take care to define the query appropriately. Should the method return multiple values, the persistence manager will throw a FinderException. For this reason, it is expected that in most circumstances developers will define their

HP-AS01DV10-11/13/01

97

HP-AS Developer’s Guide

select methods returning multiple values. These methods return implementations of the java.util.Collection or java.util.Set interfaces.

Pooling Entity Beans Each entity bean home maintains a pool of bean instances that are wrapped by the container. The remote implementation / EJB instance pairs are removed from the pool for the duration of a transaction. The EJB Service configuration file has the following setting to control the bean pool properties:

When the pool is empty or no bean is available to service a request, a new wrapped bean instance is created by the container. For additional information about the ejb-service-config.xml file, refer to Appendix A: HP-AS Configuration Files in the HP-AS Administrator's Guide.

Connecting Entity Beans to a Database Entity beans use the HP-AS Connector Service as an implementation for JDBC connection management.. The Connector Service establishes a JDBC vendor driver, connection URL, user and password for database vendor login. An advertised-name is used to register a JNDI lookup name for the data source. The following is an example entry from the connector-service-config.xml file.. For reference information on connector-service-config.xml, refer to Appendix A: HP-AS Configuration Files in the HP-AS Administrator's Guide. hp-jdbc-tx BankApp_BMP org.hsqldb.jdbcDriver jdbc:hsqldb:{HP-AS_install_dir}\db\hsql\bankapp jdbc/BankDB true sa mypassword

In addition, a resource reference must be specified in the EJB JAR deployment descriptor. This reference matches the advertised-name specified in the connector service configuration file: jdbc/BankDB javax.sql.DataSource Container

98

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

The above reference must be specified for BMP and CMP entity beans. The res-auth element is for resource authorization and can be set to Container or Application. This should always be set to Container for CMP entity beans. BMP entity beans can use Application or Container. If Application is specified, the bean developer must supply code that provides the user name and password to access the data source. If Container is specified, user and password information will be taken from the connector service configuration file, connector-service-config.xml. To perform a JNDI lookup of a data source from an EJB (following the previous example), the following should be used for the lookup name: java:comp/env/jdbc/Employee

Read-Only Entity Bean Entity EJBs that will never be modified by a client can be marked as read-only. This removes the overhead of unnecessary updates on access. Entity beans are marked as read only in the hp-ejbJAR.xml deployment descriptor. ejbLoad is still called to refresh the entity bean's state from the database.

Deploying an Entity Bean Before deploying an entity bean to a HP-AS instance, verify that an appropriate database has been configured in the HP-AS Connector Service. The connector service establishes a JNDI name for each database entry. In addition, a resource reference must be specified in the EJB JAR deployment descriptor. The resource reference tag () in the EJB JAR deployment descriptor should match the JNDI name specified in the Connector Service configuration file. The following shows an example of an hp-ejb-JAR.xml for a CMP entity bean:

This bean is configured to use the CMP 1.1 implementation. The entity-passivation setting is set to false so the container does not call the ejbActivate and ejbPassivate methods. The read-only attribute is false so the bean is not marked as read only.

HP-AS01DV10-11/13/01

99

HP-AS Developer’s Guide

Message-Driven Beans Coding Basics Message-Driven Beans (MDBs) were introduced in the EJB 2.0 Specification. MDBs asynchronously process JMS messages from specific a topic or queue. Like stateless session beans, MDBs do not maintain conversational state for the client, although instance variables of a message-driven bean instance can maintain state across the handling of client messages. Unlike session or entity beans, MDBs do not employ remote or local interfaces. The client interacts with the MDB via JMS by sending messages to the JMS destination topic or queue to which the MDB is subscribed. In fact, MDBs are anonymous – they have no client-visible identity.

Figure 5.1: Message-Driven Bean Interface Requirements

MDBs must implement the interfaces javax.ejb.MessageDrivenBean and javax.jms.MessageListener. All MDBs require that the following methods be implemented: Method

100

Description

onMessage(javax.jms.Message)

This method is invoked by the EJB Container when a message is received for the destination to which the bean is subscribed. The message object is passed as a method parameter.

ejbRemove()

This method signals that the instance is in the process of being removed by the container. Note that there is no guarantee this method will be invoked under certain conditions. System exceptions thrown from the MDB or a crash of the EJB Container are two such situations.

setMessageDrivenContext(...)

This method is called by the bean's container to associate an MDB instance with its context, which is maintained by the container.

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

Method ejbCreate()

Description Each MDB class must have one ejbCreate method with no arguments. This method is not enforced by the interface, but is required by the EJB server at deployment.

Deployed MDBs automatically receive messages from a messaging service. They take full advantage of the transaction, security, and error handling mechanisms provided by the EJB Container, simplifying the handling of asynchronous messages.

Message-Driven Beans in HP-AS The HPAS implementation of MDBs is platform and vendor neutral, making it compatible with JMScompliant legacy Message Oriented Middleware. Internally, HP-AS provides a JMS service that acts as a bridge to the JMS provider. MDBs use this JMS service to obtain JMS administered objects such as connection factories and destinations. The JMS service provides the following: •

JMS connection pooling.



Dead JMS connection detection and recovery.



Concurrent message processing using ConnectionConsumer, which requires support by the JMS provider.



XA Support, which requires support by the JMS provider.

XA Transaction Support The X/Open XA specification provides definitions for transaction processing in resource managers like databases and messaging systems. The HP-AS JMS Service is XA compliant allowing JMS clients to participate in global transactions. XA support is an optional component of the JMS specification that requires support by both the JMS provider and the application server. The current specification was not intended to fully address the contract between the application server and the JMS provider. This portion of the specification will be addressed by the Java Connector Architecture (JCA) specification in the future. Currently, XA support for JMS clients within HP-AS is limited to Sonic Software’s SonicMQ JMS implementation. For JMS vendors that do not support XA, we provide an XA resource implementation that allows any JMS resource to be used within a global transaction. The XA resource does not fully support the two phase commit protocol, but performs a compensating transaction on the JMS session. This means that if the global transaction is committed, the local JMS transaction is committed through the session. Otherwise, the local JMS transaction is rolled back.

Concurrent Message Processing The HP-AS EJB Container achieves concurrent message processing using a ServerSession/ ConnectionConsumer implementation. This implementation is an optional part of the JMS specification, and must be implemented by both the application server and JMS provider. HP-AS can integrate with any JMS provider that supports this portion of the JMS specification.

HP-AS01DV10-11/13/01

101

HP-AS Developer’s Guide

Message-Driven Beans and EJB Security The EJB 2.0 specification insures that Message-Driven Beans (MDB) must establish a security identity used by the container during execution of the onMessage() method of the bean instance. This is accomplished by setting the run-as identity information in the deployment descriptor for the MDB instance. The run-as identity should be set in the security-identity section under the element: Administrator

Communication between an MDB and another EJB follows the same semantics as a method invocation from one EJB to another. When an MDB invokes methods on another EJB, the established run-as security-identity is used to determine whether the MDB has privileges to invoke a given method (unless that EJB also uses a run-as identity). In this way, security restrictions defined by the application designer for other EJB components are not compromised in a system using MDBs as the initiating client.

MDB Deployment The JMS server must be running before attempting to deploy an MDB. If the JMS server is not running when the EJB Container attemps to deploy an MDB, the bean is not deployed and a log message is emitted. The container does not attempt to re-deploy the MDB.

Accessing Enterprise Java Beans Using Local Interfaces Coding Basics EJBLocal and EJBLocalHome interfaces were introduced in the EJB 2.0 specification. A local interface provides optimized access to an EJB from a client co-located in the same JVM in a standardized way. Local interfaces reduce the overhead of access by using pass-by-reference semantics. Local interfaces can be applied to session beans and entity beans. They are applied in the same fashion as remote interfaces. Both local and remote interfaces can be applied to a single EJB. EJB clients can only make calls to EJBs using local interfaces if both the client and EJB are located within the same JVM. J2EE 1.3 also defines a mechanism for servlets to access local interfaces to EJBs. The following code listings provide examples of a local interface applied to a stateful session bean.

Local Interface Example package com.hp.mw.j2ee.containers.ejb.tutorials.local_interface; import javax.ejb.EJBException, javax.ejb.EJBLocalObject, java.util.Collection; public interface SongNameLocal extends EJBLocalObject { public abstract String reverse(String s); public abstract boolean addSongTitle(String songTitle); }

102

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

Local Home Interface Example package com.hp.mw.j2ee.containers.ejb.tutorials.local_interface; import javax.ejb.CreateException,javax.ejb.EJBLocalHome; // Referenced classes of package //com.hp.mw.j2ee.containers.ejb.tutorials.local_interface: // SongNameLocal public interface SongNameLocalHome extends EJBLocalHome { public abstract SongNameLocal create() throws CreateException; }

Looking Up an EJB With a Local Interface In order to lookup an EJB with Local interfaces from a local client, the client must specify a local reference. The local reference describes the interface requirements that the client has for the referenced EJB. Local references are described in the deployment descriptor through the ejb-local-ref element. Below is an example: Get Local Home for SongNameBean ejb/SongNameLocalHome Session com.hp.mw.j2ee.containers.ejb.tutorials.local_interface.SongNameLocalHome com.hp.mw.j2ee.containers.ejb.tutorials.local_interface.SongNameLocal SongNameBean

The local client would then use the following code to perform a lookup. Append the ejb-ref-name to the “java:comp/env/” environment naming context. InitialContext ctx = new InitialContext(); SongNameLocalHome songNameLocalHome = (SongNameLocalHome)ctx.lookup("java:comp/env/ejb/SongNameLocalHome"); SongNameLocal m_songNameLocal = songNameLocalHome.create();

EJB Security EJB Security at Run time EJB Container security is implemented using communication with a JAAS-based security service. The service provides JAAS authentication, while authorization is provided by the HP-AS access provider service. At design time, the RadPak tool can be used to specify security role assignments to each method of an EJB, as well as a role for . This information is added to the EJB deployment descriptor. When a user accesses a protected resource within the web container, their principle (usually a user name and password) is established and associated with a role. If the user invokes an EJB method, their principle is passed with the request. The HP-AS security service, using the information contained in the EJB deployment descriptor, verifies which methods are mapped to the principle's role. If the principle's role is mapped to the requested method, then the method is invoked; otherwise, an exception is thrown. If the EJB method in turn requests another method in a different EJB, the principle is passed with the request and must be verified by the called EJB.

HP-AS01DV10-11/13/01

103

HP-AS Developer’s Guide

When an EJB client invokes an EJB, and the client has not been authenticated, a “guest” user role is assumed to invoke the EJB methods. Therefore, if security is not being used, a “guest” user role should be assigned to the appropriate EJB methods (any methods required to run the application). If the deployer for a method in the home, remote, or local interface for an EJB defines no security role, the container will deny access to the caller. Container security can be disabled in the ejb-serviceconfig.xml file if this behavior is not needed.

Using the HP-AS Security Framework with EJBs The HP-AS security framework provides the facilities to incorporate authentication and authorization in deployed applications. Implementations are included with HP-AS for authentication and authorization against a database, or a XML security file. Before implementing security for your EJBs: 1

Configure HP-AS to use the appropriate persistence mechanism to store users, groups and roles in the access-provider-service-config.xml. For more information, see the security chapter in this guide.

2

Use the HP-AS configuration console to create users, groups and roles, and to define the appropriate associations.

3

Assign EJB methods to roles in the EJB deployment descriptor. The roles should correspond to those defined using the HP-AS configuration console. A list of available roles is also presented under the Security Role tab of the RadPak tool making the roles created in the security tool available. The roles are assigned to EJB methods using the Method Permissions tab located in the RadPak tool.

RadPak Code Generation RadPak provides EJB generation at the command line or using a graphical user interface. Internally, RadPak uses the Ant ejbJAR task to generate implementation classes and build the JAR file. After using the EJB Project Wizard within RadPak, the project folder will contain a build.xml file. The build.xml allows for compilation of EJB source code, copying of files, generation of implementation classes and compilation of implementation classes. The build file can be run outside of RadPak, to do so: 1

Download Ant, version 1.3.x

2

Copy radpak-optional.JAR from the RadPak patches directory and paste it into the lib directory of your Ant installation. This Jar provides additional ejbJAR task features.

3

Place radpak.JAR (located in the lib directory of your RadPak installation) in your class path, before executing ant.

4

Open a console, change directories to the location of the build.xml in your project folder. Enter “ant” on the command line. For more information on RadPak, refer to Chapter 11 of this guide.

104

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

Co-Located Client Access Lookup of EJBs within HP-AS does not require the any system properties to be set. Any environmental settings are automatically populated if the lookup is performed within HP-AS (from an EJB, JSP/servlet, or a non-enterprise bean). For a collocated EJB and client, all client JNDI lookups of EJBs are performed by: InitialContext ctx = new InitialContext(); ctx.lookup("java:comp/env/");

An ejb-ref-name should always be used for an EJB client JNDI lookup. The normal lookup syntax is “java:comp/env/{ejb-ref-name}. J2EE applications should be packaged in an EAR file. An EAR file can contain a servlet or JSP packaged inside a war. Do not package EJB classes (home, remote or bean implementation class) within a WAR file that is packed inside an EAR. A class loader will automatically find the EJB class dependencies if the EJB has been deployed. Within the EAR are the WAR file, the EJB JAR file and a deployment descriptor that must be named application.xml (as required by the EJB 2.0 specification). The descriptor specifies the EJB JAR and WAR file. Below is an excerpt from an EAR file descriptor: Artist_SongTitle JSP to ArtistSongTitle Bean ArtistTitle_gen.JAR ArtistSong_WebClient.war artistSongs

Note the context-root settings under the web element. The context-root is associated with the deployed WAR file, and is used in the URL of a web browser, when invoking a JSP. To access the WAR (and JSP contained within) through a browser URL, the entry would be: http://localhost:9090/artistSongs/

Where artistSongs is the context-root for the web application. If the servlet is in a separate EAR from the EJB, the servlet / JSP will not be able to lookup the EJB without specifying the application mapping in the HP proprietary, hp-web.xml. In addition, the EJB Container must be configured to use CORBA transport.

HP-AS01DV10-11/13/01

105

HP-AS Developer’s Guide

Remote Client Access There are four ways to configure a remote client to access EJBs.

Application Client Container Access The application can be deployed into the HP-AS application client container, which is a fully managed environment for EJB clients. In this case, the container automatically manages environment settings for JNDI lookup resolution. For more information, refer to Chapter 6, Developing Application Clients. The JNDI lookup of an EJB can be specified by: •

InitialContext ctx = new InitialContext();



ctx.lookup("java:comp/env/");

Ideally, a remote client application should be packaged inside an application client JAR file. The application client JAR file contains an application client descriptor, as well as a HP application client descriptor. Also, a MANIFEST file is used to determine the name of the remote client class to execute, which must have a main method. An example application client descriptor: application-client.xml: Remote_Client_to_EJB Remote Client to EJB ejb/LoanCalculator Session com.hp.mw.j2ee.containers.ejb.tutorials.remclient.LoanCalculatorHome com.hp.mw.j2ee.containers.ejb.tutorials.remclient.LoanCalculatorRemote LoanCalculator

An example manifest file is: Manifest-Version: 1.0 Main-Class: com.hp.mw.j2ee.containers.ejb.tutorials.remclient.LoanCalculatorClient

The EJB name can be mapped to an advertised name independent of the ejb-link mechanism.

106

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

The corresponding application-client.xml is: Remote_Client_to_EJB Remote Client to EJB ejb/LoanCalculator Session com.hp.mw.j2ee.containers.ejb.tutorials.remclient.LoanCalculatorHome com.hp.mw.j2ee.containers.ejb.tutorials.remclient.LoanCalculatorRemote

The ejb-ref-name in the HP application client descriptor corresponds to the ejb-ref-name in the standard application client descriptor. The application-name in the HP application client descriptor should match the application name in which the EJB JAR was deployed on the server. Normally, the EAR file name is used as the name of the application. Note: The name-server host and port attributes should be set to the port and machine where the Corbaloc service runs.

There are deployment examples in the form of a Windows batch file and an Ant file available from http://gallery.bluestone.com/HPASv8/tutorials for running the application client container For additional information, refer to the Application Client Container Tutorial in the EJB Tutorials Guide.

Client Access Outside the Application Client Container Clients deployed outside the application client container can use an HP JNDI SPI in one of two ways.

Access with the HP JNDI SPI The first mechanisms support lookups of the form “java:” To do so, create a Hashtable of environmental settings within the remote client code, and pass the Hashtable object to the InitialContext constructor. Settings that are required include the location of the HP CORBA client descriptor file (specified by the environment setting hp.configuration.file) and the specification of a HP SPI. This is illustrated by: Hashtable env = new Hashtable(); env.put("java.naming.factory.url.pkgs", "com.hp.mw.j2ee.corba.spi"); env.put("hp.configuration.file","C:\\remote-client-config.xml "); Context ctx = new InitialContext(env); ctx.lookup("java:comp/env/");

Alternatively, the environment properties can be configured in the standard jndi.properties file. In this case, the InitialContext constructor can be used with no arguments. The remote client configuration file contains two sets of information, the orb initialization information and the mapping of JNDI names to EJB homes as the following example shows. com.iona.corba.art.artimpl.ORBImpl com.iona.art.artimpl.ORBSingleton

HP-AS01DV10-11/14/01

107

HP-AS Developer’s Guide



The ejb-refs section defines the location of the corbaloc service and links to the deployed EJB. The following attributes appear within the distributed element: Attribute

Description

application-name

Refers to the application under which the EJB was deployed. The EJB should be deployed with an EAR, so that the application name is the name of the EAR file, minus the “.EAR” extension. In this case, the applicationname matches the name of the EAR.

name-server-host

Specifies the location of the corbaloc service. Normally, this is the same machine as the application server. However, if a Java LBB is used, the corbaloc service is located on the Java LBB machine, so the Java LBB machine name must be specified.

name-server-port

By default, the port is set to 2809. This can be modified in the corbaloc service configuration file.

ejb-ref-name

The name to use for the lookup on an EJB. Referring to the above example, the lookup name should be: “java:comp/env/ejb/LoanCalculator.”

advertised-name

The value for this attribute should match the advertised-name in the HP EJB deployment descriptor. If a HP EJB deployment descriptor is not packaged with the EJB, then this attribute should match the ejb-name given in the standard EJB deployment descriptor.

There are deployment examples in the form of a Windows batch file and an Ant file available from http://[KENIG TBD]/Tutorials/client_apps/java_ejb_client

for running the application client container Please reference the “Java Client Tutorial Without a Client Container” under the EJB Tutorials Guide for further information. Note: The HP CORBA client descriptor file can require modification. Verify that application-name matches the deployed EAR file name, minus the “.EAR” extension.

Access with the Conventional JNDI SPI Clients deployed outside the application client container, can also use the conventional JNDI syntax that omits the “java:comp/env.” In this case, the JNDI environment properties should be: java.naming.factory.initial=com.hp.mw.j2ee.corba.spi.COSNamingContextFactory java.naming.provider.url=corbaloc::localhost:2809/ApplicationName org.omg.CORBA.ORBClass=com.iona.corba.art.artimpl.ORBImpl org.omg.CORBA.ORBSingletonClass=com.iona.corba.art.artimpl.ORBSingleton hp.spi.orb.argument.name.1=-ORBdomain_name hp.spi.orb.argument.value.1=localhost

java.naming.provider.url specifies the location of the corbaloc listener (a corbaloc URL). “ApplicationName” in the above example should correspond to the application in which the EJB was deployed. Normally, the application name is the same as the EAR file name, minus the “.EAR” extension. 108

HP-AS01DV10-11/13/01

Chapter 5: Developing EJB Components

ORB classes are specified with org.omg.CORBA.ORBClass and org.omg.CORBA.ORBSingletonClass. hp.spi.orb.argument.name. and hp.spi.orb.argument.value. are used to specify ORB initialization parameters. Multiple parameters can be defined by using consecutive integers in place of . The Orbix2000 domain name, specified in this example as ‘localhost’, is not the DNS name; it specifies which configuration domain Orbix2000 should use. See the Orbix2000 Administrator’s Guide for more information. In both deployment scenarios HP-AS JARs are required in the client class path.

Inter-Container EJB Access EJBs can be configured to reference EJBs deployed in other containers using the HP EJB JAR deployment descriptor, hp-ejb-JAR.xml. The same mechanism can be used when referenced EJBs are deployed into different application name spaces within the same container. In the distributed scenario, the configuration in the hp-ejb-JAR.xml is identical to the remote client xml when the HP JNDI SPI is used. In the HP deployment descriptor for the referencing EJB, the co-located element indicates a reference made to another EJB, where the referencing EJB is in the same virtual machine as the referenced EJB. The CORBA transport mode for the EJB service must be used for collocated clients across application namespaces.

Firewall Issues Remote Client using CORBA A proxy server can be specified using environment entries. This can be necessary for validation of deployment descriptors, if the deployment descriptor references a URL for a DTD or schema. Add the following as environment entries to the script that starts the application client container: -Dhttp.proxyHost=proxy_host -Dhttp.proxyPort=port_number

Where proxy_host is the firewall server and port_number is an allowed port on the firewall server. A remote client cannot access an EJB if there is a firewall between the client and the deployed EJB without ORB specific firewall tunneling software. Also, there cannot be a firewall between the client/Java LBB and Java LBB/HP-AS instance.

Failover and the Load Balance Broker The load balancing and fault tolerance infrastructure for HP-AS uses a server component called the Load Balance Broker (LBB). The LBB selects from the available pool of application server instances. Detailed information on the LBB can be found in the chapter 4 of the HP-AS Administrator’s Guide. EJB lookup resolution in remote clients uses the LBB to establish an association between the client and an application server instance. Remote clients are not load balanced on every request. They are only redirected to another HP-AS instance if the client detects that a failure has occurred with the instance with which it is currently associated. When a client is redirected to another application server instance, the load-balanced broker is used to ensure that instance is selected based on the load-balancing algorithm in the LBB. A detailed technical overview describing how the application client and the LBB interact is described in the HP-AS Technical Guide. In this configuration, the application client interacts with the LBB

HP-AS01DV10-11/13/01

109

HP-AS Developer’s Guide

using standard GIOP messages. In this case, the name-server-host and name-server-port in the HP application client deployment descriptor refer to the corbaloc listener on the LBB instance.

Configuration Procedure HP-AS can also register EJB objects in an external COSNaming implementation. This is not enabled by default in the server. The following steps describe how to configure HP-AS to register EJBs in the Orbix2000 COSNaming implementation. 1

Make changes to two configuration files under {HP-AS_install_dir}\config\HP-AS: Within orb-service.config.xml:

where, {myhost} and {port} are the host and port of the Corbaloc server in which the name service is registered. {myport} is 3075 by default (this is an Orbix default). If the above argument element is omitted, HP-AS will default to the Orbix naming service on the computer that is running the EJB Container. Within ejb-service-config-corba.xml:

and set the register-external-names attribute to "true" (if omitted, the default is false). 2

Start the Orbix name server. If the default “localhost” domain is used, start it by using: "start_localhost_services" under {Orbix_install_dir}\orbix_art\1.2\localhost.

Note that the only the Orbix naming service uses the locator, not the client. For further information, please reference Orbix2000 1.2 documentation online at http://www.iona.com/docs/orbix2000/1.2/index.html. 3

HP-AS can now register with the external naming service.

4

If a remote client will access an EJB registered in the external naming service, then the client must be directed to the host that runs the Orbix Name Service, and the appropriate port (the default is 3075). If using CORBA programming to perform the lookup in a remote client, then an environment setting like the following should be used: -ORBInitRef NameService=corbaloc::localhost:3075/NameService

110

HP-AS01DV10-11/13/01

Chapter 6

Developing Application Clients Overview Application clients are an additional J2EE component with access to the same system resources afforded the other J2EE components (EJB, servlet, etc.). Application clients are programs that execute in their own Java virtual machines (JVMs). They generally follow the model for Java technologybased applications: they are invoked at their main() method and run until the virtual machine is terminated. However, they differ than other client applications since they rely on the J2EE container for resources such as database connections and access to remote EJBs.

Assembling and Deploying an Application Client HP Application Server client applications run in a JVM on a client machine. The client JVM must be able to locate the Java classes you create for your application and any Java classes your application depends upon, including some required HP Application server classes. Therefore, the following HP Application server core JAR files should be deployed to the client machine and available on the given JVM’s classpath: •

baseservices.jar



orbservice.jar



csf_tet_2_2_0_orbix.jar



extendedservices.jar



hpas.jar



ejbservice.jar

The following dependent jars are required (all found in the /lib/ext directory):

HPAS01DV10-11/13/01



ejb.jar



gnu.jar



jaas.jar



jmxri.jar

111

HP-AS Developer’s Guide



connector.jar



jaxp.jar



xerces.jar



xalan.jar



jdbc2_0-stdext.jar



jta-spec1_0_1.jar



mail.jar



activation.jar



jms.jar



jnet.jar

In addition, the following Orbix 2000 classpath elements are required: •

/orbix/orbix_art/1.2/classes/58209_2.jar



/orbix/orbix_art/1.2/classes/omg.jar



/orbix/orbix_art/1.2/classes/orbix2000.jar



/orbix/orbix_art/1.2/localhost



/orbix/etc

The client application needs to be staged into a JAR file or EAR file by either utilizing HP RadPak or assembling the components in a staging directory and building the archive file using the JDK jar facility.

Using HP RadPak Use the following procedure to create a deployable application client JAR file:

112

HPAS01DV10-11/13/01

Chapter 6: Developing Application Clients

1

Create a new staging directory for your client application by opening a File Browser, right-mouse clicking on the desired destination and selection New Directory… Select a directory name.

2

Place the files that constitute your client application in the given directory by copying or moving them into the folder that you created.

3

Right-click your application directory and select New Document… From the list select METAINF/application-client.xml.

HPAS01DV10-11/13/01

113

HP-AS Developer’s Guide

114

4

If you are referencing any remote EJBs from your application client please follow the same procedure to add the proprietary HP application client deployment descriptor (META-INF/hp-applicationclient.xml). See the Contacting Remote EJBs section below for more details.

5

Add a manifest file to the directory by right-mouse clicking on the directory and selecting New Document… and from the list generated select META-INF/MANIFEST.MF.

6

Add a Main-Class entry to the MANIFEST.MF file in the META-INF directory by right mouse clicking on the MANIFEST.MF file and selecting Open. Once the manifest editor is displayed, rightmouse click on the last row and select Add Row.

HPAS01DV10-11/13/01

Chapter 6: Developing Application Clients

7

Modify the row you just added by selecting Main-Class from the selection list that appears when you double-click on the right column value. Enter the value of your main class (The class that has a main() method) on the left side of the row.

HPAS01DV10-11/13/01

115

HP-AS Developer’s Guide

116

8

Make sure to save your changes by selecting File | Save or clicking on the disk icon button.

9

You can now generate a JAR of this directory by right-mouse clicking on the directory and selecting Convert to Jar.

HPAS01DV10-11/13/01

Chapter 6: Developing Application Clients

10 You now have a deployable application client JAR. The resultant JAR can be packaged in an EAR file

(either new or existing). See the RadPak documentation for EAR assembly instructions.

Manual Assembly of Application Client An application client JAR file can be assembled manually by following a similar process to the one outlined in the section above, namely: 1

Create a staging directory.

2

Create a META-INF sub-directory with a MANIFES.MF file and an application-client.xml deployment descriptor file.

3

Use the JDK jar command to build the application client JAR file.

Running the Application Client Container Once the appropriate classpath is established use the following command to invoke the Application Client container:

HPAS01DV10-11/13/01

117

HP-AS Developer’s Guide

%JAVA_HOME%\bin\java Dorg.omg.CORBA.ORBClass=com.iona.corba.art.artimpl.ORBImpl Dorg.omg.CORBA.ORBSingletonClass=com.iona.corba.art.artimpl.ORBSingleton Djavax.rmi.CORBA.PortableRemoteObjectClass=com.iona.corba.rmi.PortableRemote ObjectDelegateImpl Djavax.rmi.CORBA.StubClass=com.iona.corba.rmi.StubDelegateImpl Dstartup.login=false com.hp.mwlabs.as.embeddors.text.AppClient embeddorDeployURL file:////config/appclient/app-clientdeploy.xml -client -jmxport

Tailoring the Application Client Container The HP Application Server application client container is configured with the services required to provide a client application will all resources it may require at runtime including JMS connections, JDBC datasource connections, and EJB references. If a client application makes no use of any of these resources the corresponding service can be removed from the application client container deployment file (/config/appclient/app-client-deploy.xml). Removing a service is simply a matter of removing or commenting out the associated node in the deployment file. See the HP-AS Technical Guide for more information on the services configured for the HP Application Service Application Client Container.

Contacting Remote EJB References There are several methods of configuring a remote client to access EJBs. These are: •

Application Client Container access – Applications can be deployed into the HPAS application client container, which is a fully managed environment for EJB clients. In this case, the container automatically manages environment settings for JNDI lookup resolution.



Inter-container EJB access – EJBs may be configured to reference EJBs deployed in other containers using the HP EJB jar deployment descriptor, hp-ejb-jar.xml. The same mechanism can be used when referenced EJBs are deployed into different application name spaces within the same container.



Access via the HP J2EE JNDI SPI – Remote clients can also be deployed without a client container, and link to the advertised-name using the HP J2EE JNDI.



Access via the Conventional JNDI SPI – Clients deployed outside the application client container, may also use the conventional JNDI syntax that omits the “java:comp/env.”

As seen above, HP-AS provides two JNDI options for looking up EJBs from Java clients and deploying remote clients without the use of a client container. The first option emulates the standard J2EE mechanism that is used in the application client container is called the J2EE JNDI Service Provider Interface (SPI). The second is called the Conventional JNDI SPI. For more detailed information on the various methods of contacting remote EJB references, refer to the Developing EJB Components chapter in the HP-AS Developer’s Guide.

118

HPAS01DV10-11/13/01

Chapter 7

Connecting to Resources Overview JNDI is used extensively within HP-AS to facilitate the lookup of enterprise resources and services. The HP-AS JNDI implementation provides a means for accessing both a number of common J2EE and J2SE resources as well as any number of custom resources through the creation of JNDI resource providers.

Database Connections JNDI is used to get connections to a JDBC datasource. Before you can connect to a datasource from your components, you must define the datasource and its connection properties. All datasources and their connection properties are defined in the \config\hpas\connector-service-config.xml file.

Setting Up a Datasource There are two datasource styles used depending on your application requirements: •

JDBC 1.X Non-XA



JDBC 2.0 XA

Note: The HP-AS Connector service provides internal implementations of generic JDBC connectors. These connectors are adapters that convert any JDBC 1.X driver or JDBC 2.0 DataSource object into a Java Connector Architecture (JCA)-based resource adapter. For more information on connectors and JDBC, see Using J2EE Services.

JDBC 1.X Non-XA Typically, JDBC 1.X is used when an application requires only local transactions to a single datasource. While JDBC 1.X does not support the idea of DataSource objects, the HP-AS implementation creates a wrapper for the JDBC 1.X driver that provides a DataSource façade. The following example demonstrates a JDBC 1.X entry in connector-service-config.xml. hp-jdbc-tx DB1 com.hp.mwlabs.jdbc.drivers.HPSequeLinkDriver jdbc:sequelink://$DEFAULT_HOST$:19996;DatabaseName=CTS jdbc/DB1

HPAS01DV10-11/13/01

119

HP-AS Developer’s Guide

true admin admin

In the datasource entry, you must proved the following elements: Element datasource-type

Description This element defines the connector resource adapter. For JDBC 1.X the default implementation is:



hp-jdbc-tx

You may also define your own resource adapter based on the connector specification. See the Using J2EE Services chapter. datasource-name

This element defines the name of your datasource.

driver

This element defines the JDBC driver to use. HP-Middleware offers a default driver that you can use (com.hp.mwlabs.jdbc.drivers.HPSequeLinkDriver). To use this driver, you must install the bundled Merant software on the database server. See the Advanced Setup chapter in the HP-AS Administrator's guide. If you want to use a different driver, it must be found on the classpath so it can be found at runtime. HP-AS can automatically load the driver class when it starts if it is in the /lib directory. For more information on adding items to the classpath, see the Getting Started chapter.

connection-url

This element defines the JDBC URL to access the database server.

advertised name

This element defines the JNDI advertised name. This is the name you use in your application to lookup this datasource.

force-containermanaged

This element defines whether you want HP-AS to control security.

username

This element defines a username needed to connect to the database.

password

This element defines a password needed to connect to the database.

JDBC 2.0 with XA JDBC 2.0 DataSource objects offer advanced features that you can leverage (i.e. distributed transactions using multiple datasources). In addition, JDBC 2.0 datasources use the JavaBeans design pattern to set their properties. This pattern provides separation between the API for the DataSource object and the API of the application. The following example demonstrates a JDBC 2.0 datasource entry in connector-service-config.xml. com.hp.mwlabs.j2ee.resource.connector.pool.SequeLinkResourceDef hp-jdbc-xa xa_mer_oracle816_on_nt test/xa_test3_mer system 120

HPAS01DV10-11/13/01

Chapter 7: Connecting to Resources

manager com.merant.sequelink.jdbcx.datasource.SequeLinkDataSource ServerName localhost DatabaseName QA PortNumber 19996

In this datasource entry, you must provide the following elements: Element resource-definitionclassname

Description The resource definition used to provide pooled connections for your DataSource object. Resource definitions are different depending on the DataSource object you are using. HP-AS includes two resource definitions for pooling connections:



When using the Merant's DataSource object you can use com.hp.mwlabs.j2ee.resource.connector.pool.SequeLinkResource Def.



When using Oracle's DataSource object you can use com.hp.mwlabs.j2ee.resource.connector.pool.OracleResourceDef

To create your own resource definition the class must be a subclass of com.hp.mwlabs.j2ee.resource.connector.pool. ConnectorResourceDef. datasource-type

This element defines the connector resource adapter. For JDBC 2.0 the default implementation is:



hp-jdbc-xa

You may also define your own resource adapter based on the connector specification. See the Using J2EE Services chapter. datasource-name

This element defines the name of your datasource.

advertised name

This element defines the JNDI advertised name. This is the name you use in your application to lookup and use this datasource.

username

This element defines a username needed to connect to the database.

password

This element defines a password needed to connect to the database.

HPAS01DV10-11/13/01

121

HP-AS Developer’s Guide

vendor-datasource

This element defines the DataSource object used to make connections. Like drivers, DataSource objects are created by driver vendors. HPMiddleware offers a default DataSource object that you can use (com.merant.sequelink.jdbcx.datasource.SequeLinkDataSource). To use this object, you must install the bundled Merant software on the database server. See the Advanced Setup chapter in the HP-AS Administrator's Guide. If you want to use a vendor specific DataSource object, it must be found on the classpath so it can be found at runtime. HP-AS can automatically load the driver in the classpath when it starts if the class is in the /lib directory. For more information on adding items to the classpath, see the Getting Started chapter. Consult your vendor documentation for the fully qualified class name of the DataSource object.

vendor-datasourceproperty

These elements define DataSource object properties. Each property contains a name value pair. For the Merant DataSource object, the following properties are defined:



ServerName



DatabaseName



PortNumber

Note: Depending on your vendor's DataSource object, you may have different properties that need to be defined. Consult your vendor documentation.

Getting a Connection Once a datasource is defined in \config\hpas\connector-service-config.xml, it will be registered with a connection factory. You can get a connection to that datasource using a JNDI lookup from your component code. When performing a JNDI lookup for a datasource, you will use the configured of the datasource. The following example demonstrates a JNDI lookup for the JDBC 1.X datasource defined above: InitialContext initialContext = new InitialContext(); javax.sql.DataSource dataSource =(javax.sql.DataSource)initialContext.lookup ("java:comp/env/jdbc/DB1");

122

HPAS01DV10-11/13/01

Chapter 7: Connecting to Resources

Mail Session Connections JNDI is used to get access to JavaMail Sessions. All accessible mail sessions are defined in the \config\hpas\java-mail-service-config.xml file. Before you can access a mail session from your components, you must define the session and its associated properties. The following example demonstrates a mail session entry in java-mail-service-config.xml.

Getting a Mail Session You can get a connection to the configured mail session using a JNDI lookup from your component code. In order to perform the lookup, you will use the configured of the mail session. The following example demonstrates a JNDI lookup for the JavaMail session defined above: InitialContext initialContext = new InitialContext(); javax.mail.Session session =(javax.mail.Session)initialContext.lookup ("java:comp/env/mail/MailSession");

Note: If you are running HP-AS on a Windows system, you will need to have IIS installed and have the "Default SMTP Virtual Server" running. In addition, you will need to disable the relay restrictions that are enabled by default in the Microsoft SMTP server. For additional information, start the IIS Web service and then go to http://localhost/iisHelp/ to browse the IIS documentation.

URL Connections JNDI is used to get access to URLs. All accessible URLs are defined in the \config\hpas\url-serviceconfig.xml file. Before you can access a URL from your components, you must define the URL in the configuration file. The following example demonstrates URL entry in url-service-config.xml.

Getting a URL You can get access to the configured URL using a JNDI lookup from your component code. In order to perform the lookup, you will use the configured of the URL. The following example demonstrates a JNDI lookup for the URL defined above: InitialContext initialContext = new InitialContext(); java.net.URL session =(java.net.URL)initialContext.lookup ("java:comp/env/url/MyURL");

HPAS01DV10-11/13/01

123

HP-AS Developer’s Guide

Creating a Custom Resource Provider If you need to provide a resource to your J2EE components beyond the standard resource providers provided in HP-AS you do have the option of creating a custom resource provider. There are a number of steps required: 1

Create a Resource Descriptor. The Reference Resolver service uses a Resource Descriptor to find out whether the given provider can return a resource of a given type. In most cases, it is sufficient to extend the com.hp.mwlabs.j2ee.naming.AbstractResourceProviderDescriptor class, as shown below: public class com.hp.mwlabs.j2ee.naming.AbstractResourceProviderDescriptor { public abstract boolean isResourceSupported (Reference ref); }

2

Create a Resource Provider. You can create a resource provider by extending the com.hp.mwlabs.j2ee.naming.AbstractResourceProvider class and implementing the abstract methods:

3



public Object getResource( Reference ref, Context ctx ): In this method you create and return an object based on the information in the in the JNDI Reference object supplied. The Context is supplied as a convenience if you need access to the requesting JNDI context.



public abstract ResourceProviderDescriptor getResourceProviderDescriptor ( Configuration config ): Utilize this method to return the ResourceProviderDescriptor for your resource provider.



protected abstract void initResource () throws ServiceException: This method provides a facility for performing any initialization required in the resource provider. This method will be invoked during the service intialization.



protected abstract void cleanupResource () throws ServiceException: This method provides a facility for performing any cleanup when the resource provider is destroyed (e.g. close database connections).

Add the resource to the HP-AS deployment file. Add a node to the hpas.deploy file:

124

HPAS01DV10-11/13/01

Chapter 7: Connecting to Resources

Getting a Connection to a Custom Provider You can access the resource created by the given provider by specifying a entry in your J2EE module's deployment descriptor and performing the associated lookup in the module's code. Descriptor: custom/MyResource com.my.custom.ResourceImpl Container

Application Code: com.my.custom.ResourceImpl resource = (com.my.custom.ResourceImpl) initialCotext.lookup ("java:comp/env/custom/MyResource");

HPAS01DV10-11/13/01

125

HP-AS Developer’s Guide

126

HPAS01DV10-11/13/01

Chapter 8

Using J2EE Services Overview This chapter provides the information you will need to: •

Use JAXP, including how to extend the service, use parsers, and configure the JAXP Service.



Use connectors, including how to setup the Connector Service, load the Connector Service, and configure adapters.

For reference information about the services described in this chapter, refer to the HP-AS Technical Guide.

Using JAXP The Java API for XML Processing (JAXP) architecture specifies a common interface for the parsing and transformation of XML documents. By defining a set of abstract base classes, JAXP allows you to easily replace the instance of one JAXP-compliant parser with another without making any changes to the client code documents. Its primary purpose is to extract or transform XML documents in some way, by either parsing the document using a Document Object Model (DOM2) or Simple API for XML (SAX2), or by formatting the document differently using XML Stylesheet Language for Transformations (XSLT). For large XML documents or when you plan to parse very few elements of an XML document, consider using SAX2. SAX2 parses elements only when an event occurs. For smaller documents or when you plan to search a document repeatedly, consider using a DOM. A DOM builds a data tree from the XML document and stores it in virtual memory during the entire process. To transform an XML document from one format to another, use an XSLT. To find out more about JAXP in general, go to: http://java.sun.com/xml/xml_jaxp.html

Extending the JAXP Service HP-AS allows you to extend the traditional JAXP Service beyond parsing and transforming documents. Using the JAXP Service in HP-AS, you can manage parsers more efficiently by tracking statistical information. The JAXP Service has also been extended to provide additional ways of accessing parsers, transformers and Templates objects.

HP-AS01DV10-11/13/01

127

HP-AS Developer’s Guide

With HP-AS, you can use the JAXP Service to perform the following additional tasks: •

Monitor the number of documents handled by a parser.



Track total time of use for a single or multiple parsers.



Track average time of use for a single or multiple parsers.



Track other usage statistics.



Parse documents with multiple parser implementation classes without setting system property values.

The HP-AS implementation provides you with additional ways to access parsers and transformers using the JAXP Service: •

Request a parser factory or transformer factory using a Java Naming and Directory Interface (JNDI) lookup.



Request a parser factory or transformer factory using the standard JAXP API Service.



Request a parser or transformer using the JAXP Service methods.

You can also use the JAXP Service to access transformers using a Templates object. The HP-AS implementation allows you to access a Templates object by: •

Requesting a Templates object using a JNDI lookup.



Requesting a Templates object using the standard JAXP API Service.



Requesting a Templates object using the JAXP Service methods.

Using Parsers JAXP allows you to request one of several different parsers for analyzing and separating XML document data into more easily processed components. HP Middleware's JAXP implementation allows you to choose between using a DocumentBuilder parser or using a SAXParser parser. The XML parser or transformer class is created using one of JAXP’s factory classes. The JAXP factory implementation classes are specified by system properties (javax.xml.parsers.DocumentBuilderFactory, javax.xml.parsers.SAXParserFactory or javax.xml.transform.TransformerFactory). The factory class is instantiated in the newInstance() method of the factory’s base class, which reads the value of the system variable. You can call methods for the factory class to set various configuration options for the parser/transformer such as isValidating(), isNamespaceAware(). You can also call the newDocumentBuilder(), newSAXParser(), or newTransformer() methods of the factory classes to create the actual instance of the parser/transformer class. The class returned from a JAXPService.newXXX() method call (a DocumentBuilder, SAXParser or Transformer) can then be used to parse and transform XML documents. Each of the parser classes contains a parse() method that takes an XML document as an argument. The DocumentBuilder parse() method returns a new instance of a Document object. The SAXParser parse() method takes an additional parameter of a DefaultHandler object that is responsible for handling callback calls from the parser. The transformer class has a transform() method that takes an XML document and a Result object that contains the transformed XML document. 128

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

The JAXP Service is responsible for supplying instances of DocumentBuilder, SAXParser and Transformer objects to client applications. The JAXP Service maintains a list of parser/transformer configurations that specify the name of the parser class as well as settings for the various parser properties such as isValidating, isNamespaceAware. The DocumentBuilder, SAXParser and Transformer classes returned from the JAXP Service are then used directly by the application to parse or transform XML documents.

Requesting a Parser or Transformer There are several different methods available to request a parser or a transformer from the JAXP Service. The parser returned from each of these methods is then used by the client application through the standard JAXP APIs.

Requesting a Parser or Transformer from a Servlet The client servlet requests a DocumentBuilder object from the JAXP Service When used from a servlet, the client uses the ResourceManager to obtain a reference to a DocumentBuilderFactory. The client then uses this DocumentBuilderFactory object through the standard JAXP API set. The same flow of events is used to request a SAXParser or Transformer object.

Use Case Actor

Client servlet

Description

Provide access to a DocumentBuilder object for parsing of XML documents configured to meet the client requirements.

Preconditions

Logical name of parser defined in the deployment descriptor of the servlet (see additional details section below).

Post Conditions

The client has a reference to a DocumentBuilder object.

Steps Actor Actions

System Responses

NP: Actor creates a new InitialContext object. NP: Actor calls the lookup() method of the context object, passing in the name of the DocumentBuilderFactory to be created.

NP: JAXP factory provider service creates new DocumentBuilderFactory object and returns it to the client. The DocumentBuilderFactory class contains a reference to its logical name.

NP: Actor calls newDocumentBuilder() method on DocumentBuilderFactory implementation class.

NP: DocumentBuilderFactory acquires reference to JAXP Service.

HP-AS01DV10-11/13/01

AP: DocumentBuilderFactory fails to obtain reference to JAXP Service, returns null DocumentBuilder object.

129

HP-AS Developer’s Guide

Actor Actions

System Responses NP: DocumentBuilderFactory calls getDocumentBuilderByName() method of JAXP Service, passing in the logical name. NP: JAXP Service reads configuration file to determine the embedded class name and property settings matching the logical name. AP: JAXP Service cannot find match for logical name. Logs error: DocumentBuilder definition not found for logical name "{0}" Returns null object. NP: JAXP Service instantiates DocumentBuilderFactory class and calls methods to set parser property settings as specified in the configuration file. NP: JAXP Service calls newDocumentBuilder() method of DocumentBuilderFactory class. This method returns an instance of the embedded DocumentBuilderImpl class. NP: JAXP Service creates new instance of the DocumentBuilderImpl class. NP: JAXP Service calls setDocumentBuilder() method of the DocumentBuilderImpl class, passing the embedded DocumentBuilder class previously created. NP: JAXP Service creates new instance of EntityResolver class. This EntityResolver will interact with the Registry Service to cache DTDs, schemas, etc. NP: JAXP Service calls DocumentBuilder.setEntityResolver(), sending the new EntityResolver object as a parameter. NP: JAXP Service returns DocumentBuilderImpl object containing the embedded DocumentBuilderImpl object.

Note: In the table above, NP=normal path and AP=alternate path.

Sample Code The following code sample demonstrates the use of the DocumentBuilder object from a servlet: Context ctx = null; ctx = new InitialContext(); DocumentBuilderFactory dbf = (DocumentBuilderFactory)ctx.lookup("java:comp/env/xerces"); DocumentBuilder db = dbf.newDocumentBuilder(); String xmlDoc="…"; InputSource inStream = new InputSource();

130

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

inStream.setCharacterStream(new StringReader(xmlDoc)); Document outDoc = db.parse(inStream);

The definition of the xerces logical name is contained in the servlet’s deployment descriptor file web.xml: xerces javax.xml.parsers.DocumentBuilderFactory Application

The following code sample demonstrates the use of the SAXParser object from a servlet: Context ctx = null; ctx = new InitialContext(); SAXParserFactory spf = (SAXParserFactory)ctx.lookup("java:comp/env/xerces_sax"); SAXParser sp = spf.newSAXParser(); InputSource inStream2 = new InputSource(); inStream2.setCharacterStream(new StringReader(xmlDoc)); MyDefaultHandler dh = new MyDefaultHandler(); sp.parse(inStream2, dh);

The definition of the xerces_sax logical name is contained in the servlet’s deployment descriptor: xerces_sax javax.xml.parsers.SAXParserFactory Application

HP-AS01DV10-11/13/01

131

HP-AS Developer’s Guide

The following code sample demonstrates the use of the Transformer from a servlet: Context ctx = null; ctx = new InitialContext(); TransformerFactory trf = (TransformerFactory)ctx.lookup("java:comp/env/xalan"); StreamSource inXSLStream = new StreamSource(new StringReader(xslDoc)); Transformer tr = trf.newTransformer(inXSLStream); StreamSource inXMLStream = new StreamSource(new StringReader(xmlDoc)); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult target = new StreamResult(out); tr.transform(inXMLStream, target);

The definition of the xalan logical name is contained in the servlet’s deployment descriptor: xalan javax.xml.transform.TransformerFactory Application

Requesting a Parser or Transformer Using the Standard JAXP API Set Client requests a DocumentBuilder object from the JAXP Service A client requests a DocumentBuilder object using the standard set of JAXP APIs (DocumentBuilderFactory and DocumentBuilder). The DocumentBuilderFactory class is responsible for instantiating the JAXP Service and requesting the default DocumentBuilder object. The DocumentBuilder object is then used by the client to parse XML documents. The same flow of events is used to request a SAXParser or Transformer object.

132

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

Use Case Actor

Client program

Description

Provide access to a DocumentBuilder object for parsing of XML documents configured to meet the client requirements.

Preconditions

System property javax.xml.parsers.DocumentBuilderFactory is set to com.hp.mwlabs.xml.jaxp.DocumentBuilderFactoryImpl.

Post Conditions

The client has a reference to a DocumentBuilder object.

Steps Actor Actions

System Responses

NP: Actor acquires reference to JAXP Service. NP: Actor reads logical parser name from its configuration file. NP: Actor calls getDocumentBuilderByName() method of JAXP Service, passing in the logical name read from configuration file.

NP: JAXP Service reads configuration file to determine the embedded class name and property settings matching the logical name. AP: JAXP Service cannot find match for logical name. Logs error: DocumentBuilder definition not found for logical name "{0}" . Returns null object. NP: JAXP Service instantiates DocumentBuilderFactory class and calls methods to set parser property settings as specified in the configuration file. NP: JAXP Service calls newDocumentBuilder() method of DocumentBuilderFactory class. This method returns an instance of the embedded DocumentBuilderImpl class. NP: JAXP Service creates new instance of the DocumentBuilderImpl class. NP: JAXP Service calls setDocumentBuilder() method of the DocumentBuilderImpl class, passing the embedded DocumentBuilder class previously created. NP: JAXP Service creates new instance of EntityResolver class. This EntityResolver will interact with the Registry Service to cache DTDs, schemas, etc. NP: JAXP Service calls DocumentBuilder.setEntityResolver(), sending the new EntityResolver object as a parameter. NP: JAXP Service returns DocumentBuilderImpl object containing the embedded DocumentBuilderImpl object.

HP-AS01DV10-11/13/01

133

HP-AS Developer’s Guide

Actor Actions AP: Actor can not find logical parser name in configuration file. Actor calls getDocumentBuilder() method of JAXP Service to retrieve the default DocumentBuilder.

System Responses NP: JAXP Service reads configuration file to determine the embedded class name and property settings of the default DocumentBuilder. AP: DocumentBuilderFactory cannot find the default DocumentBuilder settings. Logs error : Default DocumentBuilder definition not found. Returns null object. NP: JAXP Service instantiates DocumentBuilderFactory class and calls methods to set parser property settings as specified in the configuration file. NP: JAXP Service calls newDocumentBuilder() method of DocumentBuilderFactory class. This method returns an instance of the embedded DocumentBuilderImpl class. NP: JAXP Service creates new instance of the DocumentBuilderImpl class. NP: JAXP Service calls setDocumentBuilder() method of the DocumentBuilderImpl class, passing the embedded DocumentBuilder class previously created. NP: JAXP Service returns DocumentBuilderImpl object containing the embedded DocumentBuilderImpl object.

Note: In the table above, NP=normal path and AP=alternate path.

Sample Code The following code sample demonstrates the use of the JAXP Service through the standard JAXP API set: DocumentBuilderFactory dbf = (DocumentBuilderFactory)DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); // Parse XML document InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(xmlDoc)); Document outDoc = db.parse(inStream);

The following code sample demonstrates the use of the Transformer object through the standard JAXP API set: TransformerFactory trf = (TransformerFactory)TransformerFactory.newInstance(); StreamSource inXSLStream = new StreamSource(new StringReader(xslDoc)); Transformer tr = trf.newTransformer(inXSLStream); StreamSource inXMLStream = new StreamSource(new StringReader(xmlDoc)); 134

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult target = new StreamResult(out); tr.transform(inXMLStream, target);

The following code sample demonstrates the use of the SAXParser through the standard JAXP API set: class MyDefaultHandler extends DefaultHandlerImpl { … } MyDefaultHandler dh = new MyDefaultHandler(); dh.setServiceContext(getServiceContext()); SAXParserFactory spf = (SAXParserFactory)SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(xmlDoc)); sp.parse(inStream, dh);

Requesting a Parser or Transformer from an HP-AS Service HP-AS service requests a DocumentBuilder object from the JAXP Service When used from a service, the client interacts directly with the JAXP Service. The client acquires the service, and then calls the getDocumentBuilder() or getDocumentBuilderByName() method. Services store their logical parser names in their configuration file. The DocumentBuilder object returned from these calls can then be used by the client to parse XML documents. The same flow of events is used to request a SAXParser or Transformer object.

Use Case Actor

HP-AS service

Description

Provide access to a DocumentBuilder object for parsing of XML documents configured to meet the client requirements.

Preconditions

None

Post Conditions

The client has a reference to a DocumentBuilder object.

HP-AS01DV10-11/13/01

135

HP-AS Developer’s Guide

Steps Actor Actions

System Responses

NP: Actor creates DocumentBuilderFactory by calling DocumentBuilderFactory.newInst ance()

NP: JAXP DocumentBuilderFactory class creates instance of com.hp.mwlabs.xml.jaxp.DocumentBuilderFactoryImpl class and returns to client.

NP: Actor calls newDocumentBuilder() method on DocumentBuilderFactory implementation class.

NP: DocumentBuilderFactory calls getDocumentBuilder() method of JAXP Service object. NP: JAXP Service reads configuration file to determine the embedded class name and property settings of the default DocumentBuilder. AP: JAXP Service cannot find the default DocumentBuilder definition. Logs error : Default DocumentBuilder definition not found. and returns a null DocumentBuilder object. NP: JAXP Service instantiates DocumentBuilderFactory class and calls methods to set parser property settings for default configuration. NP: JAXP Service calls newDocumentBuilder() method of DocumentBuilderFactory class. This method returns an instance of the DocumentBuilder class. NP: JAXP Service returns DocumentBuilder object to the DocumentBuilderFactory. NP: DocumentBuilderFactory returns DocumentBuilder object to client.

Note: In the table above, NP=normal path and AP=alternate path.

Sample Code The following code sample demonstrates the use of the JAXP Service from another HP-AS service: String logicalParserName; JAXPServiceInt jaxpService = (JAXPServiceInt)getServiceContext().acquireService (JAXPServiceInt.class, -1, null ); DocumentBuilder db = jaxpService.getDocumentBuilderByName(logicalParserName); // Parse XML document InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(xmlDoc)); Document doc = db.parse(inStream); getServiceContext().releaseService( jaxpService ); 136

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

The following code sample demonstrates the use of the Transformer object from another HP-AS service: JAXPServiceInt jaxpService = (JAXPServiceInt)getServiceContext().acquireService (JAXPServiceInt.class, -1, null ); StreamSource inXSLStream = new StreamSource(new StringReader(xslDoc)); Transformer tr = jaxpService.getTransformer(inXSLStream); StringReader read1 = new StringReader(xmlDoc); StreamSource inXMLStream = new StreamSource(read1); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult target = new StreamResult(out); tr.transform(inXMLStream, target); getServiceContext().releaseService( jaxpService );

The following code sample demonstrates the use of the SAXParser from another HP-AS service: class MyDefaultHandler extends DefaultHandlerImpl { … } MyDefaultHandler dh = new MyDefaultHandler(); dh.setServiceContext(getServiceContext()); JAXPServiceInt jaxpService = (JAXPServiceInt)getServiceContext().acquireService (JAXPServiceInt.class, -1, null ); SAXParser sp = jaxpService.getSAXParser(); InputSource inStream = new InputSource(); inStream.setCharacterStream(new StringReader(xmlDoc)); sp.parse(inStream, dh); getServiceContext().releaseService( jaxpService );

Requesting a Transformer from a Templates Object Clients use Templates objects to increase performance if they plan on reusing the same stylesheet for several XML documents. A Templates object is basically a holding object for a compiled stylesheet. The Templates object is cached in the JAXP Service, saving time. Because it is thread-safe, you can safely pass the Templates object to another method or thread. To use a Templates object, client programs obtain the Transformer Factory and call the newTemplates() method, which takes the stylesheet as a parameter. The client then calls the newTransformer() method from the Templates object.

HP-AS01DV10-11/13/01

137

HP-AS Developer’s Guide

Requesting a Templates Object from a Servlet The client servlet requests a Templates object from the JAXP Service When used from a servlet, the client uses the ResourceManager to obtain a reference to a TransformerFactory object, which in turn requests a Templates object, which in turn requests a Transformer object. The client then uses this Transformer object through the standard JAXP API set.

Use Case Actor

Client servlet

Description

Provide access to a Transformer object for transforming of XML documents configured to meet the client requirements.

Preconditions

Logical name of transformer defined in the deployment descriptor of the servlet (see additional details section below).

Post Conditions

The client has a reference to a Transformer object.

Steps Actor Actions

System Responses

NP: Actor creates a new InitialContext object. NP: Actor calls the lookup() method of the context object, passing in the name of the TransformerFactory to be created

NP: JAXP factory provider service creates new TransformerFactory object and returns it to the client.

NP: Actor calls newTemplates() method on TransformerFactory implementation class.

NP: TransformerFactory calls getTemplatesByName() method of JAXP Service, passing in the logical name. AP: TransformerFactory cannot find logical name settingTransformerFactory, calls getTemplates() method of JAXP Service to obtain default Temeplates. NP: JAXP Service reads configuration file to determine the embedded class name and property settings matching the logical name. AP: JAXP Service cannot find match for logical parser name, logs error: Templates definition not found for logical name "{0}" . JAXP Service returns null Templates object. NP: JAXP Service instantiates TransformerFactory class and calls methods to set parser property settings as specified in the configuration file. NP: JAXP Service calls newTemplates() method of TransformerFactory class. This method returns an instance of the Templates class.

138

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

Actor Actions

System Responses NP: JAXP Service returns Templates object to the TransformerFactory. NP: TransformerFactory returns Templates object to client.

Actor calls newTransformer() method of Templates class.

NP: Templates object call getTransformerFromTemplates() method of JAXP Service. NP: JAXP Service creates new TransformImpl wrapper class. NP: JAXP Service calls newTransformer() method of Templates object. NP: JAXP Service sets new Templates object as the embedded class of the wrapper TemplatesImpl class. NP: JAXP Service return new Transformer object to Templates object. NP: Templates object returns new Transformer to client.

Note: In the table above, NP=normal path and AP=alternate path.

Sample Code The following code sample demonstrates the use of the Templates object from a servlet: Context ctx = null; ctx = new InitialContext(); TransformerFactory trf = (TransformerFactory)ctx.lookup("java:comp/env/xalan"); StreamSource inXSLStream = new StreamSource(new StringReader(xslDoc)); Templates tmp = trf.newTemplates(inXSLStream); Transformer tr = tmp.newTransformer(); StreamSource inXMLStream = new StreamSource(new StringReader(xmlDoc)); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult target = new StreamResult(out); tr.transform(inXMLStream, target);

The definition of the xalan logical name is contained in the servlet’s deployment descriptor: xalan

HP-AS01DV10-11/13/01

139

HP-AS Developer’s Guide

javax.xml.transform.TransformerFactory Application

Requesting a Templates Object Using the Standard JAXP API Set The client requests a Templates object from the JAXP Service A client requests a Templates and a Transformer object using the standard set of JAXP APIs (TransformerFactory, Templates and Transformer). The TransformerFactory class is responsible for instantiating the JAXP Service and requesting the default Templates object. The Templates object then acquires the JAXP Service to request the Transformer object. The Transformer object is then used by the client to transform XML documents.

Use Case Actor

Client program

Description

Provide access to a Transformer object for transforming of XML documents configured to meet the client requirements.

Preconditions

System property javax.xml.transform.TransformererFactory is set to com.hp.mwlabs.xml.jaxp.TransformerFactoryImpl.

Post Conditions

The client has a reference to a Transformer object.

Steps Actor Actions

System Responses

NP: Actor creates TransformerFactory by calling TransformerFactory.newInstance()

NP: JAXP TransformerFactory class creates instance of com.hp.mwlabs.xml.jaxp.TransformerFactoryImpl class and returns to client.

NP: Actor calls newTemplates() method on TransformerFactory implementation class.

NP: TransformerFactory calls getTemplates() method of JAXP Service object. NP: JAXP Service reads configuration file to determine the embedded class name and property settings of the default TransformerFactory. AP: JAXP Service cannot find the default TransformerFactory definition. Logs error : Default Templates definition not found and returns a null Templates object. NP: JAXP Service instantiates TransformerFactory class and calls methods to set parser property settings for default configuration. NP: JAXP Service calls newTemplates() method of TransformerFactory class. This method returns an instance of the Templates class.

140

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

Actor Actions

System Responses NP: JAXP Service returns Templates object to the TransformerFactory. NP: TransformerFactory returns Templates object to client.

NP: Actor calls newTransformer() method of Templates class.

NP: Templates object call getTransformerFromTemplates() method of JAXP Service. NP: JAXP Service creates new TransformImpl wrapper class. NP: JAXP Service calls newTransformer() method of Templates object. NP: JAXP Service sets new Templates object as the embedded class of the wrapper TemplatesImpl class. NP: JAXP Service return new Transformer object to Templates object. NP: Templates object returns new Transformer to client.

Note: In the table above, NP=normal path and AP=alternate path.

Sample Code The following code sample demonstrates the use of the JAXP Service through the standard JAXP API set: TransformerFactory trf = (TransformerFactory)TransformerFactory.newInstance(); String xslDoc="…"; StreamSource inXSLStream = new StreamSource(new StringReader(xslDoc)); Templates tmp = trf.newTemplates(inXSLStream); Transformer tr = tmp.newTransformer(); String xmlDoc="…"; StreamSource inXMLStream = new StreamSource(new StringReader(xmlDoc)); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult target = new StreamResult(out); tr.transform(inXMLStream, target);

Requesting a Templates Object from an HP-AS Service

HP-AS01DV10-11/13/01

141

HP-AS Developer’s Guide

HP-AS service requests a Templates object from the JAXP Service When used from a service, the client interacts directly with the JAXP Service. The client acquires the service, and then calls the getTemplates() or getTemplatesByName() method. Services store their logical transformer names in their configuration file. The Templates object returned from these calls can then be used to create a new transformer object. The Transformer object returned from this call can then be used by the client to transform XML documents.

Use Case Actor

HP-AS service

Description

Provide access to a Transformer object for parsing of XML documents configured to meet the client requirements.

Preconditions

None

Post Conditions

The client has a reference to a Transformer object.

Steps Actor Actions

System Responses

NP: Actor acquires reference to JAXP Service.

NP: Actor determines logical transformer. NP: Actor calls getTemplatesByName() method of JAXP Service, passing in the logical name.

NP: JAXP Service reads configuration file to determine the embedded class name and property settings matching the logical name. AP: JAXP Service cannot find match for logical name. Logs error: Templates definition not found for logical name "{0}". Returns null object.

NP: JAXP Service instantiates TransformerFactory class and calls methods to set parser property settings as specified in the configuration file.

NP: JAXP Service calls newTemplates() method of TransformerFactory class. This method returns an instance of the Templates class. NP: JAXP Service returns Templates object to client.

NP: Actor can not determine logical transformer name. Actor calls getTemplates() method of JAXP Service to retrieve the default Templates.

NP: JAXP Service reads configuration file to determine the embedded class name and property settings of the default Templates. AP: JAXP Service cannot find the default Templates settings. Logs error : Default Templates definition not found. Returns null object. NP: JAXP Service instantiates TransformerFactory class and calls methods to set parser property settings as specified in the configuration file.

142

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

Actor Actions

System Responses NP: JAXP Service calls newTemplates() method of TransformerFactory class. This method returns an instance of the Templates class. NP: JAXP Service returns Templates object to the client.

NP: Actor calls newTransformer() method of Templates class.

NP: Templates object call getTransformerFromTemplates() method of JAXP Service. NP: JAXP Service creates new TransformImpl wrapper class. NP: JAXP Service calls newTransformer() method of Templates object. NP: JAXP Service sets new Templates object as the embedded class of the wrapper TemplatesImpl class. NP: JAXP Service return new Transformer object to Templates object. NP: Templates object returns new Transformer to client.

Note: In the table above, NP=normal path and AP=alternate path.

Sample Code The following code sample demonstrates the use of the JAXP Service from another HP-AS service: JAXPServiceInt jaxpService = (JAXPServiceInt)getServiceContext().acquireService (JAXPServiceInt.class, -1, null ); StreamSource inXSLStream = new StreamSource(new StringReader(xslDoc)); Templates tmp = jaxpService.getTemplates(inXSLStream); Transformer tr = tmp.newTransformer(); StringReader read1 = new StringReader(xmlDoc); StreamSource inXMLStream = new StreamSource(read1); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult target = new StreamResult(out); tr.transform(inXMLStream, target); getServiceContext().releaseService( jaxpService );

HP-AS01DV10-11/13/01

143

HP-AS Developer’s Guide

Service Configuration The configuration file for the JAXP Service (JAXPService.config) contains information describing the mapping of the logical parser names to their actual configuration options. These logical names are then used by applications to identify the parser configuration they require. The configuration file is divided into three sections, one each for DocumentBuilders, SAXParsers and Transformers. There must be one and only one of each of these tags per configuration file. Each section is delimited by the following tags: Tag

Description



DocumentBuilder parser definitions.



SAXParser parser definitions.



Transformer definitions.

Each section contains tags defining the default parser class name, as well as any other parser configurations. These tags are: Tag

Description



default parser factory class name (1 per section).



Parser configuration definition (0 – n per section).

Each parser’s tag contains the following attributes: Attributes

Description

class

The actual class name of the factory.

version

The version of the parser to use.

thread-safe

Whether the parser is safe to cache (thread safe). Possible values are: true, false.

spec-level

The level of DOM or SAX support.

wrap-parser

Whether to return the parser wrapped in the HP Middleware JAXP implementation class. Possible values are true, false.

registry-name

Optional. Name of the registry service repository to use.

There are also configuration attributes for each tag based on its type (DocumentBuilder or SAXParser).

144

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

Attributes Specific to DocumentBuilder parsers Attributes

Description

is-validating

Specifies that the parser produced by this code will validate documents as they are parsed. Possible values are true or false.

is-coalescing

Specifies that the parser produced by this code will convert CDATA nodes to Text nodes and append them to the adjacent (if any) text node. Possible values are true or false.

is-expand-entity-references

Specifies that the parser produced by this code will expand entity reference nodes. Possible values are true or false.

is-ignoring-comments

Specifies that the parser produced by this code will ignore comments. Possible values are true or false.

is-ignoring-element-contentwhitespace

Specifies that the parsers created by this factory must eliminate whitespace in element content (sometimes known loosely as 'ignorable whitespace') when parsing XML documents (see XML Rec 2.10). Note that only whitespace which is directly contained within element content that has an element only content model (see XML Rec 3.2.1) will be eliminated. Due to reliance on the content model this setting requires the parser to be in validating mode. Possible values are true or false.

is-namespace-aware

Specifies that the parser produced by this code will provide support for XML namespaces. Possible values are true or false.

Attributes Specific to SAXParser parsers Attributes

Description

is-validating

Specifies that the parser produced by this code will validate documents as they are parsed. Possible values are true or false.

is-namespace-aware

Specifies that the parser produced by this code will provide support for XML namespaces. Possible values are true or false.

tags for Document builders, SAXParsers and Transformers may also have custom attributes and features that are defined on a per-parser implementation basis. A name/value pair defines the attributes, with the value being a String value. Features are also specified by a name/value pair with the value being a Boolean value.

HP-AS01DV10-11/13/01

145

HP-AS Developer’s Guide

Custom Attributes The following tags and attributes are available when specifying any custom attributes/features and their values: Tag

Description

Attributes



Defines a custom attribute for a parser

name value - string



Defines a custom feature for a parser

name value - Boolean (true, false)

Sample Configuration File An example of the configuration file is:

146

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services



JAXP Service Management The JAXP Service is managed using JMX. The management interface exposes the reconfigureService() method that allows the client to modify the service’s configuration file. The parser configurations maintained at run time can be dynamically created when a client requests a parser using only the properties it requires, and no current configuration meets those requirements. These dynamic configurations are automatically named and not stored in the persistent configuration.

HP-AS01DV10-11/13/01

147

HP-AS Developer’s Guide

When viewing the JMX Management window through HP-AS, HP Middleware's JAXP implementation allows you to monitor usage through standard statistical information. You can view data about the number of documents processed, the total processing time and the average processing time. To assist you in managing the data, you can view a list of all documents or sort them by class name or logical name.

Adding a New DocumentBuilder, SAXParser or Transformer Node to the Configuration File To add a new parser or transformer node to the configuration file, do the following: 1

First, add a new PARSER node within the Document-builders tag. Set the class name, threadsafe value and specification version. For example:

2

Next, add a new config node for the new parser with a name value of default. The CONFIG node should nest within the PARSER node. Set the default values of each attribute for the new parser. For example:

3

Now add the logical name CONFIG node, still within the PARSER node, and set any attributes that will override those set as defaults. For example:

4

Last, close the PARSER tag.

Adding a New Logical Name Once a parser has been defined, you can add one or more logical name nodes to use or ignore the default values set in the Default CONFIG node. Just add the logical name CONFIG node, still within the PARSER node, and set any attributes that will override those set as defaults. For example, the default configuration of the xerces parser may be set to validate documents as it parses. In some instances, you may want to run xerces without validating all XML documents it parses. To override that one default, add a logical name node that looks like this:

148

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services

Using Connectors The HP-AS Connector service provides connection factories to applications and services that request them and maintains connection pools to provide efficient use of the physical connections. The underlying implementation conforms to the J2EE Connector Architecture (JCA) and allows any JCAcompliant resource adapter to be deployed into the application server. The JCA specifies the connection, transaction, and security contracts between the application server and the resource adapter. Refer to the JCA specification on Sun’s web site for additional information. Connection factories typically create connections to an Enterprise Information System (EIS), such as a database, mainframe, or enterprise resource planning system (ERP), such as SAP or PeopleSoft. Configured connection factories in the HP-AS can be accessed in one of two ways: by looking them up through the JNDI or by requesting them directly from the Connector service interface. The first method is used from within applications while the second is used from within other services. Although the Connector service is designed to work with any connector, the resource adapters will need to be supplied by the user, most likely from a third-party vendor. Only JDBC resource adapters are supplied with the HP-AS. In order to make use of the Connector service, the resource adapters must be properly deployed and configured. The HP-AS includes pre-deployed connectors for generic JDBC access to SQL databases. Connectors for other types of systems must be deployed explicitly. This section describes how to complete these tasks and provides sample files and code for each of them.

Resource Adapter Archives The Connector service resides within the HP Application Server, much as the Servlet and EJB containers do. In order for this service to provide applications with connections, a Resource Adapter Archive (RAR) must be deployed. This archive contains all of the files that are needed for a specific type of resource adapter. Many RARs can be deployed at the same time, each for a different type of resource adapter. RAR files typically contain three or more files, as follows: File

Description

META-INF/ra.xml

The out-of-box configuration file for the resource adapter.

META-INF/hp-ra.xml

The HP-AS proprietary configuration file.

xxxx.jar

The class files for the adapter.

It is important to configure the RAR for your specific environment. This is accomplished by adding/editing the hp-ra.xml file within the RAR or by configuring the RAR within the Connector service's configuration file. This configuration information includes security credentials, connection URLs, and other site-specific parameters. These steps are described in the following sections. RARs can be deployed directly to the application server or from within an EAR file.

HP-AS01DV10-11/13/01

149

HP-AS Developer’s Guide

Setting Up the Connector Service In order for the Connector service to function with a specific adapter, several tasks must be completed, as follows: 1

Verify that the extendedservices.jar file is in the server’s classpath. This file contains the Connector service’s classes.

2

Modify the HP-AS deployment file to include the Connector service and the other services that it requires.

3

Configure the adapter. This can be done in one of two ways:

4



By editing the Connector service’s configuration file (i.e., connector-config.xml).



By editing the RAR’s configuration file (i.e., hp-ra.xml).

Deploy the RAR file. This can be done in one of two ways: •

Add the RAR, including configuration information, to the Connector service's configuration file (i.e., connector-config.xml). In this case, the RAR's embedded hp-ra.xml file is not necessary and is superseded by the configuration information in connector-config.xml. The RAR will be deployed when the Connector service is started.



Deploy the RAR or EAR file to the J2EE Partition service. In this case, the RAR's embedded hpra.xml file is used to configure the adapter. Deployment to the J2EE Partition service is persisted in that service's configuration file. The RAR/EAR file can be dragged and dropped onto the J2EE Partition service if this method is used.

At this time, the connection factories for the configured RARs can be looked up through JNDI or directly from the service. In order for an application to perform a JNDI lookup, it must be declared in the application's deployment descriptor. The following sections provide the information that is needed to complete each of the tasks listed above. Note: The Connector service configuration file also contains pool management parameters, such as maximum and minimum pool size. These parameters can be modified as described in Configuring Adapters in the Connector Service's Configuration File later in this chapter.

Loading the Connector Service The Connector service relies on several other services in the HP-AS architecture. In order for the Connector service to function, the Connector service and its required services must be added to the HP-AS deployment file. To do so, place the following information into this file:

150

HP-AS01DV10-11/13/01

Chapter 8: Using J2EE Services



Note: The Connector service is required by the EJB service. If you will be using the EJB service, you must add the above configuration to the HP-AS deployment file.

This configuration deploys the Connector service as well as the services it relies upon (i.e., Application Class Loader service, Transaction Manager service, Reference Resolver service). Note: The Connector can function in a limited form in the absence of the Transaction Manager, Class Loader, and/or Reference Resolver services. If the transaction service is not available, distributed transaction support will not exist. The absence of the application Class Loader service mandates that all resource adapter classes contained within the RAR file must be present in the system classpath of the application server. If the Reference Resolver service is not available, connector-provided resources will not be accessible through JNDI from application components such as servlets and EJBs.

When modifying the HP-AS deployment file for the Connector service, the following schema standards must be observed: •

The elements for the Connector service and its required services must appear within the deployment file’s element.



The elements for the Application Class Loader, Transaction Manager, and Reference Resolver must appear before the Connector service’s element.



The Connector service elements must appear before the Servlet and EJB services.

HP-AS01DV10-11/13/01

151

HP-AS Developer’s Guide

Configuring Adapters The following is a sample Connector service configuration file. Note: The connector-config.xml file is optional. test-cci-adapter .../deployment/hp-jdbc-xa.rar hp-jdbc-tx DB1 com.hp.mwlabs.jdbc.drivers.HPSequeLinkDriver jdbc:sequelink://$DEFAULT_HOST$:19996;DatabaseName=CTS jdbc/DB1 cts1 cts1 test-cci-adapter test-cci eis/test-cci cts2 cts2

DOCINFO-11/13/01

283

HP-AS Developer's Guide

subelements of one of the declarations in the deployment descriptor. --> /employee-service-icon16x16.jpg --> /employee-service-icon32x32.jpg -->

284

DOCINFO-11/13/01

Appendix C: Web Application Deployment Descriptor

Employee Self Service -->

Suggest Documents