20 september 2007kaiser: coms w4156 fall 20071 coms w4156: advanced software engineering prof. gail...

101
20 September 2007 Kaiser: COMS W4156 Fall 2 007 1 COMS W4156: Advanced Software Engineering Prof. Gail Kaiser [email protected] http://york.cs.columbia.edu/clas ses/cs4156/

Upload: nancy-mcdowell

Post on 14-Dec-2015

214 views

Category:

Documents


1 download

TRANSCRIPT

20 September 2007 Kaiser: COMS W4156 Fall 2007 1

COMS W4156: Advanced Software Engineering

Prof. Gail Kaiser

[email protected]

http://york.cs.columbia.edu/classes/cs4156/

20 September 2007 Kaiser: COMS W4156 Fall 2007 2

Enterprise Java Beans History

• Originated with IBM 1997

• Later adopted by Sun (1.0 1998, 1.1 1999)

• Enhanced under Java community process (2.0 2001, 2.1 2003, 3.0 2006)

• EJB 3.0 is a major departure from earlier versions, but backwards compatible (old code works with 3.0 but probably not vice versa)

20 September 2007 Kaiser: COMS W4156 Fall 2007 3

Goals

• Standard component architecture for building distributed business applications in Java

• Make it easy to write applications: Application developers do not have to understand complex low-level APIs

• Part of the Enterprise-grade Java initiative• Provide interoperability between enterprise

beans and Java Platform Enterprise Edition components as well as non-Java applications

20 September 2007 Kaiser: COMS W4156 Fall 2007 4

Goals

• Follow the Write Once, Run Anywhere philosophy of Java - an enterprise bean can be developed once and then deployed on multiple platforms without recompilation or source code modification

• Define the contracts that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime

• Compatible with other Java APIs• Compatible with CORBA protocols

20 September 2007 Kaiser: COMS W4156 Fall 2007 5

EJB specifications

• EJB is an open specification, like all of the Java EE platform

• Any vendor can develop a runtime environment that complies with the specification – but typically vendors lag a little behind the latest specs release

• EJB frameworks take the form of “application servers”– Application servers usually sit on top of web servers– Embrace 3-tier architectures for distributed business

applications

20 September 2007 Kaiser: COMS W4156 Fall 2007 6

Reprise: 3-Tier Architecturewith Component Services Middleware

Client

Componentservicesmiddleware

Database

Application logic com

ponents

LDA

PD

ocument

Storage

20 September 2007 Kaiser: COMS W4156 Fall 2007 7

Java-Specific 3-Tier Architecture

20 September 2007 Kaiser: COMS W4156 Fall 2007 8

EJB as component model framework

• Standardized interfaces + programming model

• Runtime environment

• Built-in component services (analogous to COM+)

• Meta-data

• Deployment facilities

20 September 2007 Kaiser: COMS W4156 Fall 2007 9

Enterprise Bean

• Body of code having fields and methods to implement business logic that operates on the enterprise’s data

• Instances are created and managed at runtime by a Container

• Client access is mediated by the bean instance’s Container - isolates the bean from direct access by client applications (and other beans)

20 September 2007 Kaiser: COMS W4156 Fall 2007 10

Enterprise Bean• If an enterprise bean uses only the services defined by

the EJB specification, the bean can be deployed in any compliant EJB Container

• Can be included in an assembled application without requiring source code changes or recompilation

• Component services information, such as a transaction and security attributes, are separate from the enterprise bean source code - allows services information to be managed by tools during application assembly and deployment (EJB 3.0 uses annotations)

20 September 2007 Kaiser: COMS W4156 Fall 2007 11

EJB Container

• Hosts and manages an enterprise bean in the same manner that the Java Web Server hosts a servlet or an HTML browser hosts a Java applet

• Manages every aspect of an enterprise bean at runtime, including [remote] access to the bean, security, persistence, transactions, concurrency and access to and pooling of resources (e.g., databases connections as in COM+)

• An enterprise bean cannot function outside of an EJB container

20 September 2007 Kaiser: COMS W4156 Fall 2007 12

EJB Container

20 September 2007 Kaiser: COMS W4156 Fall 2007 13

EJB Container

• When a client application invokes a method on an enterprise bean, the container first intercepts the invocation to ensure component services are applied properly to every operation a client performs on the bean

• The enterprise bean developer can focus on encapsulating business rules, while the container takes care of everything else

20 September 2007 Kaiser: COMS W4156 Fall 2007 14

Container Resource Management

• Containers manage many beans simultaneously • To reduce memory consumption and

processing, containers pool resources and manage the lifecycles of beans very carefully

• When a bean is not being used, a container will place it in a pool to be reused by another client, or possibly evict it from memory and only bring it back when its needed

20 September 2007 Kaiser: COMS W4156 Fall 2007 15

Container Resource Management

• Because client applications don't have direct access to the beans, the client application is completely unaware of the container’s resource management activities

• A bean that is not in use might be evicted from memory on the server, while its reference on the client remains intact

• When the client invokes a method on the reference, the container re-incarnates the bean to service the request

20 September 2007 Kaiser: COMS W4156 Fall 2007 16

Interaction with Container

• The enterprise bean interacts with its container through one of three mechanisms: – Callback methods– The EJBContext interface– Java Naming and Directory Interface (JNDI)

20 September 2007 Kaiser: COMS W4156 Fall 2007 17

Callback Methods

• Every bean implements a subtype of the EnterpriseBean interface, which defines several methods

• Each callback method alerts the bean to a different event in its lifecycle

• The container will invoke these methods to notify the bean when it's about to activate the bean, persist its state to the database, end a transaction, remove the bean from memory, etc.

• The callback methods give the bean a chance to do some housework immediately before or after some event

20 September 2007 Kaiser: COMS W4156 Fall 2007 18

EJBContext

• Every bean obtains an EJBContext object, which is a reference directly to the container

• The EJBContext interface provides methods for interacting with the container so that the bean can request information about its environment like the identity of its client, the status of a transaction, or to obtain references to itself

20 September 2007 Kaiser: COMS W4156 Fall 2007 19

Java Naming and Directory Interface

• JNDI is a standard extension to the Java platform for accessing naming systems like LDAP (Lightweight Directory Access Protocol), file systems, etc.

• provide a unified interface to multiple naming and directory services in the enterprise so that application components can access these services

• Every bean automatically has access to a special naming system called the Environment Naming Context (ENC)

• The ENC is managed by the container and accessed by beans using JNDI

• The JNDI ENC allows a bean to access resources like JDBC connections, other enterprise beans, and properties specific to that bean

20 September 2007 Kaiser: COMS W4156 Fall 2007 20

Bean-Container Contract

• The EJB specification defines a bean-container contract, which includes the callbacks, EJBContext, and JNDI ENC

• As well as a strict set of rules that describe how enterprise beans and their containers will behave at runtime, how security access is checked, how transactions are managed, how persistence is applied, etc.

• The bean-container contract is designed to make enterprise beans portable between EJB containers so that enterprise beans can be developed once, then run in any EJB container

20 September 2007 Kaiser: COMS W4156 Fall 2007 21

Portability

• Portability is central to EJB• Portability ensures that a bean developed

for one container can be migrated to another if another brand offers more performance, features, or savings

• Portability also means that the bean developer's skills can be leveraged across several EJB container brands, providing organizations and developers with better opportunities

20 September 2007 Kaiser: COMS W4156 Fall 2007 22

Business Data and Methods • Entity beans represent persistent business data

stored in one row of a database and add behavior specific to that data (Java Persistence API in EJB 3.0)

• Session beans implement business processes, generally a transient conversation with a client

• Message-driven beans combine features of a session bean and a message listener, allowing a business component to receive messages asynchronously – usually Java Message Service (JMS) messages

20 September 2007 Kaiser: COMS W4156 Fall 2007 23

Business Methods

• Business methods are tasks that a bean performs

• Although entity beans often have task-oriented methods, tasks are more typical of a type of bean called a session bean

• Session beans do not represent persistent data • They represent business processes or agents

that perform a service, like making a reservation at a hotel, e.g., HotelClerk

20 September 2007 Kaiser: COMS W4156 Fall 2007 24

Session Beans

• The business methods defined in a session bean represent processes rather than simple accessors– used to manage the interactions of entity and other session

beans, access resources, and generally perform tasks interactively on behalf of the client

• The session bean acts as an agent in the sense that it performs tasks on behalf of the user, but is not itself persistent in the database and does not represent data in the database

• You don't need information about the HotelClerk, you need the hotel clerk to perform tasks for you

20 September 2007 Kaiser: COMS W4156 Fall 2007 25

Session Beans

• Usually not permanent objects, usually not sharable

• Represents a single client within the application server

• Session beans can be used to organize processing tasks, somewhat analogous to the way each Java class can be used to encapsulate related processing

• The tasks can be distributed on different machines

20 September 2007 Kaiser: COMS W4156 Fall 2007 26

Session Bean

• Updates shared data in an underlying database– Does not represent directly shared data in the

database, although it may access and update such data

• Is relatively short-lived• Is removed when the EJB Container crashes

– The client has to re-establish a new session object to continue computation

20 September 2007 Kaiser: COMS W4156 Fall 2007 27

Session Beans

• Another way session beans can be thought of, is like how browsers and web servers operate

• A web server is located in a particular location, but multiple browsers can connect to it and get it to perform services (such as delivering HTML pages) on their behalf

• Each server performs a specialized unique task (serving for a particular domain)

• The clients can connect to any of a number of servers, depending upon their needs.

20 September 2007 Kaiser: COMS W4156 Fall 2007 28

Session Beans

• In the same way, each session bean may perform a type of task, at a given remote location

• Its clients will be other Java programs (rather than a browser)

• Its clients will connect to it when they need that type of task done

• The tasks will be usually be programmatic and more specific than “give me this HTML page”

20 September 2007 Kaiser: COMS W4156 Fall 2007 29

Session Beans

• An example might be a session bean that performs a specialized calculation that is hidden from the clients

• The clients do not need to know how to do the calculation, but just need to know the results

• The session bean might provide methods for providing the input of the calculation and for getting the result of the calculation

• The client just needs to access the session bean and call its methods

20 September 2007 Kaiser: COMS W4156 Fall 2007 30

Session Beans

• Another example may be when book-keeping needs to be done in a central location

• For instance, a bank's ATM machines may be Java programs that are clients of a session bean running in a central location

• This session bean does the book-keeping tasks of maintaining the balance in the account, reducing the amount for each ATM withdrawal and increasing it for each ATM deposit, etc.

20 September 2007 Kaiser: COMS W4156 Fall 2007 31

Session Beans

• Session beans do not have a primary key

• Unlike entity beans, session beans are not primarily meant to be shared or found later (though they can be, using “handles” – until a container-specific timeout)

20 September 2007 Kaiser: COMS W4156 Fall 2007 32

Example Session Bean Remote Interface

import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface HotelClerk extends EJBObject { public void reserveRoom(Customer cust, RoomInfo ri, Date from, Date to) throws RemoteException;

public RoomInfo availableRooms( Location loc, Date from, Date to) throws RemoteException;

}

20 September 2007 Kaiser: COMS W4156 Fall 2007 33

Stateless vs. Stateful

• There are two basic kinds of session bean: Stateless and Stateful

• Stateless session beans are made up of business methods that behave like procedures: they operate only on the arguments passed to them when they are invoked, they do not maintain business state between method invocations (but can lookup state in database or file)

• Stateless beans are called "stateless" because they are transient, they do not maintain business state between method invocations

20 September 2007 Kaiser: COMS W4156 Fall 2007 34

Stateless Session Beans

• Each invocation of a stateless business method is independent from previous invocations

• Instance variables may contain state specific to the client, but only for the duration of the invocation

• All instances are equivalent – the EJB container can assign a pooled stateless bean instance to any client

• Improves scalability• Only kind of enterprise bean that can implement

a web service

20 September 2007 Kaiser: COMS W4156 Fall 2007 35

Stateless vs. Stateful

• Stateful session beans encapsulate business logic and conversational state specific to a client

• Stateful beans are called "stateful" because they do maintain business state between method invocations

• State held in instance variables, in memory and not persistent

• Mediates between client and other components of the application

20 September 2007 Kaiser: COMS W4156 Fall 2007 36

Stateful Session Beans

• To conserve resources, stateful session beans may be passivated when not in use by the client

• In stateful beans, passivation means the bean's conversational-state is written to a secondary storage (often disk) and the instance is removed from memory

• If the client removes the bean or terminates, the session ends and the state disappears

20 September 2007 Kaiser: COMS W4156 Fall 2007 37

Stateful Session Beans

• The client's reference to the bean is not affected by passivation, it remains alive and usable while the bean is passivated

• When the client invokes a method on a bean that is passivated, the container will activate the bean by instantiating a new instance and populating its conversational-state with the state written to secondary storage

20 September 2007 Kaiser: COMS W4156 Fall 2007 38

Passivate and Activate

• The ejbPassivate and ejbActivate callback methods are invoked on the bean by the container just before the bean is passivated and just after the bean is activated

• When the client invokes a method on a bean that is passivated, the container will activate the bean by instantiating a new instance and populating its conversational-state with the state written to secondary storage

• Passivation means that the bean instance is disassociated with its remote reference so that the container can evict it from memory or reuse it

• A bean might be passivated if it hasn't been used for a while or as a normal operation performed by the container to maximize reuse of resources

20 September 2007 Kaiser: COMS W4156 Fall 2007 39

Accessing Enterprise Beans (EJB = 3.0)

• A client can access a session bean only through the methods defined in the bean’s business interface - all other aspects of the bean (method implementations and deployment settings) are hidden from the client

• Session beans can have more than one business interface

• Need to decide the type of client access allowed by the enterprise beans: remote, local or web service

• [Web services not discussed today]

20 September 2007 Kaiser: COMS W4156 Fall 2007 40

Remote Clients

• A remote client of an enterprise bean can run on a different machine and a different Java virtual machine (JVM) than the enterprise bean it accesses

• The client can be a web component, an application client, or another enterprise bean

• The location of the enterprise bean is transparent• The remote interface defines the business and life cycle

methods that are specific to the bean• For example, the remote interface of a bean named BankAccountBean might have business methods named deposit and credit

20 September 2007 Kaiser: COMS W4156 Fall 2007 41

Remote Clients

• Decorate the business interface of the enterprise bean with the @Remote annotation:@Remote public interface InterfaceName { ... }

• Decorate the bean class with @Remote, specifying the business interface or interfaces:@Remote(InterfaceName.class) public class BeanName implements InterfaceName { ... }

20 September 2007 Kaiser: COMS W4156 Fall 2007 42

Local Clients

• Client must run in the same JVM as the enterprise bean it accesses

• Can be a web component or another enterprise bean

• The location of the enterprise bean it accesses is not transparent

• The local business interface defines the bean’s business and life cycle methods

20 September 2007 Kaiser: COMS W4156 Fall 2007 43

Local Clients

• If the bean’s business interface is not decorated with @Local or @Remote, and the bean class does not specify the interface using @Local or @Remote, the business interface is by default a local interface

• To build an enterprise bean that allows only local access, optionally annotate the business interface of the enterprise bean as a @Local interface@Local public interface InterfaceName { ... }

• Specify the interface by decorating the bean class with @Local and specify the interface name@Local(InterfaceName.class) public class BeanName implements InterfaceName { ... }

20 September 2007 Kaiser: COMS W4156 Fall 2007 44

Method Parameters and Return Values

• The parameters of remote calls are more isolated than those of local calls - the client and bean operate on different copies of a parameter object

• If the client changes the value of the object, the value of the copy in the bean does not change

• In a local call, both the client and the bean can modify the same parameter object – but should not rely on this side effect of local calls

• Because remote calls are likely to be slower than local calls, the parameters in remote methods should be relatively coarse-grained

20 September 2007 Kaiser: COMS W4156 Fall 2007 45

Deciding on Local vs. Remote: Coupling

• Tightly coupled beans depend on one another

• For example, if a session bean that processes sales orders calls a session bean that emails a confirmation message to the customer, these beans are tightly coupled

• Tightly coupled beans are good candidates for local access

• Because they fit together as a logical unit, they typically call each other often and would benefit from the increased performance that is possible with local access

20 September 2007 Kaiser: COMS W4156 Fall 2007 46

Deciding on Local vs. Remote: Type of Client

• If an enterprise bean is accessed by application clients, then it should allow remote access

• In a production environment, these clients almost always run on different machines than the Application Server

• If an enterprise bean’s clients are web components or other enterprise beans, then the type of access depends on how you want to distribute your components

20 September 2007 Kaiser: COMS W4156 Fall 2007 47

Deciding on Local vs. Remote: Component Distribution

• Java EE applications are scalable because their server-side components can be distributed across multiple machines

• In a distributed application, the web components may run on a different server than do the enterprise beans they access

• Then the enterprise beans should allow remote access

20 September 2007 Kaiser: COMS W4156 Fall 2007 48

Deciding on Local vs. Remote: Performance

• Due to factors such as network latency, remote calls may be slower than local calls.

• On the other hand, if you distribute components among different servers, you may improve the application’s overall performance

• Actual performance can vary in different operational environments

20 September 2007 Kaiser: COMS W4156 Fall 2007 49

Deciding on Local vs. Remote

• If you aren’t sure which type of access an enterprise bean should have, choose remote access, which gives more flexibility

• In the future you can distribute your components to accommodate the growing demands on your application

• Although it is uncommon, it is possible for an enterprise bean to allow both remote and local access through different interfaces - the same business interface cannot be both a local and remote business interface

20 September 2007 Kaiser: COMS W4156 Fall 2007 50

Accessing Enterprise Beans (EJB <3.0)

• An enterprise bean developer provides two interfaces, remote and home, plus the actual bean implementation class

• The client uses these public interfaces to create, update, manipulate, interact with and remove beans from the EJB server

• The implementation class (or bean class) is instantiated at runtime and becomes a distributed object

20 September 2007 Kaiser: COMS W4156 Fall 2007 51

Remote and Home Interfaces

• The home interface represents the life-cycle methods of the component (create, destroy, find), extending javax.ejb.EJBHome

• The remote interface represents the business methods of the bean, extending javax.ejb.EJBObject

• These EJB interface types define a standard set of utility methods and provide common base types for all remote and home interfaces

20 September 2007 Kaiser: COMS W4156 Fall 2007 52

Remote and Home Interfaces

20 September 2007 Kaiser: COMS W4156 Fall 2007 53

Client Access

• Clients use JNDI to get a home interface, then used to create or find a bean

• The create and find methods return a reference to the remote interface

• The remote interface defines the business methods like – accessor and mutator methods, e.g., for changing a

customer's name– business methods that perform tasks, e.g., using the

HotelClerk bean to reserve a room at a hotel

20 September 2007 Kaiser: COMS W4156 Fall 2007 54

Client Access Example

// ... obtain a reference that

// implements the home interface

CustomerHome home = …

// Use the home interface to create a

// new instance of the Customer bean

Customer customer = home.create(customerID);

// using a business method on the Customer customer.setName(someName);

20 September 2007 Kaiser: COMS W4156 Fall 2007 55

Remote Interface Example

import javax.ejb.EJBObject; import java.rmi.RemoteException; public interface Customer extends EJBObject { public Name getName() throws RemoteException;

public void setName(Name name) throws …; public Address getAddress() throws …; public void setAddress(Address address) …; }

20 September 2007 Kaiser: COMS W4156 Fall 2007 56

Life Cycle Methods

• All beans have a home interface• The home interface provides life cycle methods

for creating, destroying, and locating beans• These life cycle behaviors are separated out of

the remote interface because they represent behaviors that are not specific to a single bean class

• The home interface implementation is (usually) automatically provided by the EJB container

20 September 2007 Kaiser: COMS W4156 Fall 2007 57

Example

import javax.ejb.EJBHome; import …;public interface CustomerHome extends EJBHome { public Customer create(Integer customerNumber) throws RemoteException, CreateException;

public Customer findByPrimaryKey(Integer customerNumber) throws RemoteException, FinderException;

public Enumeration findByZipCode(int zipCode) throws …; }

20 September 2007 Kaiser: COMS W4156 Fall 2007 58

Example Discussion

• The create method is used to create a new entity, which will result in a new record in the database

• The number and datatype of the arguments of each create are left up to the bean developer, but the return type must be the remote interface datatype

• The findByPrimaryKey and findByZipCode methods are used to locate specific instances of the Customer bean

• A home may have many create and find methods

20 September 2007 Kaiser: COMS W4156 Fall 2007 59

Using Remote and Home Interfaces

• The remote and home interfaces are used by applications to access enterprise beans at runtime

• The home interface allows the application to create or locate the bean, while the remote interface allows the application to invoke a bean's business methods

20 September 2007 Kaiser: COMS W4156 Fall 2007 60

Enterprise Beans as Distributed Objects

• The remote and home interfaces are types of Java RMI Remote interfaces

• The java.rmi.Remote interface is used by distributed objects to represent the bean in a different address space (process or machine)

• An enterprise bean class is instantiated and lives in its container but can be accessed by client applications that live in other address spaces, using skeletons and stubs

20 September 2007 Kaiser: COMS W4156 Fall 2007 61

Stubs and Skeletons

• To make an object instance in one address space available in another is accomplished using a little trick involving network sockets

• To make the trick work, wrap the instance in a special object called a skeleton that has a network connection to another special object called a stub

20 September 2007 Kaiser: COMS W4156 Fall 2007 62

Stubs and Skeletons

20 September 2007 Kaiser: COMS W4156 Fall 2007 63

How this works• The stub implements the remote interface so it looks like a business

object• But the stub doesn't contain business logic, it holds a network

socket connection to the skeleton• Every time a business method is invoked on the stub's remote

interface, the stub sends a network message to the skeleton telling it which method was invoked

• When the skeleton receives a network message from the stub, it identifies the method invoked and the arguments, and then invokes the corresponding method on the actual instance

• The instance executes the business method and returns the result to the skeleton, which sends it to the stub

• The stub returns the result to the application that invoked its remote interface method

20 September 2007 Kaiser: COMS W4156 Fall 2007 64

Implementing the Skeleton

• The skeleton for the remote and home interfaces are implemented by the container, not the bean class

• This is to ensure that every method invoked on these reference types by a client application are first handled by the container and then delegated to the bean instance

• The container intercepts so that it can apply persistence, transactions, and access control automatically

20 September 2007 Kaiser: COMS W4156 Fall 2007 65

Network Communication

• Distributed object protocols define the format of network messages sent between address spaces

• Most EJB servers support either the Java Remote Method Protocol (JRMP) or CORBA's Internet Inter-ORB Protocol (IIOP)

• Which is hidden under a specialized version of the Java RMI API

• The bean and application programmer only see the bean class and its remote interface, the details of the network communication are hidden

20 September 2007 Kaiser: COMS W4156 Fall 2007 66

Java Message Service (JMS)

• A messaging standard that allows Java EE application components to create, send, receive, and read messages

• Enables distributed communication that is loosely coupled, reliable, and asynchronous (analogous to MSMQ and COM+ Events)

• ???

20 September 2007 Kaiser: COMS W4156 Fall 2007 67

Message-Driven Beans

• Message-driven beans are not accessed by clients through interfaces

• Instead, a client sends messages to the message destination for which the message-driven bean class is the MessageListener

• Destination assigned during deployment, the EJB container can assign a message to any corresponding bean instance from a pool

• A single message-driven bean can process messages from multiple clients

20 September 2007 Kaiser: COMS W4156 Fall 2007 68

Message-Driven Beans

• Execute upon receipt of a single client message• Are invoked asynchronously• Relatively short-lived• Do not represent directly shared data in the

database, but they can access and update this data

• Can hold certain state across messages, such as a JMS API connection, an open database connection, or an object reference

20 September 2007 Kaiser: COMS W4156 Fall 2007 69

Processing Messages

• When a message arrives, the container calls the message-driven bean’s onMessage method to process the message

• This method normally casts the message to one of five JMS message types and handles it in accordance with the application’s business logic ???

• Can call helper methods, or invoke a session bean to process the information in the message or to store it in a database

• A message can be delivered to a message-driven bean within a transaction context, so all operations within the onMessage method are part of a single transaction

• If message processing is rolled back, the message will be redelivered

20 September 2007 Kaiser: COMS W4156 Fall 2007 70

Business Data• An entity bean provides an object view of data in the

database (same concept supplied in EJB 3.0 by Java Persistence API)

• Allows shared access from multiple users• Can be long-lived (as long as data in the database)• Persistent

– The entity, its primary key, and its remote reference survive a crash of the EJB Container

– If the state of an entity was being updated by a transaction at the time the container crashed, the entity’s state is automatically reset to the state of the last committed transaction

20 September 2007 Kaiser: COMS W4156 Fall 2007 71

Entity Beans

• Permanent: – Standard Java objects come into existence

when created in a program, and are lost when the program terminates

– But an entity bean exists until it is deleted– An application program can create an entity

bean, then be stopped and restarted, and again find the entity bean it was working with - and continue using the same entity bean

20 September 2007 Kaiser: COMS W4156 Fall 2007 72

Entity Beans

• Network based: 

– Standard Java objects are used only by one application program

– But an entity bean can be used by any program on the network

– The program just needs to be able to find the entity bean, in order to use it

20 September 2007 Kaiser: COMS W4156 Fall 2007 73

Entity Beans

• Executed remotely: – Methods of an entity bean usually run on

a “server” machine– When you call an entity bean's method,

your program's thread stops executing and control passes over to the server

– When the method returns from the server, the local thread resumes executing

20 September 2007 Kaiser: COMS W4156 Fall 2007 74

Entity Beans

• Identified by a primary key: – Entity Beans must have a primary key– Each entity bean is uniquely identified by its

primary key (in some underlying database)– For example, an “employee” entity bean may

have Social Security numbers as primary keys– You can only use entity beans when your

objects have a unique identifier field, or when you can add such a field (or set of fields)

20 September 2007 Kaiser: COMS W4156 Fall 2007 75

Example Entity Beanimport javax.ejb.EntityBean; public class CustomerBean implements EntityBean { Address myAddress; Name myName; CreditCard myCreditCard; public Name getName() { return myName; } public void setName(Name name) { myName = name; }

public Address getAddress() { return myAddress; }

public void setAddress(Address address) { myAddress = address; } ... }

20 September 2007 Kaiser: COMS W4156 Fall 2007 76

Entity Bean and the DB

• An Entity Bean class represents a database table or a view upon it

• An Entity Bean instance (object) of the same class maps to a row in that table/view

• Access and modification to the Entity Bean data are backed up by corresponding operation on the actual data source

20 September 2007 Kaiser: COMS W4156 Fall 2007 77

Entity Bean Persistence

• There are two types of entity bean: Container-Managed Persistence (CMP) and Bean-Managed Persistence (BMP)

• With CMP, the container manages the persistence of the entity bean– Vendor tools are used to map the entity

fields to the database and absolutely no database access code is written in the bean class

20 September 2007 Kaiser: COMS W4156 Fall 2007 78

Persistence

• With BMP, the entity bean contains database access code (usually JDBC) and is responsible for reading and writing its own state to the database– BMP entities have a lot of help with this since

the container will alert the bean as to when it's necessary to make an update or read its state from the database

– The container can also handle any locking or transactions, so that the database maintains integrity

20 September 2007 Kaiser: COMS W4156 Fall 2007 79

Container-Managed Persistence

• All the logic for synchronizing the bean's state with the database is handled automatically by the container

• A given class could be mapped to any database provided that the container-managed fields have corresponding types (columns in RDBMS) in the database either directly or through Object-Relational mapping

20 September 2007 Kaiser: COMS W4156 Fall 2007 80

Container-Managed Persistence• Container-managed fields can be any primitive

data types or serializable type• A given class can then be mapped to any

relational database• Once the bean's fields are mapped to the

database, and the bean is deployed, the container will manage creating records, loading records, updating records, and deleting records in response to methods invoked on the bean's remote and home interfaces

20 September 2007 Kaiser: COMS W4156 Fall 2007 81

Instance Fields

• Not all fields in a bean are automatically container-managed fields, some may be just plain instance fields for the bean's transient use

• A bean developer distinguishes container-managed fields from plain instance fields by indicating which fields are container-managed in the deployment descriptor*

• *Note: In EJB 3.0, the preferred approach is annotations directly in the source code

20 September 2007 Kaiser: COMS W4156 Fall 2007 82

Primary Key

• A subset (one or more) of the container-managed fields must also be identified as the bean's primary key

• The primary key is the index or pointer to a unique record(s) in the database that makes up the state of the bean

• Used to locate the bean’s data in the database

20 September 2007 Kaiser: COMS W4156 Fall 2007 83

Primary Key

• Primitive single field primary keys are represented as their corresponding object wrappers (e.g., a primitive int in the bean class will manifest itself as the java.lang.Integer type)

• Primary keys that are make up of several fields, called compound primary keys, will be represented by a special class defined by the bean developer

20 September 2007 Kaiser: COMS W4156 Fall 2007 84

Create

• When the create method is invoked, the container delegates the create method call to the bean instance's matching ejbCreate method

• ejbCreate callback methods are used to initialize the instance state before a record is inserted into the database

• When the ejbCreate method is finished, the container reads the container-managed fields and inserts a new record into the database indexed by the primary key

20 September 2007 Kaiser: COMS W4156 Fall 2007 85

PostCreate

• An entity bean doesn't technically exist until after its data has been inserted into the database, which occurs during the ejbCreate method

• Once the data has been inserted, the entity bean exists and can access its own primary key and remote references

• The ejbPostCreate callback method allows the bean to do any post-create processing before it begins serving client requests

20 September 2007 Kaiser: COMS W4156 Fall 2007 86

Remove

• ejbRemove• Another callback method, which cleans up

before deletion

20 September 2007 Kaiser: COMS W4156 Fall 2007 87

Finder Methods

• The methods in the home interface that begin with “find” are called finder methods

• Used to query the EJB server for specific entity beans, based on the name of the method and arguments passed

• In EJB 1.x there was no standard query language defined for find methods, so each vendor implemented the find method differently (until EJB 2.0)

20 September 2007 Kaiser: COMS W4156 Fall 2007 88

Finder Methods

• In CMP entity beans, the finder methods are not implemented with matching methods in the bean class - containers implement them when the bean is deployed in a vendor-specific manner

• The deployer uses vendor-specific tools to tell the container how a particular find method should behave

20 September 2007 Kaiser: COMS W4156 Fall 2007 89

Single vs. Multiple

• There are two basic kinds of find methods: single-entity and multi-entity find methods

• Single-entity find methods return a remote reference to the one specific entity bean that matches the find request– If no entity beans are found, the method

throws an ObjectNotFoundException– Every entity bean must define the single-

entity find method with the method name findByPrimaryKey, which takes the bean's primary key type as an argument

20 September 2007 Kaiser: COMS W4156 Fall 2007 90

Single vs. Multiple

• The multi-entity find methods return a collection (Enumeration or Collection type) of entities that match the find request (e.g., findByZipCode)

• If no entities are found, the multi-entity find returns an empty collection

20 September 2007 Kaiser: COMS W4156 Fall 2007 91

Bean-Managed Persistence

• A BMP enterprise bean manages synchronizing its state with the database

• Uses a database API (e.g., JDBC) to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the transactions for the bean automatically

• Gives the bean developer the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container

• Must also implement own finder operations

20 September 2007 Kaiser: COMS W4156 Fall 2007 92

BMP Load and Store

• The ejbLoad and ejbStore methods contain code to read the bean's data from the database and to write changes to the database

• ejbLoad usually invoked by the container at the beginning of a transaction, just before the container delegates a business method to the bean

• ejbStore invoked by the container at the end of a transaction, just before the container attempts to commit all changes to the database

20 September 2007 Kaiser: COMS W4156 Fall 2007 93

Transactions

• Container-managed (automatic) …• … or Bean-managed• Container-managed transactions

– Lets you specify relationships among methods that make up a single transaction so that all methods in one transaction are treated as a single unit

– Otherwise, auto-commit defaults such that other applications viewing data will updated data after each write (unless using Transaction API to group)

– Transactional attributes of Beans set administratively– {Required, RequiresNew, Mandatory, NotSupported, Supports, Never }

20 September 2007 Kaiser: COMS W4156 Fall 2007 94

Transactions

• NotSupported: Transactions are not supported in this method

• Supports: This method can be called as part of a transaction or independently

• Required: This method needs to be part of a transaction; if called outside a transaction, a new transaction is automatically started

• RequiresNew: When this method is called, a new transaction should be started

• Mandatory: This method can be called only as part of a transaction

• Never: This method cannot be called as part of a transaction

20 September 2007 Kaiser: COMS W4156 Fall 2007 95

Transaction Callbacks• public void afterBegin() throws

javax.ejb.EJBException,java.rmi.RemoteException { }

• public void beforeCompletion() throws javax.ejb.EJBException,java.rmi.RemoteException {  }

• public void afterCompletion() throws javax.ejb.EJBException,java.rmi.RemoteException { }

20 September 2007 Kaiser: COMS W4156 Fall 2007 96

EJB Security

• Lets you configure an enterprise bean so that system resources are accessed only by authorized users

• Handled in the deployment descriptor or annotations

• User may have one or more “roles”

• Only roles have access rights, not users

• Methods allowed only for particular roles

20 September 2007 Kaiser: COMS W4156 Fall 2007 97

EJBs within Java EE

• Java EE includes many other specifications• Servlets: main engines for accepting and

dispatching Web-based server-side computing• JSP – Java response to ASP for server-side

processing of dynamic WWW pages – a mix of HTML, scripting, and Java snippet– Used for presentation– Compiled on the fly into servlets

• Break down the middle tier in different “slices”

20 September 2007 Kaiser: COMS W4156 Fall 2007 98

EJBs within Java EE

Client

Database Back-end tier

Front-end tier

LDAPDatabase

JSP - PresentationServlets

EJB container

Middle tierJava EEApp. Server

20 September 2007 Kaiser: COMS W4156 Fall 2007 99

Example: Auction House

• Entity Beans (aka Java Persistence Entities) can be used to map state of the Auction into a DB– Items, Bids, Payments, etc.

• Session Beans can be used to represent the interaction with a Customer

• Message beans can be used to notify the Customer of competing bids, winning their bid, etc.

• Entry point could be a JSP (for human Customers) or a servlet (for automated Customers)

20 September 2007 Kaiser: COMS W4156 Fall 2007 100

Upcoming Deadlines

• Project concept due September 25th • Individual development assignment #3 due

October 2nd • Revised project concept due October 9th – first

iteration begins• First iteration plan due October 16th

20 September 2007 Kaiser: COMS W4156 Fall 2007 101

COMS W4156: Advanced Software Engineering

Prof. Gail Kaiser

[email protected]

http://york.cs.columbia.edu/classes/cs4156/