Mwt Unit III

download Mwt Unit III

of 16

Transcript of Mwt Unit III

  • 8/9/2019 Mwt Unit III

    1/16

    Deployment

    April 27, 2008 at 2:21 pm (EJB, Unit 3) (EJB)

    Deployment

    PermalinkLeave a Comment

    EJB Clients

    April 27, 2008 at 2:19 pm (EJB, Unit 3) (EJB)

    EJB Clients

    PermalinkLeave a Comment

    Deployment

    April 22, 2008 at 3:52 am (EJB, Unit 3)

    Deployment

    1. Must include the names of the home interface, remote interface, and implementation

    class.2. Set the isolation level and transaction attribute for the bean.3. Deployment Descriptor must be of type javax.ejb.deloyment.EntityDescriptor4. Include the name of the primary key class.5. Provide the list of container-managed fields6. Must specify whether the bean is reentrant or not.7. Provide a description for the finder methods, so that the deployer can use the container to

    generate them.

    BEA Weblogic usesfindByCustID(), custom finder method, as follows:

    findByCustID(int cusidnum) (=custid $custidnum)

    This method takes one integer argument calledcustidnum. The expression (=custid $custidnum) is a prefix-notation expression that indicates that

    the method should return all instances where the database column that maps to the fieldcustid matches the argument of the finder method exactly.

    PermalinkLeave a Comment

  • 8/9/2019 Mwt Unit III

    2/16

    Entity Bean Life Cycle

    April 22, 2008 at 3:49 am (EJB, Unit 3)

    An entity bean can have only three states:o Non-existenceo Pooledo

    Ready Non-existence

    o In this state, the bean doesnt exist.o A bean leaves this state and enters the polled state when it is added into the pool

    by the container, at which point newInstance() and setEntityContext() areinvoked on it.

    o It enters the state of non existence when the container removes it from the pool, atwhich point unsetEntityContext() andfinalize() are called on it.

    Pooled stateo In this state, entity beans have no identity. So all are identical.

  • 8/9/2019 Mwt Unit III

    3/16

    o When an ejbFind() method is invoked, the container uses an EJB instance fromthe pooled state to handle the request.

    o A bean transitions from the poled state to the ready state when one of two things

    happen: The container selects the instance to handle an ejbCreate() request, at

    which point ejbCreate() and ejbPostCreate() are invoked on the object. The container selects the instance to be activated, at which point

    ejbActivate() is invoked on the instance.o The ejbPostCreate() method takes the same arguments as the ejbCreate() method.

    It is invoked only after ejbCreate() has reached completion successfully.o ejbPostCreate() coded to perform any special processing needed after the beanis

    created, but before it becomes available to the client.o A bean transitions from the ready state to the pooled state when one of two things

    happens: The container selects the instance for passivation at which point

    ejbPassivate() is called on the object. The client invokes a remove() method on the instance, at which point the

    instances ejbRemove() method is invoked.o When a bean returns to pooled state, it once again loses its identity and becomes

    one of several available instances in the pool. Ready State:

    o In this state, beans accept invocations of its business methods. It can also processinvocations of its ejbLoad() and ejbStore() methods.

    o The container keeps the state of the bean with its representation in the database.o ejbLoad() reads data from the database and uses it to popular instance variables,

    and ejbStore() writes data from the instance variables to the database.o When a bean is activated, the container automatically invokes its ejbLoad()

    method.o Similarly, before the bean becomes passivated, its ejbStore() method is invoked.o So, no logic needed in the ejbActivate() and ejbPassivate() to handle state

    synchronization between the objectand the database. Reentrant Instances

    o It is possible, in narrow circumstances, to make an entity EJB reentrant.o This situation occurs when the entity bean uses another entity bean as a client, and

    the remote entity bean must perform a callback parent bean.

    Key points:

    All entity beans must provide afindByPrimaryKey() method in their home interface.Clients use thisfinder methodto locate existing entity beans based on their primary key.

    The implementation details of the finder methods also vary depending on whether the

    bean has bean-managed or container-managed persistence. If the bean has bean-managed persistence the developer must implement a finder method

    that is declared in the home interface.

  • 8/9/2019 Mwt Unit III

    4/16

    If the bean has container-managed persistence, the container will provide

    implementations of the finder methods; developers need not to implement them. The container can easily generate an implementation of the findByPrimaryKey() method,

    because it know exactly what it needs to do and receives the primary key class. getEJBObject() returns a reference to the Entity beans EJBObject. getPrimaryKey() returns an object that contains the primary key for this Entity Object. In the client side, each method invocation must perform the following tasks

    o Serialize all arguments on the client side.o Transmit the arguments to the servero Deserialize the arguments on the servero Invoke the remote methodo Serialize the return value on the servero Transmit the return value to the cliento Deserialize the return value on the client side.

    PermalinkLeave a Comment

    Primary Keys

    April 22, 2008 at 3:46 am (EJB, Unit 3)

    Primary Keys

    Each entity bean instance has an associated primary key.

    Logically, a primary key is a value or combination of values that allows you to uniquelyspecify a row of data.

    In EJB, the primary key is represented by a Java class that contains whatever unique dataare necessary to lookup a particular entity EJBs.

    Example:

    pubic class CustomerPK implements java.io.Serializable

    {

    public int custid;

    }

    According to the EJB specification, a primary key class must implement thejava.io.Serializable interface.

    This class simply carries the value for the primary key from the client to the server. The server inspects the class and uses the values it contains to perform a database lookup

    for the object of the requested primary key. If two entity beans have the same home interface and the same primary key, they are

    considered to be identical.

  • 8/9/2019 Mwt Unit III

    5/16

    PermalinkLeave a Comment

    BMP and CMPApril 22, 2008 at 3:44 am (EJB, Unit 3)

    Bean Managed and Container-Managed Persistence

    There are two types of entity beans:o Entity beans with bean-managed persistenceo Entity beans with container-managed persistence

    An entity bean with bean-managed persistence contains code that updates the underlyingdatabase.

    An entity bean with container-managed persistence contains no such code; instead, it

    relies on the container to update the database as necessary. This is simpler to implement but require a high degree of functionality from their

    container. Beans with bean-managed persistence are slightly more complex to implement, but do

    not require extra support from the container.

    PermalinkLeave a Comment

    When to use Entity Beans

    April 22, 2008 at 3:38 am (EJB, Unit 3)

    Entity Beans

    When to use Entity Beans:

    To understand entity beans, a brief recap of session beans is helpful. Session beans

    are:o Intended to be used by a single client.o Relatively short-lived they are intended to last for the duration of the

    clients session with the server.o

    Not able to survive a server crasho Capable of interacting with shared data in a database.

    Entity beans by contrast,o Can be used concurrently by several clientso Are relatively long-lived they are intended to exist beyond the lifetime of

    any single cliento Will survive a server crash.o Directly represent data in a database.

  • 8/9/2019 Mwt Unit III

    6/16

    Concurrent use by Several clientso More than one client will have access to the bean concurrently. o Although the clients all think that theyre accessing the bean freely, in reality

    this interaction is interposed by the container so as to guarantee the integrity

    of the database.o A container may interpose on client interactions with an entity bean in two

    ways to guarantee database integrity. The guarantee can directly interpose, queuing client request and

    allowing only one request at a time to be executed. The container can create an instance of the bean for each client that

    wishes to use it, and then allow the underlying database to deal with

    synchronization issues. Long lifetime:

    o Entity beans represent data in an underlying database. Therefore, theirlifetime matches the lifetime of the underlying data itself.

    o Entity EJBs may continue to exist for days, months or even years.o No upper limit exists on the lifetime of entity EJBs and they can be removed

    in only two ways: A client explicitly invokes the remove() method on the beans remote

    interface or home interface. Someone deletes the beans data from the underlying database.

    o Another interesting fact about an entity beans lifetime is that an Entity beandoes not necessarily need to provide a create() method, a client will bet be

    able to create new entity EJB via the beans home interface.o Nevertheless, one can create a new entity EJB by directly inserting a row of

    data into its underlying database.o Even without a create() method, a client can still obtain a reference to an

    existing Entity EJB by using one of its finder methods. Survival of Server Crashes:

    o The session bean could be irrevocably destroyed in three ways: The client connection to the bean can timeout The server can be restarted The server can crash

    o None of these three problem applies to entity beans: There is no timeout period associated with entity beans. Entity beans are guaranteed to survive an orderly server restart. Entity beans are guaranteed to survive a server crash.

    Direct representation of data in an underlying database:o Typically an entity bean maps directly to a row in an underlying database. o For example, a table called CUSTOMERS with the following columns:

    An integer called CUST_ID that represents a unique ID for each

    customer. A string called CUST_NAME that contains the customers name. A string called CUST_ADDR that contains the customers address.

    o Now an entity bean called Customer can be created that contains three

    instance variables:

  • 8/9/2019 Mwt Unit III

    7/16

    Cust_id Cust_name Cust_addr

    o These variables map directly to the columns in the underlying CUSTOMERS

    table.o A client application can then interact with the customer EJBs to modify these

    fields, update the underlying database, or perform any other business logicnecessary on the customer object.

    PermalinkLeave a Comment

    Transaction Isolation Levels

    April 22, 2008 at 3:32 am (EJB, Unit 3)

    Transaction Isolation Levels:

    This allows to specify a bean how much or how little of other transactions can beviewed during the course of its own transaction execution.

    An inverse relationship exists between higher levels of isolation and the level of

    concurrency. That is, an application that requires a high degree of isolation must

    maintain more locks for a longer period of time than an application for which a

    lower degree of isolation is acceptable. Two programs attempting to simultaneously access a database can have essentially

    three types of problem interactions.o Transaction A modifies a row; transaction B reads it; transaction A does a

    rollback and the row disappears. This situation is called dirty read.o Transaction A reads a row; transaction B modifies the row; transaction A

    reads the row again and sees a different value. This case is called a non-

    repeatable read.o Transaction A selects a set of rows that satisfy a given search condition;

    Transaction B inserts rows that satisfy the same condition. If transaction A

    executes the same query again, it will receive additional data. This situationis called a phantom read.

    Four levels of transaction isolations are possible:o TRANSACTION_READ_UNCOMMITTED Permits dirty reads, non-

    repeatable read and phantom reads.o TRANSACTION_READ_COMMITTED Permits only non-repeatable

    reads and phantom reads.o TRANSACTION_REPEATABLE_READ Permits only phantom reads.o TRANSACTION_SERIALIZABLE does not permit any of these situations

    to occur.

    PermalinkLeave a Comment

  • 8/9/2019 Mwt Unit III

    8/16

    Transactions and EJB

    April 22, 2008 at 3:29 am (EJB, Unit 3)

    Transactions and EJB

    Table shows the various transaction specifiers, illustrating which transaction is in effectin various situations.

    The table includes two rows for each type of transaction support. The first row indicates what occurs if the client calls the bean without a transaction

    context; the second row indicates what happens if the client calls the bean with atransaction in effect.

    Transaction Attribute Clients TX Beans TX

    TX_NOT_SUPPORTEDNone None

    T1 None

    TX_REQUIREDNone T2

    T1 T1

    TX_SUPPORTSNone None

    T1 T1

    TX_REQUIRES_NEWNone T2

    T1 T2

    TX_MANDATORYNone Error

    T1 T1

    TX_NOT_SUPPORTED means that the bean should never be called within a transactiono If a client calls the bean without a transaction in effect, the bean method is

    invoked.o If the client calls the bean while the client has a transaction in effect, the container

    suspends the clients transaction temporarily, invokes the bean method, and afterthe method has finished executing resumes the clients transaction.

    TX_REQUIRED means that the beans methods must always be invoked within atransaction.

    o If the client does not currently have a transaction in effect, the container creates anew transaction, invokes the method within the transaction, and then terminatesthe transaction prior to returning to the client.

    o If the client does have a transaction in effect, it serves as the transaction contextfor the beans method invocation.

    TX_SUPPORTS means that the bean can be invoked in a client supplied transactioncontext.

  • 8/9/2019 Mwt Unit III

    9/16

    o If the client does not supply a transaction context, it invokes the beans methodwith no transaction context.

    o If the client supplies a transaction context, this context is used as the transaction

    context for the beans method. TX_REQUIRES_NEW means that the beans method must always be invoked in a new

    transaction context.o If the client has not supplied a transaction context, the EJB container creates a

    new one.o If the client has supplied a transaction context, the EJB container creates a new

    one anyway, suspending the clients transaction context until the beanstransaction has been completed.

    TX_MANDATORY means that the client is required to supply a transaction contexto If the client attempts to invoke a TX_MANDATORY bean without a transaction

    context, the container will throw a TransactionRequiredException to the client.o If the client supplies a transaction context, the bean will use this context to invoke

    the method.

    TX_BEAN_MANAGED is a bit of a special case:

    Clients TX Instances Current TX TX Used by method

    None None None

    T1 None None

    None T3 T3T1 T3 T3

    In the first case, neither the client nor the bean has a transaction context open. Thebeans method is therefore invoked without a transaction context.

    In the second case, the client has a transaction context open, but the bean doesnot. The clients transaction is suspended, and the bean is invoked with notransaction context.

    In the third case, the client has no transaction context open, but the bean does. Thebeans method is invoked in its own transaction context.

    In the fourth case, the client has a transaction context open, as does the bean. The

    clients transaction is suspended, the method is invoked in the beans transactioncontext, and the clients transaction context is resumed after the methodcompletes.

    TX_BEAN_MANAGED transaction also differs depending on whether the session beanis either stateful or stateless:

    o A stateful bean can maintain an open transaction across method invocations. Thatis, it can open a transaction in one method, respond to several method invocationswithin that transaction, and then close the transaction in yet another method. In

  • 8/9/2019 Mwt Unit III

    10/16

  • 8/9/2019 Mwt Unit III

    11/16

    Even though the client invokes create() and remove(), these methods do not necessarilyresult in an actual instance being created or removed in the container.

    The container will maintain a pool of stateless beans. This pool will be large enough to

    ensure that any client that needs to invoke a method receives an instance. The system administrator will normally set the number of stateless session beans in the

    instance pool, adjusting this number as necessary to provide the required level of service. A container might also manage the pool of instances itself, creating and removing

    instances as necessary to serve the current client load.

    newInstance() Allocates space for the bean and brings it into existence. setSessionContext() Gives the bean a SessionContext ejbCreate() Allows the bean to perform any necessary initializations. Because stateless beans have no state, they can be reused by many clients in the course of

    their existence. A stateful session bean can implement any of several ejbCreate() methods that take

    different sets of arguments.

    Only one of the available ejbCreate() methods will be invoked at creation time, however. Once the ejbCreate() method executes the bean enters the method ready state. It remains in this state as long as only non-transactional methods are invoked on it. Three transitions out of this state are possible.

    o The bean can enter a transactiono It can be passivatedo It can be removed.

    The bean enters a transaction if one of its transactional methods is invoked. (shouldcontain transaction declaratory TX_BEAN_MANAGED, TX_REQUIRED,TX_REQUIRES_NEW, TX_MANDATORY, for TX_SUPPORTS caller should have atransaction)

  • 8/9/2019 Mwt Unit III

    12/16

    If the bean implements the SessionSynchronization interface, the container invokes itsafterBegin() method to notify it that it is entering a transaction.

    The bean then moves to the method-ready in transaction state, where it remains until

    the transaction concludes. If the transaction was created specifically for the method invocation, the bean will exit

    the method-ready in transaction state immediately. For the TX_BEAN_MANAGED, the bean remains in this state until a commit or

    rollback occurs. If a commit occurs while the bean is in the method-ready in transaction state, the

    beforeCompletion() method of the SessionSynchronization interface is invoked with aboolean value of true as the argument.

    This sequence of invocations allows the bean to perform any database updates, before thetransaction commits, and provides it with definitive notification that the transaction hassuccessfully committed. After these methods finish the bean returns to the method-

    ready state. On the other hand, if a rollback occurs while the bean is in the method-ready in

    transaction state, beforeCompletion() is not invoked; rather afterCompletion is invokedwith a boolean argument of false.

    If the bean is in the method-ready in transaction state, dont attempt to call the bean ina different transaction context, this will lead to an error state.

    When the bean is passivated, the container invokes its ejbPassivate() method and thenwrites it out to some type of persistent storage; it also removes the bean from memory.

    A bean in the method-ready in transaction state cannot be passivated; only beans in themethod-ready state are subject to passivation.

    If the bean have opened any database or socket connections from the ejbCreate() method,the code should included in the ejbPassivate() method to close these connections.

    A bean cannot maintain open database or socket connections when it is passivated. These connections are reestablished again when the beans are activated. The final transaction is out of the method-ready state is caused by the removal of the

    bean. Unlike stateless session beans, stateful session beans are actually removed by the

    container in response to a clients call to the remove() method on the beans remoteinterface.

    Before removing the bean, the container calls the beans ejbRemove method, which givesit one last opportunity to write out database updates before it passes out of existence. This

    will close all the opened database and socket connections. After ejbRemove() has executed, the bean is destroyed and cannot be resurrected

    Session Beans Constraints

    April 22, 2008 at 3:13 am (EJB, Unit 3)

    Session Beans Constraints

  • 8/9/2019 Mwt Unit III

    13/16

    Session beans disappear from the server, ifo The session beans timeout value expireso The server crashes and is restartedo The server is shutdown and restarted

    If any of these event occurs, state information of the bean is lost.

    Solutions:

    1. Session timeout value is configurable so the timeout value can be increased.2. Server crashes and restarts are fairly rare events.

    1. The user can be notified that non-recoverable error has occurred and ask theuser to try again later.

    2. A copy of the state of the bean can be cached at the client side and a new beancan be recreated in the event of original bean dies.

    3. Use a database on the server side to hold the state of the clients conversation. Ifthe session bean dies during the conversation, the client can reconnect and passin a unique customer identifier to query the database to retrieve whatever stateinformation was saved prior to the failure of the session beans.

    A session beans state is not transactional. If the internal state of the bean is

    modified, the rollback will not affect the session beans internal state.

    Solution:

    The session beans state should be reset manually to whatever it was before thetransaction began.

    A stateless session bean cannot implement the SessionSynchronization interface.Because stateless session beans lack a conversational state and cannot hold a

    transaction across method invocations. The final constraint on session beans is that they are not reentrant. If one thread is

    currently using a session bean, the container will throw a java.rmi.RemoteExceptionin response to any other requests to connect to the session bean.

    PermalinkLeave a Comment

    Constraints on Beans

    April 22, 2008 at 3:08 am (EJB, Unit 3)

  • 8/9/2019 Mwt Unit III

    14/16

    Common Constraints for all beans:

    EJB cannot start new threads or use thread synchronization primitives.o Container is responsible for creating and managing new bean instanceso EJB beans are not allowed to spawn threads themselves, but the container

    can run multiple beans concurrently.o This prevention is needed not to interfere the containers management of its

    beans EJB cannot directly access the underlying transaction manager

    o Because the container has the responsibility for managing transactions.o If bean declares its transaction management as TX_BEAN_MANAGED, is

    allowed to use a javax.jts.UserTransaction to manage the state of its owntransaction.

    The bean cannot use the JDBC commit and rollback primitives.o This constraints exists because the container is responsible for issuing the

    commit and rollback instructions for transaction-enabled beans.o A bean with a transaction attribute of TX_NOT_SUPPORTED, however,

    can use JDBC commit or rollback, because no external transaction manager

    exists. Beans are not allowed to change theirjava.security.Identityat runtime.

    o The identity is typically set up at deployment time by the systemadministrator

    o Runtime changes are disallowed to prevent malicious beans from acquiring

    unintended privileges. EJB cannot have read/write static variables. But static final variables are allowed.

    PermalinkLeave a Comment

    When to Use Session Beans?

    April 22, 2008 at 3:04 am (EJB, Unit 3)

    The EJB 1.0 specification requires support for session beans. EJB 2.0 specification requires support for Entity Beans Few EJB containers will not implement support for entity beans.

    When to use Session Beans?

    Session beans are intended to allow the application author to easily implement portions ofapplication code in middleware and to simply access to this code.

    Entity beans are essentially a transactional object persistence mechanism; when you needto save the objects state to persistent storage.

  • 8/9/2019 Mwt Unit III

    15/16

    PermalinkLeave a Comment

    EJB Development Considerations and StepsMarch 5, 2008 at 3:48 pm (EJB, Unit 3) (EJB)

    The steps to developing EJBs can be partitioned along two main lines: server-side and client-sidedevelopment. Although server-side development of distributed communications servers, such as CORBA andRMI, takes on a somewhat-complicated nature at times, server-side development of EJBs is simplified becausemuch of the communications, state management, resource allocation, and thread management infrastructurecoding is provided by the container. These are the main steps employed for server-side EJB development:

    1. Implement EJB standard interfacesAny interfaces requiredby the standard EJB component model to enable container-based management of the EJB should beimplemented.

    2. Implement EJB business-specific interfacesAny business-specific interfaces provided by your EJB and any supporting helper and utility classes should beimplemented.

    3. Create client remote interfacesThe remote interface foryour EJB that defines all business-specific interfaces to the EJB should be created.

    4. Create client home interfacesThe home interface for yourEJB that defines the application-specific methods for creating your EJB, as well as application-specificmethods for finding your EJB (if it is an entity bean), should be created.

    5. Compile EJB codeThe EJB implementation, home interface,and remote interface should be compiled.

    6. Configure module deployment descriptorsThe standardEJB deployment descriptor should be configured to define the specific structural characteristics anddependencies of your EJB. Any deployment descriptors needed by your container/server provider shouldalso be configured.

    7. Package EJB into an EJB JAR moduleThe standard EJBdeployment descriptor, any vendor-specific deployment descriptors, and one or more of your compiled EJBclass files should be packaged into an EJB JAR module.

    8. Configure application deployment descriptorA standardJ2EE deployment descriptor should be configured for a cohesive collection of J2EE modules.

    9. Package EJB Modules into a J2EE EAR ApplicationThestandard J2EE deployment descriptor and one or more EJB JAR files should be packaged into a J2EEEAR application.

    10. Deploy the J2EE applicationThe J2EE EAR applicationshould be deployed to a J2EE-compliant application container/server environment.

    On the client side, clients must simply be designed to utilize the proper EJB client interfaces andlibraries. EJB client development proceeds along the following lines:

  • 8/9/2019 Mwt Unit III

    16/16

    1. Standard client library verificationThe proper EJB clientlibraries must be established.

    2. EJB client interface generationThe properly compiledinterfaces and stubs specific to a particular EJB must also be provided to an EJB cl ient.

    3. Client implementationThe EJB client may be implementedto utilize any interfaces as appropriate.

    4. Client code compilationThe EJB client code should becompiled.

    5. Configure application client deployment descriptors(optional)Any standard J2EE application client deployment descriptor should be configured to define thespecific configuration properties of your EJB client.

    6. Package client into application client JAR (optional)Thestandard J2EE application client deployment descriptor and compiled EJB client class files should bepackaged into a J2EE application client JAR.

    7. Launch the J2EE application client (optional)The J2EEapplication client may be launched within a special J2EE application client container environment.