deploying a stateless ejb

Upload: rama-raju-indukuri

Post on 30-May-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/14/2019 Deploying a Stateless EJB

    1/61

    1

    Developing a Stateless Session

    Enterprise Java Bean

  • 8/14/2019 Deploying a Stateless EJB

    2/61

    2

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    How to develop and deploy a statelesssession bean by example:

    What is a stateless session bean When to use session beans Steps for implementing a stateless session

    bean Overview of EJB APIs Example Stateless session bean

    implementation Assembling an deploying the example session

    bean Writing and running the client of the example

    session bean

    Session Bean Tutorial Agenda:

  • 8/14/2019 Deploying a Stateless EJB

    3/61

    3

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session beans are typically usedfor business process or controllogic that spans multiple entitybeans

    Entity Bean Entity Bean

    What Are Session Beans?

    entity entity entity

    session

    A session bean is implemented to perform a sequence of tasks within the

    context of a transaction. For example, a session bean can execute a process or

    a transaction that accesses a database to display certain information to the

    client.

  • 8/14/2019 Deploying a Stateless EJB

    4/61

    4

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    What Is a Session Bean?

    Is relatively short- lived (life typically isthat of its client).

    Is removed when the EJB servercrashes.

    Does not represent data in database, butcan access it.

    Executes on behalf of a single client.

    Can be transaction aware.

  • 8/14/2019 Deploying a Stateless EJB

    5/61

    5

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    When to Use Session Beans?

    Use Session beans to model process orcontrol objects specific to a particularclient.

    To model workflow, processes or tasks,manage activities (make reservation,purchase...).

    To Coordinate processes between entitybeans, control interactions of beans.

    To put business application logic on the

    Server Side.

  • 8/14/2019 Deploying a Stateless EJB

    6/61

    6

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Beans Represent a

    business process

    One instance perclient

    Short-lived: Life ofclient is life of bean

    Transient Doesnt survive

    server crashes May be

    transactional

    Entity BeansRepresent business data

    Shared instance formultiple clients

    Long-lived: as long asdata in database

    Persistent

    Survive server crashesAlways Transactional

    Session vs. Entity Beans

    3 major design patterns for distributed objects multi-tier systems:

    EJB stateless session bean: stateless server object: object which provides

    responses to requests without storing information between requests (like http).

    Can be re-used on different client after method call finished.

    EJB stateful session bean: session oriented object: session is acting as agentfor the client, keeping state information until session is finished , 1 per client

    until session is finished.

    EJB entity bean: persistent object: wraps "object data" stored in a database

    and provides operations to manipulate this data. shared among multiple clients

    concurrently.

  • 8/14/2019 Deploying a Stateless EJB

    7/61

    7

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    2 Types of Session Beans

    Stateless: execute a request and returna result without saving any client specificstate information.

    transient

    temporary piece of business logic neededby a specific client for a limited timespan

    Stateful: maintains client specificstate.

    State instance data

    Stateless session beans model business processes that can be completed in a

    one method call.

    Stateless session beans do not maintain their state across method calls.

    Typically, you use stateless beans when the entire task can be performed

    within a single method call.

    Any instance of a stateless session bean can be used at any time by any client.

  • 8/14/2019 Deploying a Stateless EJB

    8/61

    8

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Stateless Session Beans

    oStateless beans:o Do not retain client information

    from one method invocation to thenext.

    o Client passes any needed informationas parameters to the businessmethods.

    oUsed mainly to provide a pool of beans tohandle frequent but brief requests.

    oThe EJB server transparently reusesinstances of the bean to servicedifferent clients.

    Stateless Session Beans

    Stateless session beans are designed strictly to provide server-side behavior.

    They are anonymous in that they contain no user-specific data. In fact, the

    EJB architecture provides ways for a single stateless session bean to serve the

    needs of many clients.

    This means that all stateless session bean instances are equivalent when they

    are not involved in serving a client-invoked method. The term stateless means

    that it does not have any state information for a specific client. However,

    stateless session beans can have non-client specific state, for example, an open

    database connection.

    A stateless session Bean maintains no state across methods and transactions

    -the EJB server transparently reuses instances of the Bean to service

    different clients at the per-method level (access to the session bean is

    serialized and is 1 client per session bean per method.

    -Pool of session beans < # clients because they can be reused

  • 8/14/2019 Deploying a Stateless EJB

    9/61

    9

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Stateless vs Stateful

    Cart items

    request with parametersneeded for processing

  • 8/14/2019 Deploying a Stateless EJB

    10/61

    10

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Stateless May Use FewerResources:

    oNumber of Stateless Session Beansneeded < Number of Clients:

    o Can be recycled.

    o Number of instances to create isminimized.

    o Shorter life (no client session) optimizesresource usage.

    o Improved performance due to fewerconnections across the network.

    oBut may require the client to maintainstate information on the client side whichcan mean more complex client code.

    Note: The difference in use of resources for stateless and stateful is application

    server specific.

  • 8/14/2019 Deploying a Stateless EJB

    11/61

    11

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    When to use Stateless SessionBeans?

    The following guide- lines can be used formodeling stateless session components:

    Reusable service objects

    May provide high performance

    Not tied up to one client after methodcompletes.

    Need to operate on multiple rows at atime (read- only view)

    Provides procedural view of data,(Entity Bean provides object view ofdata.)

    5.4.2.1 Uses of Stateless Session Beans

    A Bean Provider can use the following session bean characteristics as guidelines when deciding whether

    to model a business object as a stateless session bean:

    Modeling reusable service objects

    A business object that provides some generic service to all its clients can be modeled as stateless session

    beans. Such an object does not need to maintain any client specific state information, so the same bean

    instance can be reused to service other clients. For example, it would be appropriate to model a business

    object that validates an employee ID against a database as a state-less service.

    Providing high performance

    A stateless session bean can be very efficient as it requires fewer system resources by the virtue of being

    not tied to one client. Since stateless session beans minimize the resources needed to support a large

    number of clients, depending on the implementation of the EJB server, applications that use this approach

    may scale better than those using stateful session beans. However, this benefit may be offset by the

    increased complexity of the client application that uses the stateless session beans because the client has

    to perform the state management functions.

    Operating on multiple rows at a time

    A business object that manipulates multiple rows in a database and represents a shared view of the data

    is an ideal stateless session bean. An example of a such business object would be a catalog object that

    presents a list of various products and categories. Since all users would be interested in such information,

    the stateless session bean that represents it could easily be shared.

    Providing procedural view of data

    In a procedural view of data, methods of the business object do not operate on instance variables. Instead

    they behave like calls in a procedural language. The method caller provides all the input and the method

    returns all output to the caller. If a business object exhibits such functionality then it should be modeled

    as a stateless session bean.

    Example: A Catalog Bean

    The sample application uses a stateless session beans to model a catalog object. A catalog object provides

    browsing and searching services to its clients. Both of the primary functions of the catalog, browsing and

    searching, are generic services that are not tied to any particular client. Also, the catalog object operates

    on multiple rows in the database at the same time and provides a shared view of the data.

  • 8/14/2019 Deploying a Stateless EJB

    12/61

    12

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Implementing a Session Bean

    In this session we will discuss an examplestateless session bean, we will discussstateful in a later session.

    As an example we will use the ATMsession bean from the bank accounttransfer scenario.

  • 8/14/2019 Deploying a Stateless EJB

    13/61

    13

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Transfer

    Money

    Use Case: ATM customer transfers money from checking

    to savings account

    Example Scenario: Use Case

    Customer

  • 8/14/2019 Deploying a Stateless EJB

    14/61

    14

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    ATM Account

    accesses

    Checking

    Account

    Savings

    Account

    transfer() withdraw()

    deposit()

    0* 0*

    Example Scenario: Classes

    balance

  • 8/14/2019 Deploying a Stateless EJB

    15/61

    15

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    : CustomerATM saving

    accountcheckingaccount

    1: transfer()

    2: debit()

    Example Scenario: SequenceDiagram

    3: credit())

  • 8/14/2019 Deploying a Stateless EJB

    16/61

    16

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Account

    Entity Bean

    Account

    Entity Bean

    ATM

    Session beanClient

    Transfer

    debit

    credit

    account1

    account2

    Example Scenario: EJB

  • 8/14/2019 Deploying a Stateless EJB

    17/61

    17

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1. Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementationclass.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb- jar file.7. Deploy the enterprise application.

    What the ATM session Bean provider is responsible for:

    Define the session Beans remote interface (Atm). The remote interface

    defines the business methods callable by a client. The remote interface must

    extend the javax.ejb.EJBObject interface, and follow the standard rules for a

    RMI-IIOP remote interface. The remote interface must be defined as public.

    Write the business logic in the session Bean class (AtmBean). The

    enterprise Bean must implement the javax.ejb.SessionBean interface, and

    define the ejbCreate(...) methods invoked at an EJB object creation.

    Define a home interface (AtmHome) for the enterprise Bean. The home

    interface must be defined as public, extend the javax.ejb.EJBHome interface,

    and follow the standard rules for RMI-IIOP remote interfaces.

    Define a deployment descriptor specifying any declarative metadata that the

    session Bean provider wishes to pass with the Bean to the next stage of the

    development/deployment work-flow.

  • 8/14/2019 Deploying a Stateless EJB

    18/61

    18

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    EJB API Review

    java.RMI.Remote

    java.io.serializable

    EJBHome

    EJBObject

    JDK

    javax.ejb

    Beanprovider

    xxxContainerprovider

    EnterpriseBean

    SessionBean

    AtmHome

    Atm

    AtmBean

    xxxatmEJBHome

    xxxatmEJBObject

    xxxAtmBean

    The tools provided by xxx Corporation are responsible for the following:

    Generate the class (xxxRemoteAtm) that implements the session beans

    remote interface. The tools also generate the classes that implement the

    communication protocol specific artifacts for the remote interface.

    Generate the implementation of the session Bean class suitable for the xxxcontainer (xxxAtmBean). xxxAtmBean includes the business logic from the

    AtmBean class mixed with the services defined in the xxxBean class. xxx tools

    can use inheritance, delegation, and code generation to achieve a mix-in of

    the two classes.

    Generate the class (xxxAtmHome) that implements the session beans

    home interface.

    Generate the class (xxxAtmMetaData) that implements the

    javax.ejb.EJBMetaData interface for the Atm Bean.

  • 8/14/2019 Deploying a Stateless EJB

    19/61

    19

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    javax. EJB Client Interfaces

    java.RMI.Remote

    EJBHome

    remove()getEJBMetaData()getHomeHandle()

    EJBObject

    getEJBHome()

    remove()getHandle()isIdentical()

    extends

    The EJBHome interface is extended by all enterprise Bean's home interfaces. An enterprise Bean's home interface

    defines the methods that allow a client to create, find, and remove EJB objects. Each enterprise Bean has a home

    interface. The home interface must extend the javax.ejb.EJBHome interface, and define the enterprise Bean type

    specific create and finder methods (session Beans do not have finders). The home interface is defined by the enterprise

    Bean provider and implemented by the enterprise Bean container. Method Summary:

    EJBMetaData getEJBMetaData()

    Obtain the EJBMetaData interface for the enterprise Bean.

    HomeHandle getHomeHandle()

    Obtain a handle for the home object.

    Void remove(Handle handle)

    Remove an EJB object identified by its handle.

    Void remove(java.lang.Object primaryKey)

    Remove an EJB object identified by its primary key.

    The EJBObject interface is extended by all enterprise Bean's remote interface. An enterprise Bean's remote interface

    provides the client's view of an EJB object. An enterprise Bean's remote interface defines the business methods

    callable by a client. Each enterprise Bean has a remote interface. The remote interface must extend the

    javax.ejb.EJBObject interface, and define the enterprise Bean specific business methods. The enterprise Bean's remote

    interface is defined by the enterprise Bean provider and implemented by the enterprise Bean container. Method

    Summary

    EJBHome getEJBHome()

    Obtain the enterprise Bean's home interface.

    Handle getHandle()

    Obtain a handle for the EJB object.

    java.lang.Object getPrimaryKey()

    Obtain the primary key of the EJB object.

    Boolean isIdentical(EJBObject obj)

    Test if a given EJB object is identical to the invoked EJB object.

    void remove()

    Remove the EJB object.

  • 8/14/2019 Deploying a Stateless EJB

    20/61

    20

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    javax. EJB Server Interfaces

    java.io.serializable

    EnterpriseBean

    EntityBean

    setEntityContext()unsetEntityContext

    ejbRemove()ejbActivate()

    ejbPassivate()

    ejbLoad()ejbStore()

    SessionBean

    setSessionContext()ejbRemove()ejbActivate()

    ejbPassivate()

    The EnterpriseBean interface must be implemented by every enterprise Bean

    class. It is a common super interface for the SessionBean and EntityBean

    interfaces.

    The SessionBean interface is implemented by every session enterprise Bean

    class. The container uses the

    SessionBean methods to notify the enterprise Bean instances of the instance's

    life cycle events.

    Method Summary:

    void ejbActivate()

    The activate method is called when the instance is activated from its "passive"

    state.

    void ejbPassivate()

    The passivate method is called before the instance enters the "passive" state.

    void ejbRemove()

    A container invokes this method before it ends the life of the session object.

    void setSessionContext(SessionContext ctx)

    Set the associated session context.

  • 8/14/2019 Deploying a Stateless EJB

    21/61

    21

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    javax. EJB Server InterfacesCont.

    EntityContext

    getEJBObject()getPrimaryKey()

    SessionContext

    getEJBObject()

    EJBContext

    getEJBHome()getEnvironment()getCallerIdentity()isCallerInRole()

    getUserTransaction()setRollBackOnly()

    The SessionContext interface

    A container provides the session bean instances with a SessionContext, which gives the

    session

    bean instance access to the instances context maintained by the container. This give

    information about the beans home object, current transaction information, security role

    information. The SessionContextinterface has the following methods:

    The getEJBObject method returns the session beans remote interface.

    The getEJBHome method returns the session beans home interface.

    The getCallerPrincipal method returns the java.security.Principal that identifies the invoker

    of the bean instances EJB object.

    The isCallerInRole method tests if the session bean instances caller has a particular role.

    The setRollbackOnly method allows the instance to mark the current transaction such that

    the only outcome of the transaction is a rollback. Only instances of a session bean with

    container-managed transaction demarcation can use this method.

    The getRollbackOnly method allows the instance to test if the current transaction has been

    marked for rollback. Only instances of a session bean with container-managed transactiondemarcation can use this method.

    The getUserTransaction method returns the javax.transaction.UserTransaction interface.

    The instance can use this interface to demarcate transactions and to obtain transaction status.

    Only instances of a session bean with bean-managed transaction demarcation can use this

    method.

  • 8/14/2019 Deploying a Stateless EJB

    22/61

    22

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Differences From Entity Bean

    Session Implements

    SessionBeaninterface

    Does not use primarykey object

    Uses create methodto create instance,stateful to initializelocal data

    Entity

    ImplementsEntityBean interface

    Uses primary keyobject

    Uses create, andcallback methods tocreate,store/updatedata in database

    Session EJB objects are created, associated with a specific client, and then

    removed as needed, whereas entity EJB objects represent permanent

    data in a data storage that can be uniquely identified with a primary key.

    Because the instance data for session beans is not persistent, the session bean

    class does not have callback methods for storing data to and loading data

    from a data source.

  • 8/14/2019 Deploying a Stateless EJB

    23/61

    23

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1 . Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementation class.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb-jar file.

    7. Deploy the enterprise application.

    What the ATM session Bean provider is responsible for:

    Define the session Beans remote interface (Atm). The remote interface

    defines the business methods callable by a client. The remote interface must

    extend the javax.ejb.EJBObject interface, and follow the standard rules for a

    RMI-IIOP remote interface. The remote interface must be defined as public.

  • 8/14/2019 Deploying a Stateless EJB

    24/61

    24

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    1 ) Create the Remote Interface

    public interface Atm extends javax. ejb.EJBObject {

    public void transfer(int fromAcctId, int toAcctId, double amount)throws java.rmi.RemoteException,InsufficientFundsException;

    }

    EJBObject

    Atm

    transfer()

    extends

    Define Business Methods:

    Session beans remote interface

    The following are the requirements for the session beans remote interface:

    The interface must extend the javax.ejb.EJBObject interface.

    The methods defined in this interface must follow the rules for RMI/IIOP.

    This means that their arguments and return values must be of valid types forRMI/IIOP, and their throws clause must include the

    java.rmi.RemoteException.

    The remote interface is allowed to have super interfaces. Use of interface

    inheritance is subject to the RMI/IIOP rules for the definition of remote

    interfaces.

    For each method defined in the remote interface, there must be a matching

    method in the session beans class. The matching method must have:

    The same name.

    The same number and types of arguments, and the same return type. All the exceptions defined in the throws clause of the matching

    method of the session bean class must be defined in the throws clause

    of the method of the remote interface.

  • 8/14/2019 Deploying a Stateless EJB

    25/61

    25

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1. Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementation class.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb-jar file.

    7. Deploy the enterprise application.

    What the ATM session Bean provider is responsible for:

    Define a home interface (AtmHome) for the enterprise Bean. The home

    interface must be defined as public, extend the javax.ejb.EJBHome interface,

    and follow the standard rules for RMI-IIOP remote interfaces.

  • 8/14/2019 Deploying a Stateless EJB

    26/61

    26

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    2) Create the Home Interface

    public interface AtmHome extends javax.ejb.EJBHome {

    Atm create() throws java.rmi.RemoteException,javax.ejb.CreateException;

    }

    EJBHome

    AtmHome

    create()

    Returns Atmremote interface

    Define Create Methods:

    Session beans home interface requirements:

    The interface must extend the javax.ejb.EJBHome interface.

    The methods defined in this interface must follow the rules for RMI/IIOP. This means that

    their arguments and return values must be of valid types for RMI/IIOP, and that their throws

    clause must include the java.rmi.RemoteException.

    The home interface is allowed to have superinterfaces. Use of interface inheritance is subjectto the RMI/IIOP rules for the definition of remote interfaces.

    A session beans home interface must define one or more create(...) methods. (stateless only

    1)

    Each create method must be named create, and it must match one of the ejbCreate methods

    defined in the session bean class. The matching ejbCreate method must have the same number

    and types of arguments. (Note that the return type is different.) (stateless no arguments)

    The return type for a create method must be the session beans remote interface type.

    All the exceptions defined in the throws clause of an ejbCreate method of the session bean

    class must be defined in the throws clause of the matching create method of the home inter-

    face.

    The throws clause must include javax.ejb.CreateException.

  • 8/14/2019 Deploying a Stateless EJB

    27/61

    27

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1. Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementationclass.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb-jar file.7. Deploy the enterprise application.

    What the ATM session Bean provider is responsible for:

    Write the business logic in the session Bean class (AtmBean). The

    enterprise Bean must implement the javax.ejb.SessionBean interface, and

    define the ejbCreate(...) methods invoked at an EJB object creation.

  • 8/14/2019 Deploying a Stateless EJB

    28/61

    28

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    3) AtmBean Implementation

    AtmBean

    transfer()ejbCreate()

    setSessionContext()ejbRemove()ejbActivate()

    ejbPassivate()

    implements

    Atm

    transfer()

    AtmHome

    create()

    must matchfor containerglue

    SessionBean

    setSessionContext()ejbRemove()ejbActivate()

    ejbPassivate()

    The following are the requirements for the session bean class:

    must implement the javax.ejb.SessionBean interface.

    must be defined as public, must not be final, and must not be abstract.

    must have a public constructor that takes no parameters. The Container uses

    this constructor to create instances of the session bean class.

    must not define the finalize() method.

    must implement the business methods and the ejbCreate methods.

    If the class is a stateful session bean, it may optionally implement the

    javax.ejb.SessionSynchronization interface.

    The session bean class may have superclasses and/or superinterfaces. If the

    session bean has superclasses, then the business methods, the ejbCreate

    methods, the methods of the SessionBean interface, and the methods of the

    optional SessionSynchronization interface may be defined in the session bean

    class, or in any of its superclasses.The session bean class is allowed to implement other methods (for example

    helper methods invoked internally by the business methods) in addition to the

    methods required by the EJB specification.

  • 8/14/2019 Deploying a Stateless EJB

    29/61

    29

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Lifecycle of a Stateless SessionBean

    method-readypool

    EJBInstance

    ejbRemove()

    business method

    does not

    exist

    1) newInstance()

    2) setSessioncontext()

    3)ejbCreate()

  • 8/14/2019 Deploying a Stateless EJB

    30/61

    30

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Invocation of a Business Method

    clientbean

    instanceEJB

    HomeEJB

    Objectsessioncontext

    synchro

    nization

    trans

    action

    data

    base

    business method

    business method

    read, update data

    register resource mgr

  • 8/14/2019 Deploying a Stateless EJB

    31/61

  • 8/14/2019 Deploying a Stateless EJB

    32/61

    32

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Creating a Stateless Session BeanInstance

    clientbean

    instanceEJBHome EJBObject context

    create()

    new

  • 8/14/2019 Deploying a Stateless EJB

    33/61

    33

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Adding Instance of Stateless SessionBean to a Method- ready Pool

    clientbean

    instanceEJB

    HomeEJB

    Objectsessioncontext

    synchro-

    nization

    trans

    action

    data

    base

    cont-

    ainer

    new

    new

    setSessionContext()

    ejbCreate()

  • 8/14/2019 Deploying a Stateless EJB

    34/61

    34

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    3) AtmBean: Implement HomeInterface Create Method

    // implement atmHome interface createprivate static AccountHome accountHome = null;public void ejbCreate (){try {

    Context ic = new InitialContext();

    java.lang. Object objref = ic.lookup("java:comp/env/ejb/Account");accountHome=(AccountHome)PortableRemoteObject.narrow(objref,

    AccountHome. class);} catch (NamingException ne) {

    System.err.println("ejbCreate: Caught unexpectedNamingException:");

    }}EXAMPLE DEPLOYMENT DESCRIPTOR XML FOR EJB REFERENCE< ejb- ref>

    < ejb- ref-name> ejb/Account< /ejb-ref-name>< ejb- ref-type> Entity< /ejb-ref-type>< home> package. AccountHome< /home>< remote> package. Account< /remote>< /ejb-ref>

    Returns void

    Bean create methods must match the methods defined in this EJB's home interface, AtmHome.

    Container tools generate the implementation of the AtmHome class and the client stub and

    server skeleton classes. Calls on those classes will be forwarded to the AtmBean.

    A stateless session bean must have only one ejbCreate method, which must return void and

    contain no arguments. In a stateless session bean, none of the methods depend on the values

    of variables set by any other method, except for the ejbCreate, setSessionContext methods

    which set the initial (identical) state of each bean instance. The term stateless signifies that

    an instance has no state for a specific client. However, the instance variables of the stateless

    session bean can contain non-client specific state across client-invoked method calls.

    Examples of such states include an open database connection or an object reference to an

    EJB object.

    ejbCreate method

    The stateless session bean class must define one ejbCreate(...) methods whose signature must

    follow these rules:

    The method name must be ejbCreate.

    The method must be declared as public.

    The method must not be declared as final or static.

    The return type must be void.

    The methods arguments must be legal types for RMI/IIOP.

    The throws clause may define arbitrary application exceptions, possibly including the

    javax.ejb.CreateException.

  • 8/14/2019 Deploying a Stateless EJB

    35/61

    35

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Removing Instance of StatelessSession Bean From Ready Pool

    clientbean

    instanceEJB

    HomeEJB

    Objectsessioncontext

    synchro-

    nization

    trans

    action

    data

    base

    cont-

    ainer

    ejbRemove()

  • 8/14/2019 Deploying a Stateless EJB

    36/61

    36

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Removal of a Stateless SessionBean Instance

    clientbean

    instanceEJBHome EJBObject context

    remove()

  • 8/14/2019 Deploying a Stateless EJB

    37/61

    37

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    3) AtmBean: Implement SessionInterface Container Callback Methods

    // save the session context in an instance variablepublic void setSessionContext(SessionContext sc) {this.context= sc;

    }

    // release resources allocated in ejbCreatepublic void ejbRemove() throws RemoveException {

    accountHome = null;}

    // Stateless Session Beans are not activated/passivated// so these methods are always emptypublic void ejbActivate() {}public void ejbPassivate() {}

    Bean callback methods:

    The container uses these to alert the bean of runtime events. Each method is

    called at a specific time during the life cycle of a bean.

    The beans container calls the setSessionContext method to associate a

    session bean instance with its context maintained by the container. Typically,a session bean instance retains its session context as part of its

    conversational state.

    The ejbRemove notification signals that the instance is in the process of being

    removed by the container. In the ejbRemove method, the instance typically

    releases the resources that it allocated in the ejbCreate method.

    ejbActivate/ejbPassivate:

    All Stateless Session bean instances are equivalent when they are not involved

    in serving a client-invoked method. A container only needs to retain the

    number of instances required to service the current client load. Due to client

    think time, this number is typically much smaller than the number of activeclients. Passivation is not needed for stateless sessions. The container

    creates another stateless session bean instance if one is needed to handle an

    increase in client work load. If a stateless session bean is not needed to handle

    the current client work load, the container can destroy it.

  • 8/14/2019 Deploying a Stateless EJB

    38/61

    38

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Lifecycle of a Stateless SessionBean

    method-readypool

    EJBInstance

    ejbRemove()

    business method

    does not

    exist

    1) newInstance()

    2) setSessioncontext()

    3)ejbCreate()

  • 8/14/2019 Deploying a Stateless EJB

    39/61

    39

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1. Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementation class.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb-jar file.

    7. Deploy the enterprise application.

  • 8/14/2019 Deploying a Stateless EJB

    40/61

    40

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    4) Compile the Remote & Home Interfaces andImplementation Class.

    javac classpath $J2EE_HOME/lib/j2ee.jarAtm.java AtmHome.javaAtmEJB.java

  • 8/14/2019 Deploying a Stateless EJB

    41/61

    41

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1. Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementation class.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb-jar file.

    7. Deploy the enterprise application.

    What the ATM session Bean provider is responsible for:

    Define the session Beans remote interface (Atm). The remote interface

    defines the business methods callable by a client. The remote interface must

    extend the javax.ejb.EJBObject interface, and follow the standard rules for a

    RMI-IIOP remote interface. The remote interface must be defined as public.

    Write the business logic in the session Bean class (AtmBean). The

    enterprise Bean must implement the javax.ejb.SessionBean interface, and

    define the ejbCreate(...) methods invoked at an EJB object creation.

    Define a home interface (AtmHome) for the enterprise Bean. The home

    interface must be defined as public, extend the javax.ejb.EJBHome interface,

    and follow the standard rules for RMI-IIOP remote interfaces.

    Define a deployment descriptor specifying any declarative metadata that the

    session Bean provider wishes to pass with the Bean to the next stage of the

    development/deployment work-flow.

  • 8/14/2019 Deploying a Stateless EJB

    42/61

    42

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    XML Short Intro

    The XML Companion

    Neil Bradley

    Addison-Wesley

    Processing Instruction (PI)

    Document Type Definition(DTD)

    Element

    Attribute

    Processing Instruction (PI)

    Document Type Definition(DTD)

    Element

    Attribute

  • 8/14/2019 Deploying a Stateless EJB

    43/61

    43

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    EJB descriptor composition

  • 8/14/2019 Deploying a Stateless EJB

    44/61

    44

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    5) Create Deployment Descriptor

    Set the values for the class names,

    transaction attributes,

    Environment values,resource references,

    EJB references

  • 8/14/2019 Deploying a Stateless EJB

    45/61

    45

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    5) Create Deployment Descriptor

    This example sets the EJB reference for referencing the Account Bean.

    Example code in the AtmEJB for referencing the Account Bean:

    Context ic = new InitialContext();

    java.lang.Object objref = ic.lookup("java:comp/env/ejb/Account");

    accountHome=(AccountHome)PortableRemoteObject.narrow(objref,

    AccountHome.class);

  • 8/14/2019 Deploying a Stateless EJB

    46/61

    46

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    5) Create Deployment Descriptor

    This example show setting the transaction attributes. We will go over

    transactions in Lecture 4. Here we set the method transfer to transaction

    required because we want to make sure that the transfer takes place in a

    transaction, so that either both the credit and debit accounts are updated or

    NO accounts are updated.

  • 8/14/2019 Deploying a Stateless EJB

    47/61

    47

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    5) Create Deployment Descriptor

  • 8/14/2019 Deploying a Stateless EJB

    48/61

    48

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    5) Create DD Cont.

    AtmBean

    Remote

    transfer

    Required

  • 8/14/2019 Deploying a Stateless EJB

    49/61

    49

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1. Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementation class.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb- jar file.

    7. Deploy the enterprise application.

  • 8/14/2019 Deploying a Stateless EJB

    50/61

    50

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    6) Package in an ejb- jar File.

    AtmAtmHomeInterfaces

    AtmEJBbean

    Deployment

    Descriptor

    XML DD

    packager ejbJarAtm.class:AtmEJB.class:AtmHome.classAtm-ejb-jar.xml Atm.jar

  • 8/14/2019 Deploying a Stateless EJB

    51/61

    51

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    6) Package in an ejb- jar File.

  • 8/14/2019 Deploying a Stateless EJB

    52/61

    52

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

  • 8/14/2019 Deploying a Stateless EJB

    53/61

    53

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Implementation

    1. Create the remote interface for thebean.

    2. Create the beans home interface.

    3. Create the beans implementation class.

    4. Compile the remote interface, homeinterface, and implementation class.

    5. Create a deployment descriptor.

    6. Package in an ejb-jar file.

    7. Deploy the enterprise application.

  • 8/14/2019 Deploying a Stateless EJB

    54/61

    54

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    7) Deploy the EnterpriseApplication

    Deployment tool

    Deployment tool

    Client Jar: : Atm, AccountEJBHome EJBObject

    Interfaces & Stubs

    Server Jar: Atm and AccountEJBHome EJBObject

    Stubs and Object implementationsEnterprise Beans

    Application jar: Atm, AccountEJBHome EJBObject interfaces,Atm, Account beans

    AtmEJB.jar,Account.EJBjar

    J2EE Reference Implementation Deployment: Behind the Scenes

    1. The J2EE process opens the application JAR file, reads the deployment descriptors, and

    generates the home interface and EJBObject implementation for each Bean.

    2. The J2EE process compiles the home interface and the EJBObject implementations and

    then runs the rmic command on the class files. This step creates the stubs and skeletons

    for the home and remote objects.3. The server packages the generated classes into a server JAR file and stores the JAR file

    in the repository.

    4. The server creates a client JAR file that contains the home and remote interfaces and

    the stubs for the home and remote objects. The server sends the client JAR file to the

    deployer and saves the file according to the name chosen at the start of the deployment

    process.

    5. The location of the client JAR file must be added to the CLASSPATH environment

    variable on any client that calls the application. Then, at runtime, the appropriate stub

    classes can be loaded so that the client can successfully locate objects, for example, the

    home object for an enterprise bean in the application.

    6. The J2EE server starts a process which loads the server JAR file and creates containers

    for the enterprise beans and binds the beans to the JNDI names in the name server.

    7. At this point, the deployment process is complete.

  • 8/14/2019 Deploying a Stateless EJB

    55/61

    55

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Example of Deployment of Bank Application .ear consisting of Atm Session

    EJB .jar and Account Entity EJB .jar.

  • 8/14/2019 Deploying a Stateless EJB

    56/61

    56

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Create a Client

    1. Use JNDI to lookup EJBs homeinterface.

    2. Call homes create method to get theEJB remote object interface.

    3. Call beans business methods thruremote interface.

  • 8/14/2019 Deploying a Stateless EJB

    57/61

    57

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    ATM Client Code

    // create an initial context (starting point in name tree)javax. naming.Context ic =newjavax. naming. InitialContext();

    // lookup jndi name (set by deployer in deploymentdescriptor)java. lang.Object objref = ic. lookup("Atm");

    AtmHome home = (AtmHome)PortableRemoteObject. narrow(objref, AtmHome.class);

    //call AtmHome Create method to get Atm interfaceAtm atm = home. create();

    // call Atm business methodsatm. transfer(41476633, 4443332121, 100000);

    1) Use JNDI name services to locate a name server:

    Create an InitialContext (starting point) with server environment properties.

    2)lookup the Atm EJBHome interface using the JNDI name given in

    deployment descriptor

    -lookup returns a stub reference to the object implementation of AccountHome

    3)call create to get a reference to the Atm EJBObject stub.

    4)call Atm business methods

  • 8/14/2019 Deploying a Stateless EJB

    58/61

    58

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Session Bean Accessing Entity Bean

    Client

    server

    JNDI nameservice

    EJBObject

    AccountBean

    EJBHome

    AccountBean

    EJBObject

    AtmBean

    EJBObjecttransferfind

    withdraw

    deposit

    find

    Example of Sequence of events for Client calling the Transfer method on the

    Atm remote interface stub.

  • 8/14/2019 Deploying a Stateless EJB

    59/61

    59

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Exercise: Design and ImplementCatalog Stateless Session Bean

    customerList Books in Store

    customerSearch for books by subject

    Use Case Scenarios

    customerGet Book Details (by ISBN)

    1)Customer finds book by ISBN

    2)Customer searches for books by subject, author title.

  • 8/14/2019 Deploying a Stateless EJB

    60/61

    60

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    Stateless Services:Catalog Session EJB

    product

    ISBN

    title

    author

    description

    A Catalog object represents different products and provides

    br owsing and searching services to its clients. Both of the primary functio

    of the catalog, browsing and searching, are generic services which are not

    tied to any par ticular client . Also, the catalog object reads multiple rows

    in the database at the same time and provides a shar ed view of the data.

    CatalogEJB

    getBooks()

    getBookDetails()

    findBooksBySubject()

    ejbCreate()

    setSessionContext()

    ejbRemove()

    ejbActivate()

    ejbPassivate()

  • 8/14/2019 Deploying a Stateless EJB

    61/61

    Copyright 2000 Sun Microsystems, Inc., All rights reserved.

    CatalogEJB

    CatalogEJB

    getBooks()

    getBookDetails()

    findBooksBySubject()

    ejbCreate()

    setSessionContext()

    ejbRemove()

    ejbActivate()

    ejbPassivate()

    BookDeta i ls

    I S B N

    ti t le

    a u th o r

    p u b l i s h e r

    s u b j e c t

    d e s c r ip t io n

    p r i c e

    g e t ISBN()

    getT i t le ()

    g e tAu th o r ( )

    g e tP r i c e ( )

    g e tDe s c r ip t io n ( )

    g e tPu b l i s h e r ( )

    Catalog

    getBooks()

    getBookDetails()

    findBooksBySubject()

    CatalogHome

    create()