Chap 16 - PowerPoint PPT Presentation

1 / 40
About This Presentation
Title:

Chap 16

Description:

Beans will be developed, including all the business logic and ... Enterprise Java Beans are invoked from the ejbObject proxy, which serializes each method call. ... – PowerPoint PPT presentation

Number of Views:45
Avg rating:3.0/5.0
Slides: 41
Provided by: tcnj
Category:
Tags: beans | chap

less

Transcript and Presenter's Notes

Title: Chap 16


1
Chap 16
  • Developing Deploying
  • Enterprise Java Beans

2
Development Lifecycle
  • Designing a distributed application requires many
    different phases, and multiple responsibilities.
  • An overall system architecture is normally
    defined (how client and servers communicate),
    then many sub-system architectures will be
    defined (how particular server components may
    communicate).

3
Development Lifecycle
  • Defining a server architecture for an application
    that uses Enterprise Java Beans can be very
    complex.
  • Decisions for what objects will be session -vs-
    entity -vs- non ejbs will be made.
  • Remote Home interfaces need to be designed (an
    understanding for how each bean will be used).
  • Beans will be developed, including all the
    business logic and other classes that are used
    with the beans (remember, beans can use each
    other )

4
Bean Development Issues
  • Enterprise Java Beans are invoked from the
    ejbObject proxy, which serializes each method
    call.

5
Creating a Session Bean
  • The design of the Session Bean architecture
    prohibits more then one method from being called
    at one time. It is synchronise, so the client is
    blocking while the method is being executed.
  • Each session bean should therefor be instantiated
    only once per client (ex if many functions use
    the ejbCalculator bean, a single bean should be
    instantiated and passed between functions).

6
Creating a Session Bean
  • Instantiation Of A Session Bean
  • When the container needs to create a new session
    bean, a newInstance() method is called from the
    bean. This automatically calls the constructor
    method.
  • Next, the beans setSessionContext() method is
    called, which makes it aware of the containers
    context.
  • Finally, the ejbCreate() method is called (this
    is ware you put code needed to execute when the
    bean is created).

7
Creating a Session Bean
  • Calls To A Session Bean
  • When a call is made to the session bean from the
    client, it is made just like any call to a local
    object.
  • Removing The Session Bean
  • When a session bean is no longer needed, it
    should be physically removed by the client by
    calling its ejbHomes remove() method.
  • This will cause the container to execute the
    beans ejbRemove() method (similar to a
    destructor).

8
Creating a Session Bean
  • Stateless Session Bean Methods Used By
    Container
  • ejbPassivate() is used when the container finds
    no activity for the bean. It may serialize it and
    save to disk until needed. Its still
    instantiated, though!
  • ejbActivate() is used if the bean is finally
    called by a client. Container will read it back
    into memory.
  • Code can be placed in any of these methods for
    custom functionality in the event a bean is
    temporarily removed.

9
A Stateless Session Bean
  • Remote Interface
  • public interface IsPrime extends EJBObject,
    Remote
  • public boolean isPrime(long num) throws
    RemoteException
  • public boolean isPrime(int num) throws
    RemoteException

10
A Stateless Session Bean
  • Home Interface
  • public interface IsPrimeHome extends EJBHome
  • IsPrime create() throws CreateException,
    RemoteException

11
A Stateless Session Bean
public class IsPrimeBean implements
SessionBean protected SessionContext
context public void ejbActivate()
public void ejbRemove() public void
ejbPassivate() public void ejbCreate()
public void setSessionContext(SessionConte
xt ctx) context ctx
12
public boolean isPrime(long num)
long test long max boolean
retVal true if((num0)(num
1)) return false num Math.abs(num)
max num/2 1 for(test2testtest) if(numtest 0)
retVal false
break
return retVal public boolean isPrime(int
num) return isPrime((long)num)
13
A Stateless Session Bean
  • Deployment Descriptors
  • beanHomeName
    isprime.IsPrimeHome
  • JNDI name of EJBean
  • enterpriseBeanClassName
    isprime.IsPrimeBean
  • The EJBean class
  • homeInterfaceClassName
    isprime.IsPrimeHome
  • The home interface implemented by a class
    generated by
  • the EJB compiler (ejbc).
  • remoteInterfaceClassName isprime.IsPrime
  • This interface is implemented by an
    "EJBObject".
  • stateManagementType
    STATELESS_SESSION
  • Either STATELESS_SESSION or
    STATEFUL_SESSION.
  • The type of session EJBean.

14
A Stateless Session Bean
  • public class IsPrimeClient
  • ctx getInitialContext(args)
  • IsPrimeHome home (IsPrimeHome)ctx.lookup("isprim
    e.IsPrimeHome")
  • IsPrime checker home.create()
  • try
  • test Long.parseLong(userinput)
  • if(checker.isPrime(test))
  • System.out.println(" is prime.")
  • else
  • System.out.println(" is not prime.")
  • catch // catch error here

15
A Stateful Session Bean
  • Creating the Home and Remote interfaces can be
    identical between stateful and stateless session
    beans, depending on your needs.
  • Again, a Stateful bean is ment to hold static
    information between calls to it - and hold on to
    the Session Context.

16
A Stateful Session Bean
  • public class NextPrimeBean implements SessionBean
  • transient protected SessionContext context
  • // all ejbMethods from the SessionBean interface
    here
  • public void ejbCreate(long start)
  • current start
  • public long nextPrime()
  • current nextPrimeAfter(current)
  • return current

17
Rules For Session Bean Development
  • Session Beans cannot be abstract (although they
    can be inherited).
  • There must be a Remote and Home interface.
  • Arguments to and returned from methods must
    follow RMI constraints. This usually means the
    object must be serializable.
  • Clients should remove the beans when done.

18
Creating An Entity Bean
  • While Session Beans represent a clients unique
    session, Entity Beans represent the data that
    clients use.
  • Each Entity Beans purpose in life is to
    represent a unique data element. What the
    underlining data store is, or how the bean
    selects or updates the data, should be
    transparent to the client.

19
Creating An Entity Bean
  • For instance, if a java applet was using a
    traditional 2-tier architecture and needed to
    retrieve customer data, it would execute a query
    in JDBCresultset stmt.executeQuery(SELECT
    cust_name, cust_address FROM tblCustomers where
    cust_id 101)
  • If that same applet was using an Entity Bean, it
    would grab the instance of that bean which
    represented customer 101ejbCustomer
    ejbHome.findByPrimaryKey(101)sName
    ejbCustomer.getName() // call methods on this
    obj. sAddress ejbCustomer.getAddress() // to
    retrieve its attributes

20
Creating An Entity Bean
  • From the last examples, one of the biggest
    differences between using SQL to retrieve the
    data from a Relational Database, and using an
    Entity Bean, is that entities are objects - with
    behavior. Where retrieving data from SQL are just
    atomic values.
  • Another difference is that Entity Beans leave the
    implementation of persistence up to the middle
    tier. Transparent to the clients.

21
Creating An Entity Bean
  • Entity Beans can use several data stores for
    persisting its data
  • Relational DBMS
  • Object DBMS
  • Object Serialization
  • Regardless of what technology is used to store
    the data, the rules for developing the beans
    should be the same.

22
Creating An Entity Bean
  • Since an Entity Bean represents data, each
    instance must have a unique identifier - a
    Primary Key.
  • This key must be serializable so it can be
    stored. Typically, a primary key class will be
    created, and each bean will use this class as
    their key (instead of just using a String or
    Integer object class)public class custPK
    implements serializable public int custId

23
Creating An Entity Bean
  • How the ejb Server deals with bean uniqueness
    depends on whether you establish your Entity Bean
    as Container or Bean Managed Persistence
  • Container Manager will leave the actual retrieval
    updating of the data store to the server. Bean
    developers do not code an JDBC.
  • Bean Managed will leave all SQL/JDBC code up to
    the bean developer. Including finding beans.

24
Creating An Entity Bean
  • Once a Primary Key is established, if the bean is
    managing its own persistence, the developer will
    need to overwrite methods in the Home interface.
  • Minimally, the findByPrimaryKey() is needed. This
    may be a simple SQL statement against an RDBMS.
    Another common method is findByName. Or custom
    ones - findByCustomerId.

25
Creating An Entity Bean
  • Much of the Session Bean methods are also used
    for Entity Beans, such as the ejbCreate(). and
    ejbRemove().
  • Others are specific for persistence, such as
    ejbStore() and ejbLoad() - used for saving or
    retrieving data from the store (or database).

26
Creating An Entity Bean
  • When developing an Entity Bean, the same
    methodology to Session Beans are used. Develop
    the
  • Remote Interface
  • Home Interface
  • Entity Bean
  • Plus, some additional classes/methods
  • Primary Key class
  • ejbStore/Load/FindBy for Bean Persistence

27
Entity Bean Design
  • Entity beans should be coarse-grained. Not every
    individual object should be a separate entity
    bean. This would create too much network traffic.
    For instance, each cell or row in a spreadsheet
    shouldn't necessarily be a separate entity bean
    (even though each row may be an individual row in
    a database). An entity bean may be an
    individual's credit report or financial report
    (with many rows).
  • Entity beans should also contain a certain amount
    of business logic that is encapsulated in the
    bean, so the client developers don't have to
    worry about it. If ejb's are used just to access
    and retrieve data, then it's better to use a
    Session bean.

28
Container Managed Persistence
  • First, decide on the Primary Key
  • public class CartPK implements java.io.Serializabl
    e
  • public String cartName

29
Container Managed Persistence
  • Next, define the Remote Interface
  • public interface ShoppingCart extends EJBObject,
    Remote
  • public void addItem(String item) throws
    RemoteException
  • public Object getItems() throws
    RemoteException

30
Container Managed Persistence
  • Define the Home Interface used to create and/or
    find individual beans (shop. carts)
  • public interface ShoppingCartHome extends EJBHome
  • ShoppingCart create(String name) throws
    CreateException, RemoteException
  • ShoppingCart findByPrimaryKey(CartPK key)
    throws RemoteException,FinderException

31
Container Managed Persistence
public class ShoppingCartBean implements
EntityBean transient protected
EntityContext context transient boolean
isModified public Vector items public
String cartName public void
ejbActivate() public void ejbRemove()
public void ejbPassivate()
public void ejbLoad() // container
implemented public void ejbStore() //
container implemented
32
Container Managed Persistence
  • ejbCreate methods for a bean will first create a
    primary key from the PK class
  • isModified will be used by the server to decide
    if the data store should be updated
  • public CartPK ejbCreate(String nm)
  • CartPK pk new CartPK()
  • pk.cartName nm
  • cartName nm
  • return pk
  • public boolean isModified()
  • return isModified

33
Container Managed Persistence
public void addItem(String item)
if(items null) items new
Vector() isModified true
items.addElement(item) public
Object getItems() if(items
null) items new Vector()
Object retVal new
Objectitems.size() items.copyInto(retVa
l) return retVal
34
Bean Managed Persistence
  • When developers code their own data store
    procedures, the bean code itself will be
    enhanced, but the Interface classes may not
    change.
  • The following methods will be overwriten in the
    Entity Bean code
  • ejbRemove()
  • ejbLoad()
  • ejbStore()
  • ejbFindByPrimaryKey()

35
Bean Managed Persistence
public void ejbLoad() throws RemoteException
File file fileForCartName(cartName)
if((file ! null)(cartName ! null))
if(file.exists())
FileInputStream fileIn
ObjectInputStream objIn
fileIn new
FileInputStream(file) objIn
new ObjectInputStream(fileIn)
items
(Vector)objIn.readObject()
objIn.close()
else if(items null) items
new Vector()
36
Bean Managed Persistence
public void ejbRemove() throws RemoteException
File file fileForCartName(cartN
ame) if((file !
null)(cartName ! null))
if(file.exists())
file.delete()

37
Bean Managed Persistence
public void ejbStore() throws RemoteException
if(!isModified()) return File
file fileForCartName(cartName)
if((file ! null)(cartName ! null))
if(file.exists())
FileOutputStream fileOut
ObjectOutputStream objOut
fileOut new
FileOutputStream(file)
objOut new ObjectOutputStream(fileOut)

objOut.writeObject(items)
objOut.close()
38
Bean Managed Persistence
public CartPK ejbFindByPrimaryKey(CartPK pk)
File file null String ctName
null CartPK retVal null
if(pk ! null) ctName pk.cartName
if(ctName ! null) file
fileForCartName(ctName)
if((file ! null) (ctName ! null)
(file.exists()))
retVal pk cartName ctName
else // ERROR - ("Couldn't locate
bean.") return retVal
39
Entity Bean Clients
public class ShoppingCartClient ShoppingCart
cartnull CartPK pk Object items
ShoppingCartHome home (ShoppingCartHome)
ctx.lookup("beancart.ShoppingCartH
ome") pk new CartPK()
pk.cartName JonsCart try
cart home.findByPrimaryKey(pk)
catch(Exception exp) cart home.create(testStr
) cart.addItem(pizza) cart.addItem(beer
) cart.addItem(coke) // end of class
40
Rules For Entity Bean Development
  • Most rules from Session Bean development, such as
    non-abstract classes, and implementation of
    Interfaces, apply here - plus
  • Must define a Primary Key (and should have a
    class)
  • ejbCreate should must be implemented with the use
    of the primary key.
  • Bean Managed ejbs must implement all necessary
    classes for the data store, including Find
    methods.
Write a Comment
User Comments (0)
About PowerShow.com