Entity Beans

April 3, 2008 at 12:33 pm (EJB, Unit 2) ()

Entity Beans

  • These are long-lived; they exist across client sessions, are shared by multiple clients, and remain alive even after a restart of the server or other failure.
  • Typically, an Entity EJB object represents a set of data in persistent storage.

 

The EntityBean Interface

public interface javax.ejb.EntityBean

{

public abstract void ejbActivate();

public abstract void ejbLoad();

public abstract void ejbPassivate();

public abstract void ejbRemove();

public abstract void ejbStore();

public abstract void setEntityContext(EntityContext ctx);

public abstract void unsetEntityContext();

}

 

ejbActivate() and ejbPassivate()

  • These methods analogous to the methods of the same name in the SessionBean Interface.
  • ejbPassivate() is called before an Entity object is swapped out and ejbActivate() is called after the Entity Object is swapped in.

 

ejbLoad() and ejbStore()

  • These operations allow the Entity bean to synchronize its state with an underlying database.
  • Under bean managed persistence the developer has to write the coding in these methods.
  • Under container managed persistence no coding is needed for these methods.

 

setEntityContext() and unsetEntityContext()

  • setEntityContext() passes an object that inherits from EJBContext() to the EJB instance.

     

    public interface javax.ejb.EntityContext extends javax.ejb.EJBContext

    {

    public abstract EJBObject getEJBObject();

    public abstract Object getPrimaryKey();

    }

     

    • The getEJBObject() method in this interface is analogous to the method of the same name in the SessionContext interface.
    • The getPrimaryKey() method returns primary key for this object.
    • In the context of entity EJBs, a primary key is an object of some user-defined type that can be used to look up a reference to a particular Entity EJB.
  • Because Entity EJBs can exist across many client invocations, the Entity Bean interface includes an unsetEntityContext() method that allows the bean to discard its previous context when it is destroyed.

 

ejbRemove()

  • The container invokes the ejbRemove() method when a client has called the remove() method of the bean’s home interface.

 

ejbFindByPrimaryKey()

  • This is implemented only if using bean-managed persistence; in container-managed persistence, the container will generate automatically.
  • The container invokes this method when a client invokes the findByPrimaryKey() method on an EJB’s home interface with a particular primary key.
  • This key is passed to the container, which uses it to look up the object and return a reference to its remote interface to the client.

 

Bean-Managed and Container-Managed Persistence

  • Entity beans are intrinsically tied to an underlying database representation.
  • The internal state of an active Entity EJB should always be synchronized with its underlying data after a transaction concludes.
  • The EJB specification permits two approaches to maintaining this synchronization:
    • Bean-Managed persistence
    • Container-Managed persistence
  • In bean-managed persistence, the author of the bean must write necessary database calls to send the object out to persistent storage and read it back in again.
    • The container calls ejbLoad() to notify the object that it should load its state in from a database; so, here the developer has to write the code to read the state from the database.
    • Similarly, the ejbStore() notifies the object that it should write its state out to the database; the developer has to write the code to write the state in the database.
  • In container-managed persistence, the developer has to do anything to synchronize with the database.
    • At runtime, container will invoke ejbLoad() and ejbStore(), but the developer need not provide any implementations to these methods.

 

Reentrant and Non-reentrant Entity Beans

  • By default, Entity EJBs are non reentrant.
  • That is, if a call is being processed and another call to the same object comes in with the same transaction context, the program will throw a RemoteException and the call will not be allowed.
  • It is possible to specify in a deployment descriptor that an Entity EJB is reentrant – that is, it will accept more than one call in the same transaction context.
  • The developer might choose this approach so as to allow a remote object invoked by a client to perform callbacks to the client.
  • If possible, always avoid reentrant entity beans.

Permalink Leave a Comment

A High Level View of an EJB Conversation

April 3, 2008 at 12:30 pm (EJB, Unit 2) ()

A High Level View of an EJB Conversation

  • In the EJB architecture, the client undertakes the following tasks:
    • Finding the bean
    • Getting access to a bean
    • Calling the bean’s methods
    • Getting rid of the bean

 

  • Finding the bean
    • EJB specification mentions two ways in which a client can find a bean
      • Using the Java Naming and Directory Interface
      • Using the CORBA’s Common Object Service (COS)
    • JNDI API provides a uniform interface to naming and directory services.
    • A naming service is a service that associates a Symbolic Name with an object
    • Domain Name Service is a commonly used naming service that is used to transfer symbolic machine names into numeric IP addresses.
    • Previous model of DNS, needed to maintain a file containing a list of symbolic host names along with the numeric IP addresses that they should resolve to.
    • Problems in this approach:
      • If the /etc/hosts/file developed errors, couldn’t resolve symbolic names.
      • Needed to maintain the change of addresses when new machines were added.
      • If a machine did not appear in the /etc/hosts file, need to know its numeric IP address to connect to it.
    • Using DNS approach allows you to avoid many of these annoyances. It works as follows:
      • A client makes a query to a DNS server
      • If the DNS server knows how to resolve the address, it returns the address.
      • If the DNS server does not know how to resolve the address, it provides the query to another DNS server
      • Once the server is able to resolve the name, it returns the address to the client. Typically, it also caches the result so that, if the request is made again, it can be handled immediately.
    • JNDI provides a uniform interface to naming services.
    • JNDI client uses the Server’s SPI (Server Provider Interface) to access its services.
    • A Java client can use JNDI to lookup an EJB component.
    • The JNDI call returns a reference to an object implementing the EJB component’s “home” interface, which can then be used to gain access to the EJB object itself.
    • The other way to find an EJB component is to use CORBA’s Common Object Services (COS) naming service.
    • COS refers to a group of Services, including naming, that is provided as part of the CORBA services specification.
    • In addition to suing COS naming directly, can make use it via JNDI.

 

  • Getting access to a bean
    • The result of the naming lookup is a reference to an object implementing the EJB components home interface
    • A client uses the home interface to look up existing EJB instances, or to create new ones.
    • This lookup result in a reference to an object that implements the EJB object’s remote interface.
    • The client uses the remote interface to interact with the EJB objects on the server.

 

  • Calling the bean’s methods
    • After the client has a reference to an object implementing the object’s remote interface, it can then invoke the methods that the EJB object makes public in the remote interface.

     

  • Getting rid of the bean
    • When the client has finished with an EJB object, it can call the remove() method on the home interface or on the object’s remote interface.
    • Usually remove() is called on a stateful session bean when it is no longer needed, so that the container can discard it and use the space for other beans.
    • remove() method on the stateless bean can be invoked, but generally has no effect; the server simply returns the instance to a pool.
    • remove() on entity beans, would remove the underlying object from persistent storage.

      (Ex: when the customer bean is removed, the data will be deleted from the underlying database.)

    • Clients can interact with EJB either through CORBA or through RMI.

Permalink Leave a Comment

Building and Deploying EJBs

April 3, 2008 at 12:25 pm (EJB, Unit 2) ()

Building and Deploying EJBs

Writing the EJB:

  • EJB must provide three required classes:
    • EJB implementation Class
    • Home Interface
    • Remote Interface
  • Each EJB must provided with a deployment descriptor
  • The deployment descriptor is serialized instance of a Java class that contains information about how to deploy the bean.
  • Two flavors of deployment descriptors:
    • Session Descriptors – apply to Session EJBs
    • Entity Descriptors – apply to Entity EJBs
  • A Deployment Descriptor contains information such as the following:
    • The name of the EJB Class
    • The name of the EJB Home Interface
    • The name of the EJB Remote Interface
    • ACLs of entities authorized to use each class or method.
    • For Entity Beans, a list of container – managed fields.
    • For Session Beans, a value denoting whether the bean is stateful or stateless.
  • Properties File may be generated, which contains environment properties that will be activated during runtime.
  • Manifest File is needed to create the ejb-jar file, which is the medium used to distribute EJBs.

    Name : <filename>

    Enterprise-Bean:True

 

Deploying the EJBs:

  • At the deployment time, the EJB container must read the ejb-jar file, create implementations for the home and remote interfaces.
  • Reads the deployment-descriptor and ensures that the bean has what it wants and ad the bean’s property settings to the environment so that they’re available to the bean at runtime.

 

Connecting to the EJB

  • The client can use either RMI or CORBA to connect to the EJB
  • The client looks up the EJB’s home interface using a naming service (JNDI or COS)
  • Invokes a find() or create() method on the home interface to get a reference to an EJB object.
  • And then uses the EJB object as if it were an ordinary object.

 

Permalink Leave a Comment

Roles in EJB

April 3, 2008 at 12:06 pm (EJB, Unit 2) ()

Roles in EJB

  • EJB specification gives a clear description of each of these roles and their associated responsibilities.

a) Enterprise Bean Provider

  • It is the person or group that writes and packages EJBs.
  • It might be a third-party vendor of EJB components, or it might be an information systems programmer who writes EJBs to implement their company’s business logic.
  • Because the container must provide transaction and network communication support, the enterprise bean provider does not need to be an expert at low-level system programming, networking or transaction processing.
  • The end product is an ejb-jar file, which contains the Enterprise bean, its supporting classes, and information that describes how to deploy the bean.

 

b) Deployer

  • The deployer takes an ejb-jar file and installs it into an EJB container.
  • The deployer’s task begins with the receipt of an ejb-jar file, and ends with the installation of the ejb-jar file in the container.
  • This task is typically handled by the System Administrator in MIS world.

 

c) Application Assembler

  • An application assembler builds applications using EJBs classes.
  • An MIS programmer may purchase a prepackaged set of EJBs that implement an accounting system.
  • Then the programmer might use tools to customize the beans.
  • The application assembler might also need to provide a user-interface client program.
  • This role is roughly analogous to that of a Systems Integrator in the MIS world.

 

d) EJB Server Provider

  • An EJB Server Provider provides a server that can contain EJB containers.
  • The EJB 1.0 specification does not describe the interface between the server and the container, so the EJB server provider and the EJB container provider will likely be one and the same for any given product.
  • The diagram shows the relationships among the EJB server, the EJB container, and the EJB bean.
  • An EJB server provides services to an EJB container and an EJB container provides services to an Enterprise Java Bean.
  • The role of the EJB server provider is similar to that of a database system vendor.

EJB Provider

 

e) EJB Container Provider

  • An EJB container is the world in which an EJB bean lives.
  • The container services requests from the EJB, forwards requests from the client to the EJB, and interacts with the EJB server.
  • The container provider must provide transaction support, security and persistence to beans.
  • It is also responsible for running the beans and for ensuring that the beans are protected from the outside world.

 

f) System Administrator

  • System Administrators are responsible for the day-to-day operation of the EJB server.
  • Their responsibilities include keeping security information up-to-date and monitoring the performance of the server.

Permalink Leave a Comment

Session Beans

April 3, 2008 at 12:01 pm (EJB, Unit 2) ()

Session Beans

  • These are generally tied to the lifetime of a given client session.
  • They are relatively short-lived.
  • The stateful session objects are created in response to a single client’s request, communicate exclusively with a single client and die when the client no longer needs them.
  • A session bean is required to implement the javax.ejb.SessionBean interface.

     

    public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean

    {

    public abstract void ejbActivate();

    public abstract void ejbPassivate();

    public abstract void ejbRemove();

    public abstract void setSessionContext(SessionContext ctx);

    }

  • Al of the methods declared in this interface are callback methods; that is they are invoked by the container to notify the Session EJB that some event has occurred.

 

ejbPassivate()

  • Container calls this method to swap the EJB class out to “semi-persistent” storage.
  • The storage is “semi-persistent” because Session EJBs do not carry the same sort of guarantee of long life as Entity EJBs do.
  • If the EJB container crashes or restarts, the session beans that existed before the crash or restart are destroyed.
  • Session bean also have an associated timeout value; after the timeout expires, they are destroyed.
  • If none of these events happens the session bean can be sapped back in at some later time.

 

ejbActivate()

  • The ejbActivate() method is essentially the inverse of the ejbPassivate() call.
  • The container calls this method after a session bean’s state has been restored from “semi-persistent” storage, but before it becomes available to the outside world.
  • A bean can use the ejbActivate() call to restore any resources that is closed before being passivated.

 

ejbRemove()

  • This callback method in invoked by the container as a result of a client calling the remove() method of a bean’s home or remote interface.
  • The client’s invocation of the remove() method notifies the container that this particular session bean instance should be destroyed.

 

setSessionContext(SessionContext ctx)

  • This method is called at the very beginning of a session bean’s life.
  • The container passes the session bean an object that implements the SessionContext interface.
  • The bean stores this object in an object variable, and can then use the SessionContext to interact with container-provided services such as security and transaction management.

 

The EJBContext Interface

  • The SessionContext interface inherits from the EJBContext interface.
  • The EJBContext interface is the parent interface of both the SessionContext and EntityContext interfaces.

    public interface javax.ejb.EJBContext

    {

    public abstract Identity getCallerIdentity();

    public abstract EJBHome getEJBHome();

    public abstract Properties getEnvironment();

    public abstract boolean getRollbackOnly();

    public abstract UserTransaction getUserTransaction();

    public abstract boolean isCallerInRole(Identity role);

    public abstract void setRollbackOnly();

    }

 

getCallerIdentity()

  • This method is used to get a java.security.Identity object that represents the identity of the client.
  • It can be used in concert with isCallerInRole() to allow the EJB object to perform authorization checks before performing an operation.

 

getEJBHome()

  • This method is used to get a reference to its own home interface.
  • This interface can be used to create or find other instances of the bean class, or to do several other things.

 

getEnvironment()

  • This call returns the EJB’s environment properties.
  • These properties can be adjusted at deployment time.

 

getRollbackOnly()

  • EJB supports distributed transactions.
  • If any of the players in a distributed transaction cannot continue for some reason, it can mark the transaction as “rollback only”.
  • A “rollback only” transaction can never complete; it must be rolled back.
  • A bean can use this to check the status of a transaction before attempting to participate in it.

 

getUserTransaction()

  • In TX_BEAN_MANAGED transaction type, the bean is responsible for beginning, committing and possibly rolling back its own transactions.
  • If a bean has a transaction attribute of TX_BEAN_MANAGED, it can use getUserTransaction() to gain access to the transaction.

 

The UserTransaction Interface

public interface javax.jtx.UserTransaction

{ public final static int STATUS_ACTIVE;

public final static int STATUS_COMMITTED;

public final static int STATUS_COMMITTING;

public final static int STATUS_MARKED_ROLLBACK;

public final static int STATUS_NO_TRANSACTION;

public final static int STATUS_PREPARING;

public final static int STATUS_PREPARED;

public final static int STATUS_ROLLEDBACK;

public final static int STATUS_ROLLING_BACK;

public final static int STATUS_UNKNOWN;

public abstract void begin();

public abstract void commit();

public abstract int getStatus();

public abstract void rollback();

public abstract void setRollbackOnly();

public abstract void setTransactionTimeout(int seconds);

}

  • This provides the classic “begin”, “commit”, and “rollback” operations
  • getStatus() operation, which allows the caller to see the status of the transaction.
  • Also allows the caller to set a transaction timeout, enabling the caller to set some upper bound on the execution time of the transaction.

 

isCallerInRole()

  • This boolean method can be used to test whether the caller has assumed a given role.
  • An EJB developer might specify several different roles that can be played by the users of the class.

 

setRollbackOnly()

  • Calling this method sets the current transaction to “rollback only”.

 

The SessionContext Interface

 

public interface javax.ejb.SessionContext extends javax.ejb.EJBContext

{

public abstract EJBObject getEJBObject();

}

 

  • This contains only one method namely getEJBObject().
  • This method returns a reference to an EJBObject.
  • This remote reference to an object implements the bean’s remote interface, and can be used if the bean wants to pass a reference to itself to some other entity.
  • EJB Container is responsible for creating objects that implement the remote interface; these objects act as proxies, forwarding the business method calls to the object.

 

  • Session bean’s home interface provides one or more “create” methods.
  • “create” methods are invoked by clients to create new instances of a particular EJB object.
  • When a client invokes a create() method on the bean’s home interface, the container creates an object of the appropriate type, calls its setSessionContext() method, and then calls a method in EJB class called ejbCreate().

 

The Rules for an ejbCreate() method in Session Beans are as follows:

  • The method must have a void return type. The container will pass the remote interface back to the client.
  • The number and type of arguments to the ejbCreate() method must exactly match the number and type of arguments in the corresponding create() method declared in the home interface.

 

The following steps are involved in the creation of a new Session Bean:

  1. The client calls a create() method in the bean’s home interface.
  2. The container sets aside storage for the object and instantiates it.
  3. The container calls the object’s setSessionContext() method.
  4. The container calls the ejbCreate() method whose signature matches the create() method invoked by the client.

 

 

Stateful and Stateless Session Beans

  • A stateless session bean is one that doesn’t keep track of any information from one method call to another – essentially, a bean with no instance variables. (Ex: CalculateInterest Bean)
  • Any two instances of a stateless bean are equivalent.
  • A container can easily handle a stateless Session bean, because instances of a stateless bean can be created and destroyed at will, without worrying about their state at the time of their destruction.
  • A stateful session bean, is a bean that changes state during a conversation – that is, a bean that has instance variables. (Ex: Shopping Cart Bean)
  • The life cycle of a stateful bean is more complex for the container than the stateless bean.
  • Because, the container have to maintain the state of the stateful session bean during swap out and swap in process.
  • According to the EJB specification, EJB Objects are not allowed to have static variables.

 

The SessionSynchronization Interface

public interface javax.ejb.SessionSynchronization

{

public abstract void afterBegin();

public abstract void afterCompletion(boolean committed);

public abstract void beforeCompletion();

}

 

  • A session bean can implement the SessionSynchronization interface if it wishes to be notified by the container about the state of any transaction in which it may be involved.
  • Even if a Session bean does not manage its own transactions via the UserTransaction interface, it may still implement the SessionSynchronization interface.
  • All of the methods in the SessionSynchronization interface are callbacks.

 

afterBegin()

  • This method notifies the bean that a transaction has begun.

 

beforeCompletion()

  • This method indicates that a transaction is nearly complete.
  • If the bean wishes to roll back the transaction for some reason, it can call the setRollbackOnly() method of the SessionContext interface to do so.

 

afterCompletion()

  • The container calls this method after a transaction has been completed.
  • Its boolean argument will be set to true if the transaction was committed successfully, and false if the transaction was rolled back.

 

  • This interface must be implemented in the stateful session bean because, the state of instance variables is not transactional.
  • That is, if the instance variables in a session bean are modified during the course of a transaction and the transaction is then rolled back, the instance variables will not be automatically reset to their original state prior to the transaction.
  • To reset the instance variables, the SessionSynchronization interface is needed and use the afterCompletion() callback to read the state variables back out of the database.
  • Note that, a stateless session bean cannot implement this interface, because, it has no state, there’s no point in trying to synchronize its state with the database.

Permalink Leave a Comment