Enterprise Java Beans - Introduction

Document Sample
Enterprise Java Beans - Introduction Powered By Docstoc
					Enterprise Java Beans
Enterprise Java Beans
   Enterprise JavaBeans, known as EJBs for
   A powerful facility dedicated to expressing
    the business logic of an application and for
    accessing a database using a JavaBeans-like
   A server-side component architecture that
    simplifies the process of building distributed
    component applications in Java
   By using EJB, you can write scalable,
    reliable, and secure applications.
Characteristics of Enterprise
   Remote Method Invocations
       Logic that connects a client and a server
   Load Balancing
   Transparent Fail-over
   Back-end Integration
       Integration with DB and legacy systems
   Clustering
   Dynamic Redeployment
       Redeployment with maximum availability
Characteristics of Enterprise
   Clean Shutdown
   Logging and Auditing
   Processing Multiple Client Requests
   Object pooling
       The objects need to be created or destroyed when client
        traffic increases or decreases
   Resource Pooling
   Security
   Caching
   Transactions, …
Component Architectures -
   Since the time of introduction of component
    architectures, a number of application servers have
   At first, each AS provided its own component
   The code became AS dependent
       Reduced portability
   Need
       A standard set of interfaces between AS and components
Component Architecture
Enterprise Java Beans
   A specification
       http://java.sun.com/products/ejb/docs.html
       Lays out rules of engagement between
        components and AS
   A set of Java interfaces
       Components and AS must conform to these
Enterprise Java Beans
   Enterprise Java Beans is a standard for
    building server-side components in Java
   Defines a set of interfaces between
    components and application servers
   Enterprise Beans are deployable, and can be
    imported and loaded into an application
    server, which hosts those components.
EJB Benefits
   Agreed upon by the industry
   Portability is easier
   Rapid Application Development
   Provides support for characteristics required
    by an Enterprise Application
EJB Execution Environment
   Enterprise beans run in the EJB container, a
    runtime environment within the Application Server
EJB Container
   The EJB container provides system-level
    services such as transactions and security to
    its enterprise beans.
   These services enable you to quickly build
    and deploy enterprise beans, which form the
    core of transactional Java EE applications.
Why Java?
   Java is one of the best-suited languages for
    building components for the following
       Interface/Implementation Separation
       Safe and Secure
       Cross-platform
Other Choices
   If you don’t want to go to the EJB route, you
    have two choices
       Lightweight open source Java Frameworks
           Spring
       Microsoft’s .Net Managed Components
EJB components
   EJB components are not presentation-tier
   They sit behind the presentation tier
    components and do all the hard work
EJB Clients
   Thick Clients
       Execute on user’s desktop
       Applets or Applications
   Dynamic Web-pages
       JSPs and Servlets can connect to EJBs for
        business services
   Web-service Clients
       Applications requiring a service over the internet
Kinds of EJBs
   Session Beans
   Entity Beans
   Message Driven Beans
Session Beans
   Model Business Processes
   A session bean represents a single client inside the
    Application Server.
   To access an application that is deployed on the
    server, the client invokes the session bean’s
   The session bean performs work for its client,
    shielding the client from complexity by executing
    business tasks inside the server.
Session Beans
   As its name suggests, a session bean is similar to
    an interactive session
   A session bean is not shared
       it can have only one client, in the same way that an
        interactive session can have only one user.
   Like an interactive session, a session bean is not
   When the client terminates, its session bean
    appears to terminate and is no longer associated
    with the client
Session Beans - State
Management Modes
   There are two types of session beans:
       Stateless Session Beans
       Stateful Session Beans
Stateless Session Beans
   A stateless session bean does not maintain a
    conversational state for the client.
   These beans do not declare any instance
    (class-level) variables, so that the methods
    contained within can act only on any local
   There is no way to maintain state across
    method calls.
Stateful Session Beans
   These beans can hold client state across
    method invocations.
   This is possible with the use of instance
    variables declared in the class definition.
   The client will then set the values for these
    variables and use these values in other
    method calls.
Entity Beans
   Model Business Data
   An entity bean represents a business object
    in a persistent storage mechanism.
   Some examples of business objects are
    customers, orders, and products.
   Typically, each entity bean has an underlying
    table in a relational database, and each
    instance of the bean corresponds to a row in
    that table.
Message Driven Beans
   Perform actions
     Similar to Session Beans
   Called by sending messages
   A message-driven bean is an enterprise bean that allows J2EE
    applications to process messages asynchronously.
   It normally acts as a JMS message listener, which is similar to an
    event listener except that it receives JMS messages instead of
   The messages can be sent by any J2EE component—an
    application client, another enterprise bean, or a web
    component—or by a JMS application or system that does not use
    J2EE technology.
   Message-driven beans can process either JMS messages or
    other kinds of messages.
Distributed Objects: The
Foundation for EJB
   EJB Components are based on distributed
   A Distributed Object is an object that is
    callable from a remote system
Distributed Objects – The Stub
   The client calls a stub
       Client-side proxy object
       Stub is responsible for masking network
        communications from the client
       Stub knows how to call over the network using
        sockets, massaging parameters into their network
Distributed Objects - Skeleton
   The Stub calls over the network to a skeleton
       A server-side proxy object
       Masks network communication from the
        distributed object
       Knows how to receive calls on a socket
Distributed Object –
Implementation Object
   The skeleton delegates the call to the
    appropriate implementation object
   This object does its work, and then returns
    control to the skeleton, which returns to the
    stub, which then returns control to the client
Distribution Transparency
   The stub and the server-side implementation
    object implement the same interface – The
    remote interface
   The stub clones the distributed object’s
    method signatures
Distribution Transparency
   A client who calls a method on the stub thinks he is
    calling the distributed object directly
   In reality, the client is calling an empty stub that
    knows how to go over the network
   The distributed object is an abstraction that is
    created by the cooperation between the stub,
    skeleton, and implementation objects
       No single entity in the scenario is the distributed object
Distributed Object
   Distributed Objects can be achieved by using
    a number of technologies
       Corba
       DCOM
       Java RMI-IIOP
Distributed Objects and
   Distributed objects enable us to distribute the
    application across a network
   As distributed applications grow larger, they
    require middleware services, such as
    transaction and security
   There are two way to get Middleware:
       Explicit
       Implicit
What constitutes an Enterprise
   The Enterprise Bean Class
   The Remote Interface
   The Home Interfaces
   javax.ejb.EJBObject extends
   javax.rmi.Remote is part of Java RMI over
    the Internet Inter-ORB Protocol (RMI-IIOP)
   Any object that implements this interface is a
    remote object and is callable from a different
   Java RMI-IIOP is J2EE’s de-facto mechanism
    for performing simple, powerful networking.
   Using RMI-IIOP you can write distributed
    objects in Java, enabling objects to
    communicate in memory across JVM and
    physical devices
   RMI-IIOP is a special version of RMI that is
    compliant with CORBA
   EJB and J2EE mandate the use of RMI-IIOP
Remote Method Invocations
   A Remote Procedure Call (RPC) is a
    procedural invocation from a process on one
    machine to a process on another machine
   A Remote Method Invocation in Java takes
    the RPC concept one step further and allows
    for distributed “object” communication
   RMI-IIOP enables you to invoke not merely
    procedures, but also methods on objects
   This yields the benefits of object-oriented
Distributed Objects-Issues
   Marshalling & Unmarshalling
       Different machines may have different way to
        represent data
       The memory layout may be entirely different
       The process is packaging and unpackaging of
        parameters so that they are usable in two
        heterogeneous environments
   Passing by reference & Passing by value
   Network or machine instability
       Error Reporting
Back to Session Beans
   Session EJB relates to business objects
     Not necessarily associated with a database
     May themselves use entity Beans
   Session EJB contains methods to provide business logic
     No concern with facilities or utilities
   Created on a per-client basis
     Can be stateful
           Attributes retain data between calls
       Can be stateless
           Attributes always at initial values
   Session EJBs are not persistent
     Data is lost on system crash
Creating a Session EJB
   There are several steps required to create an EJB
       Most are common between entity and session beans
       In this section, we concentrate on Session EJB
   Three items are required for deployment
     EJB class implementation
           Implements the methods to support EJB interfaces and provides
            business logic
       Remote EJB interface
           A remote interface describing services the EJB supplies
       Home interface
           Describes methods for constructing and finding EJB
   Notice that only one set of implementation code is required
     The business logic implementation. Everything else is generated
      by the EJB server
     The developer simply defines the interfaces
The EJB Remote Interface
   Defines services provided by the Session EJB
       Extends javax.ejb.EJBObject interface
         All methods must throw RemoteException

         All return types must be Serializable

       Named after class; e.g., Cart
       This is the definition of services available to client
         Client requests an object matching this interface

   You specify methods in the interface
       And implement matching methods in implementation class
         Server generates intermediate objects
Session EJB Remote Interface:
Importing both EJB and RMI         Must extend EJBObject

import javax.ejb.*;
import java.rmi.*;
import java.util.*;

public interface Cart extends EJBObject
       public void addTicket(String ticket)
               throws RemoteException;
        public Vector getTickets( ) throws RemoteException;
 Define EJB services for
 Session EJB
The Session EJB Home Interface
   Every Session EJB has an associated Home interface
     Interface describes the methods available to control life cycle
           Creation methods
       Does not define methods for locating specific EJB instances
           Session EJBs are created on a per-client basis .
           They are not persistent
   The Home interface must conform to EJB specification
     All methods must be Create methods
           Create methods must be named create (... )
   Only mandatory method is at least one Create method--
        Returns the EJB instance that is created from supplied data
The Session EJB Home
Interface: Example
Name is EJB name + 'Home'          Must extend EJBHome

   import javax.ejb.*;
   import java.rmi.*;

   public interface CartHome extends EJBHome
          Cart create ( ) throws CreateException,

                             Define create services
The Session Bean Class
   Finally, we need to implement the EJB
    Remote interface
       This is where we carry out the services specified
           The Session EJB class itself
   The Session EJB is a lengthy class
       Needs to implement support for
           Home Interface
           Remote Interface
           Bean Lifecycle service methods
The Session Bean Class
   Contains the logic
   A simple Java class that conforms to a well-
    defined interface and obeys certain rules
   The EJB Class must implement
    javax.ejb.EnterpriseBean interface
       javax.ejb.SessionBean, javax.ejb.EntityBean
   The interface forces the class to implement
    certain methods the all beans must provide
EJB Implementation: Remote
   This is the actual implementation of the
    EJB Remote interface
       Methods are implemented same as any other
        Java interface
           Again, the class itself does not implement the interface
 EJB Implementation: Remote Services-
Fields to define Bean              This time we implement SessionBean
 import javax.ejb.*;
 import java.rmi.*;
 import java.util.*;
 public class CartBean implements SessionBean
          private Vector tickets;
          private SessionContext ctx;
          public void addTicket(String ticket) throws RemoteException {
          public Vector getTickets( ) throws RemoteException {
                    return tickets.clone();
 // code for home services & code for ejb service callback suppprt}

                        Each method should throw RemoteException
The EJB Implementation: Home
   This is implementation to support the Home
       Need to support only Create methods

   Need to implement each Create method defined
    in interface
       Name of method is ejbCreate (...)
         But has correct signature
       Simply set up internal fields as required
         And return void
         The container hooks up the bean up to the client
The UP, Implementation: Home

public class CartBean implements SessionBean
       // code to support remote interface
       // code to support ejb services callback

        public void ejbCreate( ) throws
               Create.Exception, RemoteException {
          this.tickets = new Vector( );
    We are simply required to set up internal fields
EJB Implementation: EJB Server
   This is implementation to support the
    container functionality
       Methods must be implemented but often are
       Must fully implement the set and
        unsetSessioncontext methods
           Tie Bean into the container context
           Enable us to check security, handle explicit
            transactions, etc.
EJB Implementation: EJB Server
public class CartBean implements SessionBean
    // code to support remote and home interface
    private SessionContext ctx;
    public void setSessionContext( SessionContext
                          ctx) throws RemoteException {
                 this.ctx = ctx;
    public void ejbActivate( ){}
    public void ejbPassivate( ){}
Connecting to Session EJB
Home: Example
import java.rmi. *;
import java.util.Vector;
import java.ejb.*;
public class ConnectDemo {
        public static void main (String args[ ]) {
                Context c = new InitialContext ( );
                Object result = c.lookup (“SeminarServer ”);
                 CartHome h = (CartHome)
                javax.rmi.PortableRemoteObject.narrow( result,
                                         CartHome. class);
                 Cart cart = h.create ( ); // could have parameters
                 Vector v = cart.getTickets ( );
        //process the tickets

         Ask the EJB Finder to return a reference to the CartHome object
Getting a Reference to the
Session EJB
   Finally, ask the EJBHome object to return an EJB reference
     This can be via a call to create or find... methods
         Then client is able to interact with the Session EJB and request
   Actually get a reference to an EJBObject
     This acts as a proxy for the Session EJB
         This is a core part of EJB model
         Can do this as EJBObject implements Remote interface
   Allows the EJB container to hook all method calls
     Mechanism that EJB uses to provide container services
         Transaction processing
         Exception handling
         Load balancing
Generating the Session EJB
   That is all there is to it!
       Now need to generate and deploy the Bean
   Same stages required for generation and
       your TA would show you how to do it in JBoss
Generating the Session EJB
   The container generates several sets of classes
    for us
       Note that we have only written the EJB Bean code
         We have written code to support the Home interface
         We have not implemented the Home interface
         We have written code to support the Remote interface
         We have not implemented the Remote interface

   Thin is important
       Only the container-generated EJBObject implements the
        Remote interface
       The client can never get -a direct reference to the Session
         All interaction goes via the EJBObject
Session EJB Generation
              Generated by Server
EJB Home                            EJB
               EJB Home
Interface                           implementation


              EJB                   Remote
  methods     methods               methods

Shared By: