Ch 2: Background Background n-Tier Architectures There are various options available when making choices regarding the architecture to be implemented. The decision to utilize a multi-tiered model is outlined below by comparing its advantages over a typical 2-tier model. 2-tier Architecture: The 2-tier architecture is generally the client-server model. The user-system interface is usually on the client desktop, with the database management services typically hosted on a more powerful machine, acting as the server to multiple clients. The logic to implement the business processes is either embedded within the user interfaces or is divided between both machines. It is commonly the former approach which is used in this architecture, thereby producing a ‘fat client’ which takes the main load of the processing. The limitations of this using this architecture outside the sphere of a LAN with under 100 clients becomes apparent on inspection. Despite the server usually being the more powerful machine, the bulk of the processing work is made the responsibility of the smaller client – this results in poor performance if the workload is great. One other problem, which is particularly the case in the realm of e-commerce, is the lack of flexibility provided by the 2-tier architecture. It is conceivable (likely, even) that the means of accessing an application can vary. The client may be a web browser, a mobile device or a Java Swing application interface; the 2-tier architecture would need to develop business logic for each type of access in a fat-client scenario because the business functionality will be sitting on the client machine. This provides poor maintainability and scalability, as any generic changes which need to be made to an application would need to be made for each individual access type. However, by adding an extra layer of abstraction between the client layer and the business processes, this problem may be overcome. Another restriction arises regarding the choice of database management system (DBMS) in the situation where the procedural load is distributed between the two tiers. If vendor-proprietary database-access code is included in an application, then it makes any decision to change to another DBMS very difficult and time-consuming, as changes programming code will need to be rewritten to account for the move. A move from one server to another might also require code-regeneration, thus displaying poor portability. A Multi-Tiered B2C Internet Retail Solution 3 Ch 2: Background 3-tier Architecture: The problems that arose in the 2-tier architecture appear to stem from the question of “When there’s more computational logic, should it go on the front end or the back end?” One solution is to take the view that it does not belong on either the server or the client. Instead, a middle tier can be introduced in order to take such responsibility away from both the client and the data-managing server. This results in a 3-tier architecture which can be summed up as follows: Front end – presentation-oriented client tier Back end – data server tier Application server – complex-processing middle tier Middle tiers: There are a variety of implementations of the middle tier – 1. transaction processing monitors 2. message servers 3. application servers For the purpose of this paper, the use of application servers shall be concentrated on. By implementing a 3-tier architecture, clients are shielded from the more complex, lower-level details of the data source connections, database schema and database implementation. It allows the decoupling of business process implementation from user interfaces and database access logic. This approach simplifies application maintenance – if the backend databases are modified, the data access code or object may be modified while the client remains unchanged and unaware of any of these modifications. It now also becomes possible to have multiple front ends, with all business services running on the application server, whilst using the same data. This is demonstrated in figure 1.1. Database Server Web browser Java Application Business Logic Legacy Database Systems Mobile device Client Tier Middle Tier (may be multi-tiered) Enterprise Information System (EIS) Tier figure 1.1 3-Tier Architecture A Multi-Tiered B2C Internet Retail Solution 4 Ch 2: Background The 3-tier model displays MVC architecture (model-view-controller). The client tier provides the view, the EIS tier provides the model and the middle tier acts as the controller. The business logic remains independent of the presentation layer. The middle tier provides business services to clients (e.g. stock taking, orderprocessing, payment validation) and system services (remote client and legacy system access, security, resource pooling, transaction management, session handling). The middle-tier may be layered further, resulting in a multi-tiered architecture as displayed later in figure 1.2. By making use of these concepts of abstraction and encapsulation, it becomes possible to ‘drag and drop’ application modules (each with a specific logical function) onto distributed machines, operating within a multi-tiered structural framework. A very useful feature of application servers is the fault-tolerant environment which they are able to provide. It is feasible that a server be able to relocate a user session to another machine in the event of a problem or heavy resource demands affecting performance. The advantage of adding an extra tier is that it allows for a thin (and therefore, simple) client. Clients can then be rapidly developed, and easily integrated with existing applications and systems. Multi-tier Architecture The distributed component model implements this architecture. Use of distributed components allows for a physical separation of the layers, and allows for deployment on different machines in order to meet certain processing and memory requirements. Each layer may be dealt with separately, which makes the roles of administration and maintenance easier. Alterations to one tier may remain transparent to another. RMI (Remote Method Invocation) and EJB (Enterprise JavaBeans) are two technologies which Java provides for the purpose of building distributed component models. These are investigated in depth shortly. Implementation of the n-tier architecture improves on the following features of a system: Usability - the ease and speed with which a user can interact with and understand a system or component. Interoperability - the ability of two or more systems or components to exchange information. Scalability - the ease with which a system or component can be modified to fit the problem area. Flexibility - the ease with which modifications to a system or component can be made – and the ability to make changes to one layer without affecting the others. Security – it is possible to set security at each step of the chain to ensure data is safe. Multiple access mediums – via WAP, HTTP, etc Maintainability Reusability A Multi-Tiered B2C Internet Retail Solution 5 Ch 2: Background J2EE Platform What is J2EE? JavaTM 2 Platform, Enterprise Edition (J2EE) is an environment which is built on the Java 2 Platform, Standard Edition (J2SE). It specifies a set of co-ordinated application programming interfaces (API’s), services and protocols, in order to provide a multi-tiered, distributed application model for the development, deployment and management of transactional enterprise applications. This functionality comes from API’s of the following enabling technologies: Enterprise JavaBeans (EJB’s) Remote Method Invocation (RMI) Java Naming and Directory Interface (JNDI) Java Database Connectivity (JDBC) Java Transactional API (JTA) Java Servlets and Java ServerPages (JSP) Java Message Service (JMS) Java API for XML (JAXP) JavaMail Java Authentication and Authorization Service (JAAS) J2EE Connector The above will be further expanded on in later sections of this chapter. By presenting this standard for implementing and deploying enterprise applications, the J2EE platform shifts responsibility for complex, lower level services to the server provider, allowing the application developer to concentrate on the business logic of the application. A Multi-Tiered B2C Internet Retail Solution 6 Ch 2: Background J2EE Architecture: J2EE integrates web and middleware technologies by having a full range of enterprise-class services to rely on, including transactional, distributed objects, message oriented middleware, and naming and directory services. JSP Pages Enterprise Beans Servlets Enterprise Beans Web browser Database Java Application Database Mobile device Client Tier Client Machine Web Tier Business Tier J2EE server EIS Tier Database server figure 1.2 J2EE multi-tiered applications The J2EE model has a multi-tiered architecture – the components of the application are distributed across different machines according to the tier they belong to. Despite the fact that J2EE applications may have 3 or 4 tiers (as depicted by figure 1.2 ), they are generally only distributed across three different locations (client machines, a J2EE server machine, and database machines); hence they are typically viewed as having a 3-tiered architecture. J2EE clients are thin – i.e. actions such as database access or querying and the execution of complex business logic are carried out by the middle tier. Multi-tier design simplifies developing, deploying, and maintaining enterprise applications. A division of labour comes about whereby : program developers can focus solely on business logic backend services can be provided by the server vendors client-side applications, providing the user interfaces, may be produced by graphical designers. A Multi-Tiered B2C Internet Retail Solution 7 Ch 2: Background We can inspect the J2EE server middle tier in more detail: Web Container EJB Container Client Protocols: HTTP/HTTPS Client Protocols: RMI/IIOP/SSL Java Servlets APIs JNDI JSP Pages JDBC JMS Enterprise Beans RMI JavaMail JAXP JAAS JTA Connector J2EE Platform Java 2 Standard Edition Platform (J2SE) figure 1.3 J2EE Platform Architecture The main constituents of J2EE architecture, which shall be expanded on below, are: J2SE J2EE components J2EE containers J2EE services (provided by API’s) Java 2 Standard Edition The J2SE runtime environment underpins the J2EE platform, providing applications with standard Java facilities and core API’s. The J2EE environment further extends J2SE services with additional API’s for developing enterprise applications. Their inclusion in the platform facilitates database access, transaction management, messaging, security and naming and directory functionality. The API’s shall be elaborated on shortly. J2EE components Components are self-contained application-level units which are supported by a container. Four types of component are specified by J2EE: 1. 2. 3. 4. Enterprise beans Servlets & JSP pages Applets Application clients (business components) (web components) (client components) (client components) Enterprise JavaBeans components (or ‘enterprise beans’) capture the business logic of an application. They are remote objects – the distributable J2EE components. Servlets are small, plug-in extensions to respond/request-oriented servers; effectively, they enhance the functionality of a server. Java ServerPages embed servlet code directly in HTML pages – they are a more presentation-oriented version of the same technology used by servlets. A Multi-Tiered B2C Internet Retail Solution 8 Ch 2: Background These components are written in Java and compiled, as would ordinarily be done with any other Java program classes. Before it can be executed, a J2EE component must be assembled into a J2EE application, verified as being well-formed according to the J2EE specifications, and then deployed into its container. (N.B. Static HTML files and utility classes - such as JavaBeans components - are not considered to be components. These are packaged along with the J2EE components at the point of application assembly.) Components can be updated and replaced independently – new functionality can be added to existing applications by either updating selected components or by plugging in new ones. Standardized components could be provided as “off-the-shelf” solutions to common tasks. J2EE containers Containers are central to the component-based model propounded by J2EE. They are standardized runtime environments which implement the relevant API’s required by the container-held components. They also provide the necessary support for client access protocols, thus stripping the need for individual components (EJBs, JSPs or servlets) to be aware of how their communications with clients are handled. Figure 1.3 presented two of the four types of containers available to J2EE applications – web containers and EJB containers. The other 2 container-types specified by J2EE are applet containers and application client containers (in order to run standard Java application clients). An application client container runs on the client machine, along with its application client components. Similarly, an applet container runs on the client machine; specifically, the applet container is a combination of a web browser and Java plug-in running together. However, for the purpose of this paper, the focus will remain on the former two containers (web and EJB), as these are central to developing e-commerce applications. Whilst applet and standard application client containers warrant a mention, it is not necessary here to embellish further on the support they provide to J2EE applications. An EJB container, which is transparent to an application developer, runs on the J2EE server and provides system-level services such as remote client connectivity, multithreading, transaction management, security authorization, life-cycle management and database connection pooling The container interfaces between low-level, platformspecific support services and the application component requiring these services. Thus, business logic is separated from resource and lifecycle management – the latter two being dealt with as the enterprise infrastructure is implemented by J2EE server vendors (for example – IBM’s WebSphere and BEA’s WebLogic are two such application servers currently available supporting the J2EE platform). Web containers also run on the J2EE server – their role is to host application web components. A web container bears responsibility for initializing, invoking, and managing the life cycle of servlets and JSPs. A Multi-Tiered B2C Internet Retail Solution 9 Ch 2: Background J2EE services A brief outline of the API’s which the J2EE platform comprises, should elucidate the nature of the services provided to application components. JNDI (Java Naming and Directory Interface) The JNDI API performs two roles in the J2EE platform. Primarily, it provides applications with a means to store and retrieve any type of named Java object. JNDI allows an object to be associated with a standard name and all naming operations are relative to a context. A context is a set of name-to-object bindings and provides a lookup operation that returns an object associated with the name. The InitialContext class is the starting point for name resolution in JNDI. A URL String (of the form scheme_id:rest_of_name) can be passed as a name parameter to any of InitialContext’s methods; a URL context factory for handling that scheme is then located and used to resolve the URL. In the case of invoking the lookup method, the object bound to the specified URL-name is retrieved. Context initial = new InitialContext(); Object objref =initial.lookup(“java:comp/env/ejb/customer”); CustomerControllerEJB In the above example, an InitialContext object is constructed, then performs a lookup operation on the URL name “java:comp/env/ejb/customer”; the result of which is to return the Object associated with that name. An application can use JNDI to look up JDBC connections or to locate the interfaces which are used to create EJB instances. JNDI’s other role is to enable access to existing enterprise directory services such as LDAP (Lightweight Directory Access Protocol), NDS (Novell Directory Services) and DNS (Domain Name System). This common API is used by applications to access these naming and directory services rather than have them require a separate API for each directory service. RMI (Remote Method Invocation) RMI is a mechanism enabling an object to invoke methods on another object which is on a different virtual machine. A remote object must implement the Remote interface which defines the methods by which a client can invoke on it. An application registers the remote object with the RMI registry (by providing the object and a String name1) in order to make it available to clients that are on a separate virtual machine. 1 The name follows the following syntax "rmi://hostname:port/remoteObjectName"; hostname = machine and port = port on which the RMI registry is running. remoteObjectName is the string name of the remote object. “rmi:”, hostname, & port are optional. Hostname default = localhost. Port default = 1099. Example – “rmi://localhost:1099/jdbc/B2CDB” where “jdbc/B2CDB” is the logical name of a DataSource object. A Multi-Tiered B2C Internet Retail Solution 10 Ch 2: Background A client, wishing to invoke a method on a remote object, queries the RMI registry, using the lookup method which returns a remote reference to the object (called a ‘stub’). RMI publishes the proxy object implementation to the remote interface. The client makes calls on the proxy object; the calls are then forwarded by RMI to the remote JVM and finally on to the remote object. Any return values are sent back along the same route, via the proxy object, to the client. The service is provided by the remote object implementation which runs on the server, whilst the stub runs on the client, acting as a proxy for the remote service. Client JVM Client Object Server JVM RMI Stub Interface Server Object Figure 1.4 Remote method calls Server implementation objects may inherit from javax.rmi.PortableRemoteObject This provides the narrow method which takes an object reference and attempts to narrow it to conform to the given interface. In the example code below, taken from CustomerControllerEJB, the given interface is CustomerHome (which is the home interface of the CustomerEJB entity bean). If the operation is successful the result will be an object of the specified type (i.e. CustomerHome) returned to the client (CustomerControllerEJB), otherwise an exception will be thrown” Context initial = new InitialContext(); Object objref = initial.lookup("java:comp/env/ejb/customer"); customerHome = (CustomerHome)PortableRemoteObject.narrow(objref, customerHome.class); CustomerControllerEJB JDBC (Java Database Connectivity) JDBC is the API for accessing relational data in Java applications. It provides database-independent connectivity. The following functionality is given to an application: Perform connection & authentication to a database server Manage transactions Move SQL statements to a database engine for pre-processing and execution. Execute stored procedures Inspect and modify the results from SELECT statements JDBC 2.0 Extension API also provides connection naming via JNDI, and transparent connection pooling & distributed transaction support. A Multi-Tiered B2C Internet Retail Solution 11 Ch 2: Background In short, JDBC is a means for passing SQL code from a Java application to a DBMS, and for processing those results returned. It does this by carrying out the following stages: 1. 2. 3. Establish connection with DBMS. Load driver: Access driver via DataSource object (registered with JNDI service provider.) Make connection: Instantiate Connection instance. InitialContext ic = new InitialContext(); DataSource ds = (DataSource)ic.lookup(java:comp/env/jdbc/B2CDB); Connection con = ds.getConnection(); The Connection returned is an open connection which is used for creating JDBC Statement/PreparedStatement objects which pass SQL statements to the DB. The above example displays a JNDI-based lookup for accessing a database using a logical name (jdbc/B2CDB). JDBC technology implements Java’s "Write Once, Run AnywhereTM" features so as to run on any DBMS. JSP/Servlets (Java Servlets and Java ServerPages) This API allows platform-independent programming logic to be embedded in the HTTP request-response processes which are carried out between a client (usually a browser) and a web server. One function which it provides is a means for maintaining client state across a session; this is important, as HTML is a stateless protocol). JSP pages are text-based documents with servlet code embedded within – they can be used interchangeably with servlets but are essentially geared towards generating static content. Servlets are the preferred mode of managing more programmatic control functions. However, since it remains a matter of developer preference, it is possible to use a combination of the two kinds of web component (servlets as controllers, JSP pages for user interface logic) or to make use of just one of the two types when building an application. JMS (Java Message Service) JMS is the messaging standard for asynchronous communication – providing the means for components to send and receive messages via enterprise messaging systems. JTA (Java Transactional API) JTA is concerned with transactions across heterogeneous enterprise systems – i.e. for working with distributed applications. It specifies interfaces to support transaction demarcation (when to perform commits and rollbacks), transactional resource management and synchronisation. JAXP (Java API for XML) JAXP deals with parsing and manipulating XML documents – irrespective of underlying parser technology. A Multi-Tiered B2C Internet Retail Solution 12 Ch 2: Background JAAS (Java Authentication and Authorization Service) JAAS is security-centric. The API can impose access control on parts of the code – based on the identity of a user running the code. Hence an administrator may be granted access to the entirety of an application, whereas a typical user may be prevented access to certain methods or modules. JavaMail This API provides mail services (such as e-commerce mail notifications) – for sending and receiving email. JavaMail is a platform- and protocol-independent API. It includes support for commonly used mail protocols such as IMAP, SMTP and POP3. J2EE Connector Connector is an API that connects J2EE platform to existing legacy systems. It provides the capability to plug in to any EJB server that supports the Connector architecture. JavaBeans Components JavaBeans components are useful, if not exactly central, to J2EE applications. Due to remote calls tending to be more time-consuming than local calls, it is advantageous to utilize coarse-grained components. It is possible to reduce the amount of remote access calls by encapsulating sets of behaviour in JavaBeans objects, which can be manipulated on the client side, and passing these as method parameters in remote method calls. EJB Technology (Enterprise JavaBeans) EJB technology forms the core of J2EE – it allows the rapid development of distributed, applications by reducing the complexity involved in building middleware components (i.e. the enterprise beans). The underlying architecture of EJB (which remains transparent to an application developer) handles the low-level system details of transaction and state management, database connectivity, persistence, multithreading, resource-pooling and security. The code involved for handling these services is complex and time-consuming to write; by making this support the responsibility of the server vendor, the application developer’s focus can remain on writing the components’ business logic. Since the enterprise beans encapsulate the business logic of an application, the client is relieved of the bulk of any complex or computational processing. The overall result is a simplified route to writing a thin-client, multi-tiered application. Enterprise Bean Types There are 3 kinds of enterprise bean, each of which is a remote object representing either a business task or a business entity: 1. 2. 3. Entity bean Session bean Message-driven bean A Multi-Tiered B2C Internet Retail Solution 13 Ch 2: Background 1) Entity Bean An entity bean represents a persistent business object – it typically correlates to a single row of a database table, although it may be stored in an alternative storage mechanism. An example of an entity bean may be a credit card, a customer or a bank account. An instance of a customer entity bean, which mapped onto the following Customer relation example, would encapsulate the data provided by one of the rows in table 1 – e.g. (03, Bway, Doh, Rangoon, bd@email.net). Customer ID Forename Surname City Email 01 Nguyen Tin Hanoi nt@email.com 02 John Doe Illinois jd@email.org 03 Bway Doh Rangoon bd@email.net table 1 Customer table in DBMS An entity bean can be identified by its primary key, which is unique to each object. This corresponds to the primary key of a table if the storage mechanism is that of a relational database. In table 1, the primary key for a Customer entity bean would be its customer ID value. This unique identifier allows a client to locate and create instances of an entity EJB. Entity bean persistence may be managed in one of two ways: Bean-Managed Persistence (BMP) or Container-Managed Persistence (CMP). Utilization of BMP entails writing the JDBC (and, therefore, SQL) code into the create, find, load, store and remove methods of an entity bean. This provides more flexibility and control over database access in the development of the enterprise bean. The alternative approach, CMP, leaves the database access calls up to the EJB container – no JDBC code is required in the entity bean. This enhances the portable nature of the J2EE application as there is no code specifically tied to any particular database. It also allows for the use of a local, client-view model, whereby enterprise beans can make local method calls on one another, thus reducing the usual overhead that remote calls necessitate. 2) Session Bean A session bean represents a client in the J2EE server – it is created by a client and executes business tasks in the J2EE server on behalf of the client. Each session bean may have only one client (whereas an entity bean may have multiple clients), and once the client terminates, the session bean appears to do likewise. Although they are not persistent objects – and so their data will be lost in the event of a server or client crashing – a stateful session bean may maintain state across a conversation with a client by storing information in its private variables. In this way, it can hold data such that subsequent method invocations can call on these values within the sessionconversation. It is this ability which allows a Cart session bean to store information on a shopping client’s selections for the duration of the shopping session. Once the client-EJB conversation terminates, this data is lost. A Multi-Tiered B2C Internet Retail Solution 14 Ch 2: Background A stateless session bean does not maintain a conversational state. All stateless session beans are identical to one another except during method invocation, when their instance variables may be assigned specific values. This may be demonstrated by considering a simple session bean, VerificationEJB, which verifies the validity of a customer credit card. (For the sake of clarity and simplicity, this example presumes that the validation can be carried out in one simple step, rather than the more realistic view which involves contacting banking services, awaiting confirmation or rejection, all the while holding the data on the customer credit card.) In this scenario, the session bean does not need to hold any data beyond returning the result of the method call. However, it will assign values during the actual method invocation (such as credit card number, expiry date, customer name) in order to check the actual details. Before doing so and after completing the validation, the session bean holds no information to distinguish it from any other VerificationEJB session bean. Hence, it is ‘stateless’. 3) Message-Driven Bean A message-driven bean shares some similarities with a stateless session bean; it is not persistent and does not maintain a conversational state with a client. Message-driven beans are local objects that allow for asynchronous messaging. They listen for messages from the JMS and are completely decoupled from the clients that send the message. Unlike the other two enterprise bean types, message-driven beans are not accessed via interfaces. Purpose Access Entity Bean Session Bean Message Bean Represents a persistent business object. Represents a server-side task to perform on behalf of a client. Allows asynchronous receipt of messages. Multiple client access Single client access Multiple client access Local/Remote Local/Remote Local Persistent Not persistent ٭ Not persistent Persistence = ٭NB The EJB container may, at times, write a stateful session bean out to secondary storage. table 2 Enterprise Bean Types EJB Transactions In order to maintain data integrity, entity beans work within transactions. The fact that entity beans are shared by multiple clients leaves data liable to lost updates, uncommitted dependency problems and inconsistent analysis. Hence transaction management is carried out by the EJB container to handle concurrency issues as well as partial update problems. Session beans also have the option of implementing bean-managed transactions in their code. This permits a bean to ensure that several steps or none at all are carried out within a transaction. In the following segment of code (taken from CheckoutEJB A Multi-Tiered B2C Internet Retail Solution 15 Ch 2: Background – a session bean belonging to this project), is an example of a bean-managed transaction. When a customer pays for their goods, the Orders relation must be updated in order to reflect that an order has been processed. Those goods belonging to the order need to be stored in the OrderLine relation which holds these details, and the stock needs to be decremented – hence the Inventory relation must also change. To maintain data integrity, either all of these actions should complete, or they should all fail. The first line of the code demarcates the beginning of the transaction and sets the Connection object’s autocommit mode off. This groups all SQL statements that follow into a single transaction, until there is a call to a commit method (as in this case) or a rollback method. The commit persists all changes made since the previous rollback or commit and releases any locks held by the Connection object. con.setAutoCommit(false); updateOrders(orderId, customerId, price, status, date); updateOrderLine(orderList); updateInventory(orderList); con.commit(); CheckoutEJB EJB Architecture (Session and entity beans) As has already been stated, entity beans and session beans are remote objects. The remote client of an enterprise bean may be a web component, a client component or another enterprise bean; the client may be running in either a separate JVM from the EJB or in the same one. The internal complexities of the bean are shielded from clients, who are presented with two interfaces by which they may interact with the enterprise bean. Both interfaces use RMI protocols. For each method defined in the interfaces, there must be an implementation which correlates to it in the enterprise bean class. The remote interface presents the client with the business methods which may be invoked on the enterprise bean, and the home interface defines the methods by which an instance of the bean may be created by the client, along with finder methods (in the case of entity beans) to locate specific enterprise beans. Figure 1.5 demonstrates these interactions. Legacy Systems EJB Container Home Interface Enterprise Bean Component Client Remote Interface Database J2EE Server figure 1.5 EJB Architecture A Multi-Tiered B2C Internet Retail Solution 16 Ch 2: Background The enterprise bean class, residing on the server, implements either the SessionBean interface, or the EntityBean interface (depending on the enterprise bean type). It contains methods with the same signatures as the remote interface, although it does not in fact implement the remote interface itself. When a bean is deployed (i.e. installed), the EJB container generates the remote interface. The implementation of this interface (EJBObject) acts as a proxy by receiving the method invocations from the client, then going on to make the appropriate calls on the enterprise bean. The EJBHome interface, which is also implemented by the EJB container, makes the enterprise bean’s home interface available to a client by means of JNDI. This has already been displayed previously in the CustomerControllerEJB excerpts (refer back to JNDI & RMI API sections). However, further clarification may help to indicate what parts are played by the various components and containers in client-EJB interactions. Here follows a similar code extract: Context initial = new InitialContext(); Object objref = initial.lookup("java:comp/env/ejb/customer"); customerHome = (CustomerHome)PortableRemoteObject.narrow(objref, customerHome.class); Customer customer = customerHome.create(customerId); The above example deals with an entity bean, which consists of: Entity bean class: Remote interface: Remote Home interface: CustomerEJB Customer CustomerHome In order to have any interactions with an entity or session bean, a client must locate the home interface for the bean in question. This is done by calling InitialContext(), which is the starting point for JNDI name-resolution operations (i.e. the root of the hierarchy). The handle, customerHome, returned by the JNDI lookup and narrow methods, provides a reference to the CustomerEJB object (which is an instance of the entity bean class proper). However, a client cannot directly instantiate an enterprise bean – only the EJB container may do so. In order to carry out this feat, the client invokes the create method provided by the home interface. The create method, which is implemented in EJBObject, invokes the appropriate ejbCreate method in CustomerEJB and returns an obect of type Customer. The direct results on an enterprise bean of calling the ejbCreate method are: The entity state is inserted in the database Intance variables are initialized (in the above case, customerId) The primary key is returned Regarding the create method’s return value, the client can then go on to use this remote handle to invoke the entity bean’s business methods. To the client’s-eye view, A Multi-Tiered B2C Internet Retail Solution 17 Ch 2: Background these business methods appear to run locally, whereas they are, in reality, running remotely in the session bean. All enterprise beans must meet certain requirements specified by the EJB API. A brief overview of the principal elements demanded by this technology will bring about a wider understanding of the design and implementation of the J2EE application developed for this project. All explanations given are directed at explaining enterprise beans with bean-managed persistence. Container-managed persistence is not addressed, as it is outside the scope of this project, and does not yet provide a high-level of reliability and support. Entity Bean Requirements Figure 1.5.1 depicts the interactions of a client with an entity bean class via the remote and home interfaces. In order for these communications to work, there are certain conventions which must be followed when building the entity bean – clearly there must be a direct correspondence between those methods available in the interfaces, and those which the are implemented in the entity bean. Client Remote Interface * Extends EJBObject interface * Defines business methods: - same signatures as for those equivalent method implementations in the bean class. - throw java.rmi.RemoteException Home Interface * Extends EJBHome interface * Defines create methods: - same number defined as there are ejbCreate methods in the bean class. * Defines findBy methods - same number as defined in bean class. Entity Bean Class EJBObject EJB Container * Implements EntityBean interface * Implements ejbFindBy & business methods * Defined as a public class * Cannot be abstract or final class * Contains an empty constructor * Implements zero or more ejbCreate methods * Implements the same number of ejbPostCreate methods as for ejbCreate * Cannot define the finalize method EJBHome figure 1.5.1 Entity Bean interactions with a client The implementation of the remote and home interfaces is taken care of by the EJB container, which merely leaves the bean developer to define the interfaces themselves, and the implementation of the entity bean class. Entity Bean Class: Implements the EntityBean interface: EntityBean interface extends EnterpriseBean and java.io.Serializable interfaces. The container uses the EntityBean methods to notify enterprise bean instances of the instance's life cycle events. A Multi-Tiered B2C Internet Retail Solution 18 Ch 2: Background The EntityBean methods which must be implemented in the bean class are: setEntityContext, unsetEntityContext, ejbRemove, ejbActivate, ejbPassivate, ejbLoad, ejbStore. (See EJB Life-Cycles section below). N.B. ejbLoad refreshes instance variables from the database and ejbStore writes instance variable values to the database. These two methods are called by the container before and after (respectively) a business method executes, thereby synchronizing instance variables of the bean with the database. Implements zero or more ejbCreate and ejbPostCreate methods: ejbCreate must be public; it inserts the entity state into storage and throws a javax.ejb.CreateException if an input parameter is invalid. It returns the primary key. For both ejbCreate and ejbPostCreate, method arguments must be legal RMI types. For every ejbCreate method, there must be a corresponding ejbPostCreate method. Every ejbPostCreate (which is invoked by the EJB container directly after ejbCreate) must be public have the same number and type of arguments as its corresponding ejbCreate method and declare a void return type. The primary key class must satisfy the following requirements: (i) Implement java.io.Serializable. (ii) Implement hashCode( ) and equals(Object obj) methods. (iii) Have a public default constructor. (iv) Class access must be public. Implements the finder methods which locate specific bean instances: The finder methods are application-specific. Every method in the entity bean class which is prefixed by “ejbFindBy-” (e.g. ejbFindByPrimaryKey – which it is obligatory to implement) has a corresponding method in the home interface which uses the prefix “find-” (e.g. findByPrimaryKey). The return type of “ejbFindBy-” methods must be the primary key or a Collection of primary keys. javax.ejb.FinderExceptions are thrown by finder methods. Home Interface: Extends the EJBHome interface: EJBHome interface extends java.rmi.Remote interfaces. The remote home interface defines methods which allow a remote client to create, find, and remove an EJB object. create and findBy methods: The home interface will declare the same number of create and findBymethods as there are ejbCreate and ejbFindBy methods implemented in the bean class. The number and types of arguments must match those of the corresponding method signature in the entity bean class. However, whilst their counterparts in the entity bean class return void (if ejbCreate) or return the primary key or a Collection of primary keys (if ejbFindBy), the return type here for both these methods is the remote interface type, or a Collection of remote interface types. A Multi-Tiered B2C Internet Retail Solution 19 Ch 2: Background Both method types must throw java.rmi.RemoteException, along with any other Exceptions thrown by their counterparts. Remote Interface: Extends the EJBObject interface: EJBObject interface extends java.rmi.Remote interfaces. The remote interface defines business methods which a remote client can call. Each of the method signatures in the remote interface must match the signature of a method which is implemented in the enterprise bean class. The method must throw java.rmi.RemoteException, along with any other Exceptions thrown by the corresponding EJB class method. Session Bean Requirements Figure 1.5.2 depicts the interactions of a client with a session bean class via the remote and home interfaces. There are numerous parallels between session beans and entity beans. To keep from repetition, the differences between session bean requirements and those of entity beans (discussed above) shall be addressed here. Since much of the preceding explanatory content regarding the bean class and its related interfaces holds equally true for session beans, it should suffice to highlight only where the architectures diverge. Client Remote Interface Home Interface * Extends EJBObject interface * Defines business methods: - same signatures as for those equivalent method implementations in the bean class. - throw java.rmi.RemoteException * Extends EJBHome interface * Defines create methods: - same number defined as there are ejbCreate methods in the bean class. Session Bean Class EJBObject EJB Container * Implements SessionBean interface * Implements business methods * Defined as a public class * Cannot be abstract or final class * Contains a public constructor with no parameters * Implements one or more ejbCreate methods * Cannot define the finalize method EJBHome figure 1.5.2 Session Bean interactions with a client A Multi-Tiered B2C Internet Retail Solution 20 Ch 2: Background Session Bean Class: Implements the SessionBean interface: SessionBean interface extends both the java.io.Serializable and EnterpriseBean interfaces. The container uses the SessionBean methods to notify session bean instances of the instance's life cycle events. The SessionBean methods which must be implemented differ from those of entity beans. They are: setEntityContext, ejbRemove, ejbActivate, ejbPassivate. (See EJB Life-Cycles section below). The latter two are unnecessary for stateless session beans. Implements one or more ejbCreate methods: N.B. Session beans implement neither ejbPostCreate methods nor ejbFindBy methods. Home Interface: As for entity beans, but without any FindBy methods. Remote Interface: As for entity beans. A Multi-Tiered B2C Internet Retail Solution 21 Ch 2: Background EJB Life-cycles A synopsis of the life-cycles of enterprise beans is presented here to complete the background information on enterprise beans. The EJB container is responsible for handling the life-cycle of an enterprise bean and it is not possible to explicitly manage the life-cycle through a J2EE application. The individual stages of each of the EJB life-cycles are expanded on below. Entity Bean: As can be seen in the proceeding diagram, an entity bean passes through a pooled stage before being activated. To start with, the EJB container creates an instance of the entity bean and invokes the setEntityContext method, which passes the runtime entity context to the bean. The instance is then pooled with all the other available entity bean instances. All pooled instances are identical. When a client invokes the create method, the EJB container calls ejbCreate and ejbPostCreate methods. This serves to associate the instance with a particular identity and moves the instance to the ready stage, where its business methods can be called. The entity bean may also enter the ready stage if the EJB container calls its ejbActivate method in order to associate it with an EJB object. When using beanmanaged persistence, ejbCreate and ejbActivate must set the primary key of the entity bean. If they fail to do so, ejbLoad and ejbStore will not be able to synchronize its variables with the database. A Multi-Tiered B2C Internet Retail Solution 22 Ch 2: Background The EJB container may return the entity bean to the pooled stage by invoking the ejbPassivate method. Alternatively, a client may call the remove method, resulting in the EJB container calling the ejbRemove method. This action also results in the disassociation of the EJB object from the enterprise bean and a return to the pooled stage. The final phase of the life-cycle comes about when the EJB container invokes the unsetEntityContext method and removes the entity bean instance from the pool. Stateful Session Bean: Stateful session beans are initialized after a client calls the create method, which the EJB container follows up by instantiating the bean, then invoking the setSessionContext and ejbCreate methods. This places the session bean in the ready state, where it may execute its business logic. The session bean may be passivated (which moves it to secondary storage) by the EJB container calling the ejbPassivate method. If a client invokes a method on the session bean while it is passivated, the container returns it to the ready stage by calling the ejbActivate method. When the client calls the remove method, the container removes the instance from the ready pool by calling the ejbRemove method. The instance may then be garbage collected. A Multi-Tiered B2C Internet Retail Solution 23 Ch 2: Background Stateless Session Bean: The stateless session bean’s life cycle is identical to that of the stateful session bean, except it is never moved to secondary storage (i.e. it is never passivate) and so only ever exists in the ready stage or not at all. Stateless session beans are far less resource-intensive than their stateful relations. Message-Driven Bean: Message beans do not have remote and home interfaces defining client access. The life-cycle is similar to that of the stateless session bean. A Multi-Tiered B2C Internet Retail Solution 24 Ch 2: Background J2EE Application Scenarios: Web Container EJB Container Web Container EJB Container Web browser EIS (Enterprise Information System) Stand-Alone Client The various, possible interactions within a J2EE architectural infrastructure are depicted above. J2EE provides the flexibility needed in order to allow for development of applications which can fit these models. A J2EE application consists of one or more modules. A module is assembled by separately packaging each J2EE component along with their utility classes and related files. Each module also contains a deployment descriptor XML file which describes the component’s deployment settings (see Deployment Descriptor section below). An enterprise bean module would consist of the enterprise bean class, its home and remote interfaces, any related files (e.g. a bespoke application-exception class) and a deployment descriptor. Enterprise bean modules are JAR (Java Archive) files. A web module would consist of one or more web components (JSP pages or servlets) along with any static HTML files, image files, helper classes, and the deployment descriptor for the module. This web module is a WAR (Web Archive) file. An application client would be packaged into a JAR file in a similar manner. These modules are assembled in a J2EE application, and the application itself is packaged in an EAR2 (Enterprise Archive) file, ready to be deployed on the server. Deployment Descriptor The deployment descriptor is an XML file which describes the specific configuration requirements of a module such as security settings, resource references and transaction management settings. The J2EE server reads the deployment descriptor at runtime in order to ascertain the configuration requirements of an application. 2 An EAR file is a JAR file with an .ear extension A Multi-Tiered B2C Internet Retail Solution 25 Ch 2: Background This architecture is demonstrated3 in figure 1.6. The TestEJB entity bean is packaged with its deployment descriptor in a JAR file (TestJAR) and the web component TestServlet is packaged in a WAR (TestWAR) along with its deployment descriptor. These two modules are assembled together in the J2EE application, Test. The EAR file is not displayed in this view. figure 1.6 deploytool display of J2EE application assembly The development of a J2EE application is a bottom-up procedure. Create enterprise beans Create web/application components Create J2EE application Package components into modules of the J2EE application Deploy Application on server The third and fourth stage are interchangeable, depending on whether an application assembler is making use of the GUI application deploytool provided with the J2EE SDK, or is using command line assembly (which swaps the two stages around). J2EE Reference Implementation The J2EE Reference Implementation, which was originally going to be used throughout the development, assembly, deployment and testing aspects of this project, is a free download provided by Sun for demonstrations, prototyping, and educational use. The included support consists of J2EE development and deployment tools, Java WebServerTM, Cloudscape database, Java Software application server, Extensible Markup Language (XML) support, and the J2EE APIs. Sun also provide the J2EE IDE 2.0 beta release Toolkit which integrates Forte for Java 2.0, with the J2EE Deploytool. This toolkit was used, at the advice of my project supervisor, instead of the reference implementation. The results of this choice are given in full in the Evaluation chapter. 3 The deploytool which presents this view is included in the J2EE reference implementation A Multi-Tiered B2C Internet Retail Solution 26