Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Mastering Enterprise JavaBeans™ and the Java 2 Platform, Enterprise Edition - Roman E

..pdf
Скачиваний:
41
Добавлен:
24.05.2014
Размер:
6.28 Mб
Скачать

Enterprise JavaBeans Overview

 

65

right next door to you, or on the client’s machine itself. It could even reside in the client code’s address space (such as an application server that supports Java servlets and enterprise beans in a single JVM). Whatever is the case, the client should be totally unaware of where the component really is—whether the component is local or remote should be transparent to the client. This is known as location transparency.

Why is location transparency beneficial? Well, for one thing, you aren’t writing your bean’s client code to take advantage of a particular deployment configuration because you’re not hard-coding machine locations. This is an essential part of reusable components that can be deployed in a wide variety of multitier situations.

Location transparency also enables container vendors to provide additional value-adds, such as the ability to take a machine on the network down temporarily to perform system maintenance, to install new software, or to upgrade the components on that machine. During maintenance, location transparency allows for another machine on the network to serve up components for a component’s client because that client is not dependent on the hard locations of any components. If a machine that has components on it crashes due to hardware or software error, you may be able to reroute client invocations to other machines without the client even knowing about the crash, allowing for an enhanced level of fault-tolerance.

Glue-Code and Bean Installation Tools

Each EJB container ships with a suite of glue-code tools. These tools are meant to integrate beans into the EJB container’s environment. The tools generate helper Java code, such as stubs, skeletons, data access classes, and other classes that this specific container requires. Bean providers do not have to think about the specifics of how each EJB container works because the container’s tools generate its own proprietary Java code automatically.

The container’s glue-code tools are responsible for transforming an enterprise bean into a fully managed, distributed server-side component. This involves logic to handle resource management, life cycle, state management, transactions, security, persistence, and remote accessibility—every service we’ve mentioned so far. The automatic code generated handles these services in the container’s proprietary way.

Specialized Container Features

Beyond the normal duties of a container, specialized containers can provide additional qualities of service that are not required by the EJB 1.0 specification. Most vendors have several different versions of their containers for sale, allowing

Go back to the first page for a quick link to buy this book online!

66

 

M A S T E R I N G E N T E R P R I S E J A V A B E A N S

customers to pay for what they get. These services help differentiate EJB container vendors, allow for innovation, and foster best-of-breed products. They also add an element of danger. If a bean depends on particular qualities of service, it may not run in other containers.

For example, let’s take the case of a load-balancing service. Load-balancing is the fair selection of components on behalf of their clients. These components may reside in many containers, housed in multiple EJB servers, distributed across the network. Given the fact that N-tier deployments can vary widely in the actual physical locations of components, the actual load-balancing algorithm is implementation dependent. This allows a lot of creativity for the EJB container provider. For example, some containers may provide a way to perform customized load balancing between distributed components. The customized load-balancer might be tunable for particular deployments and might make the overall system more scalable.

A high-end EJB container may also provide dynamic resizing of managed resources and components. For example, if clients are less active at night than during the day, perhaps a smaller pool of resources is necessary at night. Some EJB containers may be intelligent enough to allow for this dynamic resizing of pools, yielding precious machine resources to be used for other purposes.

Other examples of specialized container functions could include the following:

■■Integration to mainframe systems

■■COM+ integration

■■Transparent fail-over

■■Stateful recovery

■■Web server, servlet, and JSP support within the container

■■Server clustering

■■Dynamic redeployment of components in a running system

■■Support for a variety of persistence mechanisms, including relational and object databases

■■Shared object caches to improve the number of times a database needs to be accessed

■■Sophisticated monitoring support

■■Distributed transactions

■■Resolution of the transactional distributed diamond problem

■■Complex database persistence services

■■Visual development environment integration

Go back to the first page for a quick link to buy this book online!

Enterprise JavaBeans Overview

 

67

■■Integrated XML facilities

■■CORBA integration and support

These are merely examples of the variety of services that a vendor could choose to add. The key idea to keep in mind when choosing to use services such as these is whether the services lock you into a particular vendor. If so, you need to ask yourself if that’s a safe bet and if you want your components to be deployable across a variety of middleware vendor products.

Summary

In this chapter, we’ve taken a whirlwind tour of Enterprise JavaBeans. We started by looking at how EJB promotes a divide-and-conquer approach to server-side computing by defining the roles of six parties in a successful EJB deployment. We then went into what an enterprise bean is, and we looked at the different kinds of beans, including session and entity beans, and their subtypes. We analyzed the trade-offs of when it was appropriate to use each kind of bean.

Finally, we took a look at the responsibilities of the EJB container and server. We examined the services containers provide to distributed server-side components, such as resource management, state management, and location transparency.

And congratulations—you’ve made it to the end of Part I! In these two chapters, you’ve taken the first steps necessary to understanding and mastering Enterprise JavaBeans. Now that you understand the high-level concepts, let’s move on and begin programming with EJB.

Go back to the first page for a quick link to buy this book online!

P A R T TWO

Developing Beans

or a successful server-side deployment, typically six major steps must be under- Ftaken. Each of these steps can be a collaboration between several individuals,

perhaps from different companies.

1.Get the application requirements down. Before embarking full-steam on writing a multi-tier distributed application, you should always spend a significant amount of time in a design phase. You should learn who will use your application, what its purpose is, and what the application requirements are. Are you or your customers running on Microsoft’s platform, UNIX, or mainframe systems? Do you need to integrate with existing application servers that are already deployed and running? Is there legacy middleware, such as CICS or Tuxedo that you need to support? Which application vendors do you need to support, such as SAP or Peoplesoft? How compatible are their products with server-side development platforms such as Windows DNA or J2EE? All of this information is necessary before you can finally make a decision on a server-side development platform.

2.Decide on a distributed object architecture, and design your application. Once you’ve settled on your application requirements, you should choose the server-side development platform that best fits your needs. Once you’ve done this, you can begin designing your application. This includes breaking up your application into components, designing your object model, specifying the interfaces between your major subsystems, and whiteboarding your application’s interactions. The Unified Modeling Language (UML) is an excellent language for this type of object modeling (the diagrams in this book are written mostly in UML). You should also look at what other vendors are building reusable components in your vertical market, as it may save you development time to buy rather than build.

69

Go back to the first page for a quick link to buy this book online!

70

 

M A S T E R I N G E N T E R P R I S E J A V A B E A N S

3.Develop or purchase reusable components. Assuming you choose the J2EE platform, you can then decide on developing your own beans or purchasing them. If you choose to build your own components, you can either develop them from scratch or wrap existing legacy systems. You can also buy prewritten enterprise beans supplied by third parties.

4.Assemble the application. Once you’ve developed a core set of components, you can start putting them to use in specific applications. This stage involves writing client code that calls your components, making them useful for a specific business or workflow. Your client code can be inside a Java applet, servlets running within a Web server, or elsewhere. They can be Javabased clients or CORBA-based clients. When you assemble your application, you can also develop custom components that your specific application needs.

5.Deploy the beans. Now that a specific application has been developed, you can physically deploy your beans inside of an EJB container/server. At this stage, you should be customizing your components for this specific deployment, such as mapping security roles to existing users in an LDAP server.

6.Oversee the deployment. Once the deployment has gone live, a system administrator should be appointed to oversee the stability of the deployed system.

In Part II, we’ll focus on the development details for implementing an EJB application. We’ll see how to write both major types of enterprise beans: session beans and entity beans. Session beans represent a business process, such as computing the price of an order, transferring funds from one bank account to another, performing statistical analysis, and so on. Entity beans are persistent business objects, and they are an object-oriented view into an underlying data store.

We’ll also see how to assemble applications using enterprise beans. You’ll learn about how to write client code that calls into enterprise beans to solve a business problem. This entails understanding the contract that clients must abide by to use EJB.

Part II is great for those of you who are ready to get down-and-dirty with EJB programming fundamentals. The more advanced topics, such as transactions and CORBA, are reserved for future chapters.

Go back to the first page for a quick link to buy this book online!

C H A P T E R3

Introduction to Session Beans

n this chapter, we’ll take our first look at enterprise bean development concepts. IThis chapter covers the following topics:

1.What an enterprise bean component is composed of, including the enterprise bean class, the remote interface, the EJB object, the home interface, the home object, the deployment descriptor, the manifest, and the Ejb-jar file.

2.The characteristics of session beans. We’ll see what makes session beans unique, and we’ll introduce the differences between stateful and stateless session beans.

3.The rules for writing session bean classes.

4.How to write client code to call session beans.

This chapter lays the necessary conceptual framework for you to begin EJB programming. We’ll see complete code examples in Chapters 4, 5, and 6.

EJB depends on several other technologies in the Java 2 Platform, Enterprise Edition suite. If you’re having difficulty understanding this chapter, you may find it helpful to read several of the appendices first—in particular, Appendix A (covering Java Remote Method Invocation) and Appendix B (covering the Java Naming and Directory Interface).

What Constitutes an Enterprise Bean?

Enterprise beans are distributed, deployable server-side components that can be assembled into larger applications. Enterprise beans can be partitioned across

71

Go back to the first page for a quick link to buy this book online!

72

 

M A S T E R I N G E N T E R P R I S E J A V A B E A N S

multiple tiers, can be transactional, can be multiuser secure, and can be deployed in any EJB-compatible container/server product.

Enterprise beans currently have two flavors: session beans and entity beans. Session beans represent a business process, whereas entity beans represent permanent business data. Sun Microsystems may introduce other bean types in the future as well.

This section examines exactly what constitutes an enterprise bean. As we will see, an enterprise bean component is not a single monolothic file—a number of files work together to make up an enterprise bean.

The Enterprise Bean Class

In Part I, we learned that the Enterprise JavaBeans specification defines the contracts between the different parties involved in a deployment. In order for a bean to work in any container, and to work with any client of that bean, the bean must adhere to a well-defined interface. In EJB, you provide your enterprise bean component implementation in an enterprise bean class. This is simply a Java class that conforms to a well-defined interface and obeys certain rules.

An enterprise bean class contains implementation details of your component. And although there are no hard-and-fast rules in EJB, a session bean implementation will be very different from an entity bean implementation. For session beans, an enterprise bean class typically contains business-process-related logic, such as logic to compute prices, transfer funds between bank accounts, or perform order entry. For entity beans, an enterprise bean class typically contains data-related logic, such as logic to change the name of a customer, reduce the balance of a bank account, or modify a purchase order.

The EJB specification defines a few standard interfaces that your bean class can implement. These interfaces force your bean class to expose certain methods that all beans must provide, as defined by the EJB component model. The container calls these required methods to manage your bean and alert your bean to significant events.

The most basic interface that all bean classes must implement (both session and entity) is the javax.ejb.EnterpriseBean interface, shown in Source 3.1.

public interface javax.ejb.EnterpriseBean extends java.io.Serializable

{

}

Source 3.1 The javax.ejb.EnterpriseBean interface.

Go back to the first page for a quick link to buy this book online!

Introduction to Session Beans

 

73

This interface serves as a marker interface; implementing this interface indicates that your class is indeed an enterprise bean class. The interesting aspect of javax.ejb.EnterpriseBean is that it extends java.io.Serializable. This means that all enterprise beans can be converted to a bit-blob and share all the properties of serializable objects (described in Appendix A). This will become important later, so keep it in mind.

Both session beans and entity beans have more specific interfaces that extend the javax.ejb.EnterpriseBean interface. All session beans must implement javax.ejb

.SessionBean, while all entity beans must implement javax.ejb.EntityBean. We’ll see the details of these interfaces a bit later. For now, know that your enterprise bean class never needs to implement the javax.ejb.EnterpriseBean interface directly—rather, your bean class implements the interface corresponding to its bean type.

The EJB Object

When a client wants to use an instance of an enterprise bean class, the client never invokes the method directly on an actual bean instance. Rather, the invocation is intercepted by the EJB container and then delegated to the bean instance. This happens for many reasons:

■■Your enterprise bean class can’t be called across the network directly because an enterprise bean class is not network-enabled. Your EJB container handles networking for you by wrapping your bean in a network-enabled object. The network-enabled object receives calls from clients and delegates these calls to instances of your bean class. This saves you from having to worry about networking issues (the container provides networking as a free service to you).

■■By intercepting requests, the EJB container can automatically perform some necessary management. This includes transaction logic, security logic, bean instance pooling logic, and any other logic that the container may require.

■■The EJB container can track which methods are invoked, display a real-time usage graph on a system administrator’s user interface, gather data for intelligent load balancing, and more. There is no requirement that an EJB container perform these tasks. But because the EJB container intercepts all method calls, there is an opportunity for containers to perform them.

Thus, the EJB container is acting as a layer of indirection between the client code and the bean. This layer of indirection manifests itself as a single networkaware object, called the EJB object. The EJB object is a surrogate object that knows about networking, transactions, security, and more. It is an intelligent object that knows how to perform intermediate logic that the EJB container

Go back to the first page for a quick link to buy this book online!

74

 

M A S T E R I N G E N T E R P R I S E J A V A B E A N S

requires before a method call is serviced by a bean class instance. An EJB object acts as glue between the client and the bean, and it exposes every business method that the bean itself exposes. EJB objects delegate all client requests to beans. We depict EJB objects in Figure 3.1.

You should think of EJB objects as physical parts of the container; all EJB objects have container-specific code inside of them (each container handles middleware differently and provides different qualities of service). Because each bean’s EJB object is different, your container vendor supplies glue-code tools that generate the class file for your EJB objects automatically.

The Remote Interface

As we mentioned previously, bean clients invoke methods on EJB objects, rather than the beans themselves. To perform this, EJB objects must clone every business method that your bean classes expose. But how do the tools that autogenerate EJB objects know which methods to clone? The answer is in a special interface that a bean provider writes. This interface duplicates all the business logic methods that the corresponding bean class exposes. This interface is called the remote interface.

Remote interfaces must comply with special rules that the EJB specification defines. For example, all remote interfaces must derive from a common interface that is supplied by Sun Microsystems. This interface is called javax.ejb.EJBObject, and it is shown in Source 3.2.

EJB Container/Server

Home

Interface

Client Code, such

Home Object

as servlets or applets

4: Route the method return value back to the client

1: Call a method

3: Method returns

EJB Object

Remote

Interface

2:Acquire a Bean, and delegate the method to the Bean

Enterprise

Bean

Figure 3.1 EJB objects.

Go back to the first page for a quick link to buy this book online!

Introduction to Session Beans

 

75

public interface javax.ejb.EJBObject extends java.rmi.Remote

{

public abstract javax.ejb.EJBHome getEJBHome() throws java.rmi.RemoteException;

public abstract java.lang.Object getPrimaryKey() throws java.rmi.RemoteException;

public abstract void remove()

throws java.rmi.RemoteException, javax.ejb.RemoveException;

public abstract javax.ejb.Handle getHandle() throws java.rmi.RemoteException;

public abstract boolean isIdentical(javax.ejb.EJBObject) throws java.rmi.RemoteException;

}

Source 3.2 The javax.ejb.EJBObject interface.

javax.ejb.EJBObject lists a number of interesting methods. Their explanations are previewed in Table 3.1. For now, don’t worry about fully understanding the meanings—just know that these methods are required methods that all EJB objects must implement. And remember that you don’t implement the meth- ods—the EJB container does when it auto-generates the EJB objects for you.

Table 3.1 Required Methods That All EJB Objects Must Expose

METHOD

EXPLANATION

getEJBHome()

Retrieves a reference to the corresponding home object (we describe

 

home objects later).

getPrimaryKey()

Returns the primary key for this EJB object. A primary key is used only for

 

entity beans (see Chapters 7-9).

remove()

Destroys this EJB object. When your client code is done using an EJB

 

object, you should call this method. The system resources for the EJB

 

object can then be reclaimed.

 

Note: For entity beans, remove() also deletes the bean from the

 

underlying persistent store.

getHandle()

Acquires a handle for this EJB object. An EJB handle is a persistent

 

reference to an EJB object that the client can stow away somewhere.

 

Later on, the client can use the handle to reacquire the EJB object and

 

start using it again.

IsIdentical()

Tests whether two EJB objects are identical.

Go back to the first page for a quick link to buy this book online!