Saturday, May 21, 2011

EJB Architecture

EJB Architecture

The Sun ONE Application Server reduces the complexity of developing middleware by providing automatic support for middleware services such as transactions, security, database connectivity, and more.

The following figure illustrates where enterprise beans fit in the J2EE environment. In this figure the client machine is running a web browser or application client, the J2EE server machine is running (or hosting) the Sun ONE Application Server, and the database server machine hosts the databases, such as Oracle and LDAP. Enterprise beans reside in the business tier, with JSPs (and servlets) providing the interface to the client tier, and the Sun ONE Application Server managing the relationships between the client and database machines.


Figure shows Sun ONE Application Server archtitecture. Illustrates client tier, web tier, business tier, EIS tier.

The Sun ONE Application Server is responsible for providing the base of the EJB execution systems, which include:

  • A standard set of EJB services
  • Distributed transaction management services
  • A means of data store access or backend system connection
  • An EJB container to implement the management and control services for the EJB classes

The following figure illustrates further details of the J2EE environment. The business logic layer shows the EJB flow.


Figure shows detailed J2EE environment. Illustrates the contents and flow of the client layer, the presentation layer,  the business logic layer, and the data access layer.

Value Added Features

The Sun ONE Application Server provides a number of value additions that relate to EJB development. These capabilities are discussed in the following sections (references to more in-depth material are included):

Read-Only Beans

Another feature that the Sun ONE Application Server provides is the read-only bean, an entity bean that is never modified by an EJB client. Read-0nly beans avoid database updates completely.

A read-only bean can be used to cache a database entry that is frequently accessed but rarely updated (externally by other beans). When the data that is cached by a read-only bean is updated by another bean, the read-only bean can be notified to refresh its cached data.

The Sun ONE Application Server provides a number of ways by which a read-only bean's state can be refreshed. By setting the refresh-period-in-seconds element and the transaction attribute of the bean, it is easy to configure a read-only bean that is (a) always refreshed, (b) periodically refreshed, (c) never refreshed, or (d) programatically refreshed.

Read-only beans are best suited for situations where the underlying data never changes, or changes infrequently. For further information and usage guidelines, see "Read-Only Beans".

pass-by-reference

The pass-by-reference element in the sun-ejb-jar.xml file allows you to specify the passing method/argument type used by enterprise beans. This is an opportunity to improve performance. See "pass-by-reference".

Pooling and Caching Features

The Sun ONE Application Server provides a highly configurable bean pooling mechanism that allows the deployer to configure bean pools according to the needs of the enterprise.

In addition, the Sun ONE Application Server supports a number of tunable parameters that can be used to control the number of beans cached as well as the duration they are cached. Multiple bean instances that refer to the same database row in a table can be cached.

Refer to "Pooling and Caching" for information on this functionality.

Monitoring

The Sun ONE Application Server supports monitoring of many aspects of the runtime environment, including various elements of the EJB container which can be useful for debugging your application's correctness as well as tuning its performance.

See the Sun ONE Application Server Administrator's Guide (Monitoring and Managing Sun One Application Server section) and the Performance, Tuning, and Sizing Guide for more information on monitoring.

Integration with Sun ONE Studio 4

Sun ONE Studio 4, Enterprise Edition for Java (formerly Forte for Java (FFJ), Enterprise Edition), is an integrated development environment (IDE) that allows you to create, assemble, deploy, and debug code in the Sun ONE Application Server from a single, easy-to-use interface. Behind the scenes, a plugin integrates the Sun ONE Studio 4 IDE with the Sun ONE Application Server.

For more information about using the Sun ONE Studio 4, see the Sun ONE Studio 4, Enterprise Edition tutorial and "CMP Mapping with the Sun ONE Studio 4 Interface".

Dynamic Deployment and Reloading

You can deploy, redeploy, and undeploy an application or standalone module. If this is done while the server is running, it is considered dynamic. The following dynamic processes are available in Sun ONE Application Server:

  • Dynamic reloading—Enables reloading the classes that constitute an application when they change on disk.
  • Dynamic redeployment (for the developer community)—Enables redeploying an existing application without restarting the server. You can ALSO disable and enable an application or module without undeploying it.

For more information on dynamic deployment, refer to the Sun ONE Application Server Developer's Guide and Administrator's Guide.

About Enterprise JavaBeans

If you are already familiar with enterprise beans and how they work, you may prefer to proceed to "About Developing an Effective Application"

The following topics are discussed in this section:

What Is an Enterprise JavaBean?

An enterprise bean, or Enterprise JavaBean (EJB), is a self-contained, reusable component that has data members, properties, and methods. Each enterprise bean encapsulates one or more application tasks or objects, including data structures and operation methods.

  • Enterprise bean methods can take parameters and send back return values.
  • Enterprise bean creation and management is handled at runtime by the container.
  • Client access mediation is handled by the container and the server where the bean is deployed.
  • Enterprise beans are restricted to using standard container services defined by the Enterprise JavaBeans Specification, v2.0. This guarantees that the bean is portable and deployable in any EJB-compliant container.
  • Enterprise beans are components that can be assembled, without recompiling, into a composite application.
  • A client's bean definition view is controlled entirely by the bean developer. The view is not affected by the container in which the bean runs or the server where the bean is deployed.

For several reasons, enterprise beans simplify the development of large, distributed applications.

  • Container-provided services—Because the EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. The EJB container—not the bean developer—is responsible for system-level services such as transaction management and security authorization.
  • Remote clients—Because the enterprise beans, not the clients, contain the application's business logic, the client developer can focus on the presentation of the client. The client developer does not have to code the routines that implement business rules or access databases. As a result, the clients are thinner, a benefit that is particularly important for clients that run on small devices.
  • Bean reusability—Because enterprise beans are portable components, the application assembler can build new applications from existing beans. These applications can run on any compliant J2EE server.

Types of Beans

There are three distinct types of enterprise beans:

  • Session bean, stateful or stateless
    • A stateful session bean is intended to represent objects and processes that maintain state across invocations, such as a document copy for editing, or specialized business objects for individual clients.
    • A stateless session bean encapsulates a transient or temporary piece of business logic needed by a specific client that does not maintain state across invocations.
    • Refer to "Using Session Beans"," for information on developing session beans.

  • Entity bean—An entity bean commonly represents persistent data which is maintained directly in a database or accessed through an Enterprise Information System (EIS) application as an object.
    • Bean-managed persistence—The bean is responsible for its own persistence. The entity bean code that you write contains the calls that access the database. For information on developing entity beans in general and bean-managed persistence in particular, refer to "Using Entity Beans".
    • Container-managed persistence—The enterprise bean container handles all database access required by the entity bean by interacting through the persistence manager. For information on container-managed persistence, refer to "Using Container-Managed Persistence for Entity Beans".

  • Message-driven bean—A message-driven bean represents a stateless service; it is essentially an asynchronous message consumer, invoked by JMS, that is completely anonymous and has no client-visible identity.
  • Refer to "Using Message-Driven Beans", for information on developing message-driven beans.

EJB Flow

When a user invokes a Sun ONE Application Server servlet from a browser, the servlet may invoke one or more enterprise beans. For example, the servlet may load a JavaServer Page (JSP) to the user's browser to request a user name and password, then pass the user input to a session bean to validate the input.


Figure shows EJB flow, from user interface to database and back.

After a valid user name and password combination is accepted, the servlet might instantiate one or more entity and session beans to run the application's business logic, then terminate. The beans themselves might instantiate other entity or session beans to do further business logic and data processing.

Sample Scenario

A servlet invokes a session bean that gives a customer service representative access to an order database. This access might include the ability to:

  • Browse the database
  • Queue items for purchase
  • Place customer orders
  • Permanently reduce number of parts in the database
  • Bill the customer
  • Reorder parts when the stock is low or depleted.

As part of the customer order process, a servlet creates a session bean that manages a shopping cart to keep temporary track of items as a customer selects them. When the order completes, the shopping cart data transfers to the order database and the shopping cart session bean is freed.

The EJB Container

Enterprise beans always work within the context of a container. The container serves as a link between the enterprise beans and the hosting server. The EJB container enables distributed application building using your own components and components from other suppliers.

Through the container, the Sun ONE Application Server provides high-level transaction management, security management, state management (persistence), multithreading, and resource pooling wrappers, thereby shielding you from having to know the low-level API details. By handling concurrency, the container shields you from worry about entities (hence, threads) simultaneously accessing an enterprise bean. This container provides all standard container services denoted by the Enterprise JavaBeans Specification, v2.0, and also provides additional services specific to the Sun ONE Application Server.

The Sun ONE Application Server services include remote access, naming service, security service, concurrency, transaction control, and database access. The following figure illustrates the EJB container provided by the Sun ONE Application Server.


Figure shows EJB container components.

Interfaces

A client never accesses session or entity EJB instances directly. Instead, a client uses the bean's remote interface to access a bean instance. The EJB object class that implements a bean's remote interface is provided by the container.

Home Interface

The home interface provides a mechanism for clients to create and destroy and find EJBs. The EJB supplies a home interface for the container that extends the javax.ejb.EJBHome interface defined in the EJB specification. At its most basic, the home interface defines zero or more create methods for each way to create a bean.

Entity beans must define finder methods for each way that can be used to look up a bean or a collection of beans.

Remote Interface

A remote interface (and remote home interface) provides a mechanism for remote clients to access session or entity beans. A remote client can be another EJB deployed in the same or a different container, or a Java program, such as an application, applet, or servlet. The remote client view of an EJB is location independent and can be mapped to non-Java client environments.

The remote home interface is defined by the EJB developer and implemented by the EJB container.

Local Interface

A local interface (and local home interface) provides a mechanism for a client that is located in the same Java Virtual Machine (JVM) with the session or entity bean to access that bean.This provides the local client view. A local client may be tightly coupled to the associated bean; session and entity beans can have many local clients.

The container provides the class that implements the local home interface and local interface. The objects that implement these interfaces are local Java objects. The local client view of an EJB is not location independent.

The following diagram shows a local client connecting through the local interfaces within the two enterprise beans in the container.


Figure shows a client on the Java Virtual Machine using local interfaces in the container to connect to EJBs.

The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container.

Pooling and Caching

The EJB container of the Sun ONE Application Server pools anonymous instances (message-driven beans, stateless session beans, and entity beans) to reduce the overhead of creating and destroying objects. The EJB container maintains the free pool for each bean that is deployed. Bean instances in the free pool have no identity (that is, no primary key associated) and are used to serve the method calls of the home interface. The free beans are also used to serve all methods for stateless session beans.

Bean instances in the free pool transition from a Pooled state to a Cached state after ejbCreate and the business methods run. The size and behavior of each pool can be controlled using the pool-related properties in the server.xml and sun-ejb-jar.xml files.

The EJB container caches "stateful" instances (stateful session beans and entity beans) in memory to improve performance. The EJB container maintains a cache for each bean that is deployed.

To achieve scalability, the container will selectively evicts some bean instances from the cache, usually when cache overflows. These evicted bean instances return to the free bean pool. The size and behavior of each cache can be controlled using the cache-related properties in the server.xml and sun-ejb-jar.xml files.

Pooling and caching parameters for the sun-ejb-jar.xml file are discussed in "Pooling and Caching Elements".

Pooling Parameters

One of the most important parameters of Sun ONE Application Server pooling is steady-pool-size. When steady-pool-size is set to greater than 0, the container not only pre-populates the bean pool with the specified number of beans, but also attempts to ensure that there is always this many beans in the free pool. This ensures that there are enough beans in the ready to serve state to process user requests.

Another parameter, pool-idle-timeout-in-seconds, allows the administrator to specify, through the amount of time a bean instance can be idle in the pool. When pool-idle-timeout-in-seconds is set to greater than 0, the container removes/destroys any bean instance that is idle for this specified duration.

Caching Parameters

Sun ONE Application Server provides a way that completely avoids caching of entity beans, using commit-c option. Commit-c option is particularly useful if beans are accessed in large number but very rarely reused. For additional information, refer to "Commit Options".

The Sun ONE Application Server caches can be either bounded or unbounded. Bounded caches have limits on the number of beans that they can hold beyond which beans are passivated. For stateful session beans, there are three ways (LRU, NRU and FIFO) of picking victim beans when cache overflow occurs. Caches can also be configured to passivate beans that were idle (not accessed for a specified duration) to be passivated.

How Enterprise Beans Access Resources

Enterprise beans can access a wide variety of resources, including databases, JavaMail sessions, JMS objects, and URLs. The J2EE platform provides mechanisms that allow you to access all of these resources in a similar manner.

This section discusses the following:

JNDI Connection

J2EE components locate the objects they need to access by invoking the lookup method of the Java Naming and Directory Interface (JNDI) API. The value returned by this call represents the object that the caller wants to access. In the case of an enterprise beans, the lookup call returns an object reference to the home interface of the bean. This reference may be used for all future invocations on the EJB home interface.

Context initial = new InitialContext();
Object objref
initial.lookup("java:comp/env/ejb/CompString");

A J2EE component on the server (a JSP, servlet, or enterprise bean) that wants to access a deployed enterprise bean, uses an EJB reference element in its deployment descriptor to specify this access. The EJB reference is mapped at deployment time to the JNDI name corresponding to the enterprise bean that the component wishes to access. This mapping serves to decouple components accessing enterprise beans from the JNDI names of the beans being accessed. Thus, the JNDI name to which an EJB's home is bound may be changed at deployment time without requiring the caller's code to change.

Database Connection

The persistence type of an enterprise bean determines whether or not you will code the connection routine for accessing a database.

  • For beans that access a database and do not use container-managed persistence—You are responsible for writing persistence code. Such beans include entity beans that use bean-managed persistence and session beans.
  • For beans that use container-managed persistence—Connection routines are generated for you at deployment. Applies only to entity beans.

URL Connections

A Uniform Resource Locator (URL) specifies the location of a resource on the web, such as web pages. These URLs then can be mapped to JNDI names so that developers can lookup the URLs.

Transaction Management

By dividing the application's work into units called transactions, you are freed from dealing with the complex issues of database failure recovery and maintaining database integrity.

As a developer, you can choose between using programmatic transaction demarcation in the EJB code (bean-managed) or declarative demarcation (container-managed). Regardless of whether an enterprise bean uses bean-managed or container-managed transaction demarcation, the burden of implementing transaction management is on the EJB container and theSun ONE Application Server. The container and the server implement the necessary low-level transaction protocols, such as the two-phase commit protocol, between a transaction manager and a database system or Sun ONE Message Queue provider.

For information on transaction handling, refer to "Handling Transactions with Enterprise Beans".

How Application Security Works

The J2EE application programming model insulates developers from mechanism-specific implementation details of application security. For the most part, the container provides the implementation of the security infrastructure. J2EE provides this insulation in a way that enhances the portability of applications, allowing them to be deployed in diverse security environments with no additional coding.

The declarative security mechanisms used in an application are expressed in the deployment descriptor. The deployer then uses specific Sun ONE Application Server tools to map the application requirements that are in a deployment descriptor to the security mechanisms that are implemented by the container.

Refer to "Developing Secure Enterprise Beans" for further information. For information on security realms, refer to the Sun ONE Application Server Developer's Guide.

About Developing an Effective Application

Partitioning a Sun ONE Application Server application's business logic and data processing into the most effective set of servlets, JSPs, session beans, entity beans, and message-driven beans is the crux of your job as a developer. There are no specific rules for object-oriented design with enterprise beans, other than that entity bean instances tend to be long lived, persistent, and shared among clients, while session bean instances tend to be short lived and used only by a single client; message-driven beans are in their own category as the only asynchronous receivers of JMS messages.

In general, your goal is to create a Sun ONE Application Server application that effectively balances the need for execution speed with the need for sharing enterprise beans (among applications and clients) and easily deploying applications across servers.

High-level information and guidelines which can help you develop enterprise beans in the Sun ONE Application Server environment are addressed in the following sections:

General Process for Creating Enterprise Beans

The procedure in this section outlines the general process of creating an enterprise bean. Specific instructions on creating the various types of enterprise beans are contained in the sections referenced in the following steps.

To create an enterprise bean:

  1. Create a directory for all the enterprise bean's files.
  2. Decide on the type of enterprise bean you are creating:
  3. Write the code for the enterprise bean according to the EJB specification, including:
    • A local and/or remote home interface
    • A local and/or remote interface
    • An implementation class (for a message-driven bean, this is all you need)

  4. Compile the interfaces and classes.
  5. Create the META-INF directory and the other structural requirements of an enterprise bean.
  6. Create the deployment descriptor files, ejb-jar.xml and sun-ejb-jar.xml. (Refer to "Assembling and Deploying Enterprise Beans".)
  7. If the bean is an entity bean with container-managed persistence, you must also create a sun-cmp-mappings.xml file and a .dbschema file. (Refer to "Using Container-Managed Persistence".)

  8. Package the class and the XML files to a JAR file, if desired. If you are using directory deployment, this is optional.
  9. Deploy the bean by itself or include it in a J2EE application. (Refer to the Sun ONE Application Server Developer's Guide.)

It's a good idea to verify the structure of these files using the verifier tool as described in the Sun ONE Application Server Developer's Guide.

Bean Usage Guidelines

Deciding which parts of an application are candidates for entity beans and which are candidates for session beans (stateful or stateless) or message-driven beans will have a significant impact on the effectiveness of your application. In general:

  • Use a stateful bean to store non-shared data that corresponds to the user conversational state, that is, a state specific to a single user.
  • Use a stateless session bean to access data or perform transactional operations.
  • Create session beans that are small, generic, and narrowly task focused. Ideally, these enterprise beans encapsulate behavior that is used in many applications.
  • Ask the application assembler to co-locate enterprise beans with your presentation logic (servlets and JSPs) on the same server. This reduces the number of Remote Procedure Calls (RPCs) when the application runs.
  • The applications should explicitly remove the beans using the ejbRemove method when they are no longer required, thereby reducing the overhead on the container (by eliminating the passivation process).
  • Unique naming is optional across enterprise beans in different applications, although applications do need to be named uniquely within the context of a single application server instance. That is, enterprise beans within an application cannot have the same name.

For further information on EJB developer guidelines, refer to "Using Session Beans", "Using Entity Beans", and "Using Message-Driven Beans".

Client View Guidelines

The choice between the use of local and remote interfaces is a design decision that you, the developer, make when developing an enterprise bean. The following facts should be taken into account in determining whether the local or remote programming model should be used:

  • The remote programming model provides location independence and flexibility with regard to deployment. The client and enterprise bean are loosely coupled.
  • Remote calls involve pass-by-value, providing a layer of isolation between caller and callee. This protects against inadvertent modification of data.
  • For local objects, pass-by-reference is optional and is not mandated by the J2EE specification
  • Remote calls are potentially expensive.
  • Remote calls require that objects that are passed as parameters be serializable.
  • Narrowing remote types requires the use of javax.rmi.PortableRemote.Object.narrow rather than Java language casts.
  • Remote calls involve error cases that are not expected in local calls. The client has to explicitly program handlers for these remote exceptions.
  • Because of the overhead of remote programming, it is typically used for relatively coarse-grained component access.
  • Local calls can optionally involve pass-by-reference. The client and the bean may be programmed to rely on pass-by-reference semantics. Locals calls imply that the local client and the enterprise bean must be co-located.
  • Because local programming provides lighter-weight access to a component, it better supports more fine-grained component access.
  • Be aware of the potential sharing of objects passed through the local interface.

For additional information, refer to the Enterprise JavaBeans Specification, v2.0.

Remote or Local Interface Guidelines

With all object-oriented development, you must determine the granularity level needed for your business logic and data processing. Granularity level refers to how many pieces to divide an application into.

  • A low level of granularity (a low number of beans and bean method invocations)—A more monolithic application is developed, creating an application that is not as likely to promote sharing and reuse, but usually executes more quickly.
  • A high level of granularity (a high number of beans and bean method invocations)—An application is divided into many, smaller, more narrowly defined enterprise beans. This creates an application that may promote greater sharing and reuse of enterprise beans among different applications at your site.
  • Dividing a distributed application into a moderate to large number of separate beans degrade performance degradation and more overhead. Enterprise beans are not simply Java objects; they are higher-level entities with remote call interface semantics, security semantics, transaction semantics, and properties. This complexity creates overhead.

Accessing Sun ONE Application Server Functionality

You can develop entity beans that adhere strictly to the Enterprise JavaBeans Specification, v2.0, or you can develop entity beans that take advantage of both the specification and additional, value-added Sun ONE Application Server features.

The Sun ONE Application Server offers several features available only in the Sun ONE Application Server container. The Sun ONE Application Server APIs enable applications to take programmatic advantage of specific Sun ONE Application Server environment features.



Note

Use these APIs only if you plan on using those beans exclusively in a Sun ONE Application Server environment.



About EJB Assembly and Deployment

The process of assembling modules and applications in Sun ONE Application Server conforms to all the customary J2EE-defined specifications, however, you can include the Sun ONE Application Server-specific deployment descriptors that enhance the functionality of the Sun ONE Application Server beyond the J2EE specifications.

A J2EE module is a collection of one or more J2EE components with two deployment descriptors of that type. One descriptor is J2EE standard, the other is specific to Sun ONE Application Server. For enterprise beans, the following deployment descriptor files apply:

  • ejb-jar.xml—J2EE standard file
  • sun-ejb-jar.xml—Sun ONE Application Server-specific file
  • sun-cmp-mappings.xml—Sun ONE Application Server-specific file used for container-managed persistence mapping

Information on the EJB DTDs and XML files is contained in "Assembling and Deploying Enterprise Beans".

An alphabetical list of all EJB-related elements is contained in "Elements Listings".

General information on assembly and deployment is contained in the Sun ONE Application Server Developer's Guide.

Deployment procedures are contained in the Sun ONE Application Server Administrator's Guide and the Administration interface online help.

No comments:

Post a Comment