Top Banner

of 93

A Practical Approach to EnterPrise Java Beans_site

Apr 05, 2018

Download

Documents

Gaurav Agarwal
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    1/93

    Kantimahanti Prasad

    BY

    The Heart of J2EE

    EJB

    [email protected] or [email protected]

    Copyright 2004 Kanti Prasad All rights reserved

    IN 30 MINs

    A Component Technology

    A Practical Introduction to

    Enterprise Java BeansDO YOU WANT

    TO ANSWER MOSTOF THE

    EJB QUESTIONS ?

    THEN LET MEHELP YOU!

    mailto:[email protected]:[email protected]:[email protected]:[email protected]
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    2/93

    A STAR or adifferent color

    represents

    importantpoints to NOTE

    1. Learning objectives

    1. Component Technology characteristics

    2. Standard Infrastructure needs

    3. Application Servers

    4. Containers

    5. J2EE Architecture and its components6. EJB Model, Overview & JNDI

    7. EJB Specifications, Roles

    8. EJB Design Approaches, Architecture

    9. Types of Beans

    10. EJB Interfaces & Session Contexts11. Life cycles of different Beans

    12. EJB Jar files & Deployment Descriptor

    13. Sample examples

    14. Components comparison

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    3/93

    2. About the AuthorKantimahanti.N.S.Prasad

    Worked in fortune 100 Corporates in Client Server Technologies.

    Specializes inArchitecture, Designing, Development & Managing day-to-day activities.

    Presently doing a PhD at Queens Uty, U.K in Adaptable Software specific toComponent Technologies and has a M.B.A(Computer Applications) from an U.S. Uty.

    Business domain strengths are in Investment banking & Insurance.

    Process improvement strengths are in 6 - Sigma and CMM.

    His present & past working experiences in various global locations are in corporates likePramerica (Prudential U.S), J P Morgan Chase, A B N Amro Bank & SGS.

    He was a part time visiting faculty in affiliates of Sydney University, Australia and All India ManagementInstitute teaching I.T, Project Management & Statistics. He has given some presentations on ProjectManagement and TQM at various venues. He has won few Talent/STAR performance awards and playsalmost all the sports what are under the Sun.

    He hails from Vizag/ Hyderabad India. His 3rd party tested Temperament Sorter results are belowhttps://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606

    If you liked his presentation, tell others and if you have a comment, tell him. He can be reached [email protected] or [email protected]

    U NEVER

    FAIL

    TILL U QUIT

    https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606mailto:[email protected]:[email protected]:[email protected]:[email protected]://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresultc.asp?TID=740281662156&PID=13606https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800https://www.advisorteam.com/temperament_sorter/testresult.asp?TID=740281673499&PID=15800
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    4/93

    3. Thank you note

    He wishes to thank Paul Perrone , Paulo Merson & Ramesh Behra for making

    this tutorial look the way it does.

    He wishes to thank Joerg Mueller, Muruganandam, CharlesJohnson & VenuGadium who had volunteered to do the editing of this presentation.

    his Sisters

    Thank you for downloading my Presentation

    Special thanks to all his Managers at Pramerica and Prudential U.S.

    & his Cousinshis BrothersDr.Rao &Family

    his ParentsSADHGISUNAYANA

    ARUNA

    DEDICATED TOCopyright 2004 Kanti Prasad All rights reserved

    He wishes to thank to Katherine Ballantyne, Choi Kwan who volunteers toedit all of his Articles & Presentations.

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    5/93

    4. Component Technology

    Components are deployable units that provide a

    business service to their clients.

    Each component provides an interface in the form of operations,properties and events

    Components can be developed in any language such as JAVA,C++,VB

    Components are frequently organized into application frameworks for

    vertical domains Component models such as Active X and EJB standardize

    communication and allow for prebuilt purchased components

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    6/93

    5. Component Characteristics

    Properties Reusability

    Operations Shareable

    Events Distributable

    Deployable Self Containment

    Self description

    Components Characteristics include

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    7/93

    Components should have a mechanism for exporting

    6. Component P O E

    Properties

    Operations

    Events

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    8/93

    7. Deployable Components

    Components are operation independent of

    Hardware

    The underlying operating system

    Their Application Server

    The network protocol they use

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    9/93

    8. Reusable Components

    Component services can be used as a part of

    business logic of other components

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    10/93

    9. Shareable Components

    If multiple clients are using a component

    simultaneously, the component will provide

    the same quality of service to all the clients

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    11/93

    10. Distributable Components

    Components should provide services to clients

    running locally or remotely

    RemoteCLIENTS

    EJB Container

    EJB

    Possible

    RemoteCLIENTS

    RemoteCLIENTS

    RemoteCLIENTS

    LocalCLIENTS

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    12/93

    11. SelfContained Components

    Components should only contain the code

    necessary to implement their services

    Infrastructure services should be injected by

    the execution environment

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    13/93

    12. Standard Infrastructure Needs

    Standard infrastructure services include

    Directory Services Distributed transaction management

    Security management

    Concurrent access management

    Persistence management

    Resource pooling (e.g. DB connections) Administration interface

    Load Balancing

    Fault tolerance

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    14/93

    13. Applicatoin Servers

    An application server provides the infrastructure and

    services to run components/applications

    J2EE

    basedsolutions

    Non-J2EEsolutions

    (PHP, Cold Fusion,Perl, etc.)

    Microsoft Solutions

    (COM, ASP.NetVB.Net,C# etc.)

    Application Server products are mostly

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    15/93

    14. Object Pooling

    An application server may create a pool of bare objects

    that may be used as EJBs when requests are made

    App Server

    EJB Container

    CLIENT

    NetworkDB

    CLIENTEJB

    EJB

    EJB

    EJB

    EJB

    EJB

    Pool

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    16/93

    15. Directory of Application Servers

    Application Servers provide clients access to software orother applications that run only on the server

    Examples include web servers, e-mail servers and database servers

    Popular Application Servers are:

    I.B.M. Web Sphere

    BEA Web Logic

    Sun Java System Application Server 7.x

    Jboss

    The full list with vital statistics are available at

    http://www.devx.com/enterprise/html/16268

    http://www.javacommerce.com/articles/serverlist.htm

    Copyright 2004 Kanti Prasad All rights reserved

    http://www.devx.com/enterprise/html/16268http://www.javacommerce.com/articles/serverlist.htmhttp://www.javacommerce.com/articles/serverlist.htmhttp://www.devx.com/enterprise/html/16268
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    17/93

    Container provides System services like

    App Server

    CLIENT

    NetworkSTUB

    Persistence Security Connection Pooling ThreadingTransaction

    EJB Container

    EJB

    Fish cannot survive outside water &EJBs cannot survive outside containers

    Containerinterceptsrequests

    Copyright 2004 Kanti Prasad All rights reserved

    Container knows what to do, as you describe everything in a special descriptor file

    A Container : provides the environment in which a bean executes

    generates Home Object

    generates EJB Object

    manages individual bean instances

    EJB

    EJB

    &

    Container means a

    pre developed Software

    To increase capability.

    clustering is taken care

    by the vendor

    Implicit Middleware

    gained through declaration

    16. Container

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    18/93

    17. J2EE Overview

    Hardware Platform

    Operating System Platform

    J2EEContainer/Server

    Operating SystemIndependence

    Hardware Independence

    Common ProgrammingServices

    Distributed Communication

    Services

    J2SE RuntimeJ2SE Language/Interfaces

    services standards component-based

    Enterprise Components

    Application ServerIndependence

    Database Independence

    Web Server Independence

    Enterprise ResourceManagement Services

    Deployment/Configuration

    Management ServicesJ2EE Interfaces

    Data

    DeploymentDescriptors (DDs)

    DeployTools

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    19/93

    J2SE

    Application ClientContainer

    DBSAAJ

    JAX-RPC

    CONJMX

    JMS

    WEBS

    JAXR

    JDBC

    MgmtDAO

    Client

    J2SE

    SAAJ

    JAX-

    RPC JTA

    CONJMX

    Mgmt

    JAF

    Java

    MailJMS

    J

    ACC

    W

    EBS

    J

    AXR

    J

    NDI

    J

    DBC

    AppletContainer

    J2SE

    HTTP/S

    HTTP/S

    Web Container

    JSP ServletApplet

    2 TIER

    3 TIER

    SAAJ

    JAX-

    RPC JTA

    CONJMX

    Mgmt

    JAF

    Java

    MailJMS

    J

    ACC

    W

    EBS

    J

    AXR

    J

    NDI

    J

    DBC

    EJB Container

    J2SE

    RMI/IIOP

    RMI/IIOP

    4 TIER

    EIS

    MainFrames

    EJB

    J2EE defines a model for developing multi-tier, web based,

    enterprise applications with distributed components

    18. J2EE 1.4 APIs

    For all the APIs refer http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html

    JSP Servlet ENGINE

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    20/93

    19. Enterprise JavaBeans Model

    EJB is Suns J2EE transactional, vendor-neutral,

    enterprise component architecture providing

    Modelling of business entities as well as synchronous and

    asynchronous processes

    Persistence via explicit code (bean-managed) or via services of the EJBserver (container-managed)

    Vendor neutrality and inter operability

    XML driven deployment and configuration

    Copyright 2004 Kanti Prasad All rights reserved

    JBs do not need a containerJBs are development componentsJBs are Classes with no argument constructor

    JBs have a getand a setmethod on them

    EJBs need a ContainerEJBs are deployable components

    EJBs are assembled to form a complete Appl

    EJBs are based on RMI IIOP and JNDI Technologies

    EnterpriseJava Beans != Java Beans

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    21/93

    J2EE EJB Container/Server

    20. EJB Overview

    EJBPool

    Client Process

    Delegate

    EJBClient

    DelegateDelegate

    Remoteinvoke

    Homecreateremove

    find

    Network

    EJB Impl

    createremove

    findinvoke

    timeoutpassivate

    activateloadstore

    STUB STUB

    LocalHome

    create

    removefind

    Local

    EJB Client

    invoke

    Delegate

    EJB simplified distributed developmentDevelop EJB implementation logicDefine Home/Local Remote/Local interfaces

    Container delegates client calls

    Container manages resources/lifecycle/callbacks

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    22/93

    21. When to use EJB

    If any of these requirements hold for your application

    the application must be scalable and distributable Transactions will be required to ensure data integrity

    the application will have a variety of clients

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    23/93

    22. Java Naming and

    Directory Interface (JNDI)JNDI

    Provides a standardized way of accessing resources in a distributed

    environment

    Protocol and naming service agnostic DNS

    NDIS

    LDAP

    X.500

    Implemented by the javax.naming package and three other packagesbelow it

    javax.naming.InitialContext is the entry point to the EJB Server

    bind associates a name with an object

    lookup finds an object given the name

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    24/93

    23. EJB Specification

    The EJB specification defines interfaces between

    the EJB and its container the container and the application server

    the container and the client

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    25/93

    24. EJB Roles

    Service & Tool Provider

    provides Server, Container and integrates with distributed facilities

    Tools Provider

    EJB Provider

    Application Assembler

    Application Server Provider

    Deployer System Administratormaintains deployment

    supplies tools builds application

    develops EJBssupplies Application Server

    deploys system

    EJB Providercreates EJB components

    Deployment Specialistdeploys apps and understands architecture issues

    Application Assembler

    assembles apps from per-built EJB comp

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    26/93

    25. EJB Design Approaches

    EJB model is based on three basic design approaches forbuilding distributed component systems

    Stateless server approach Session-oriented approach

    Persistent Object approach

    Copyright 2004 Kanti Prasad All rights reserved

    javax.ejb.EnterpriseBean interface

    javax.ejb.EntityBean

    The EJB specification provides these asStateless session Beans Message driven beans

    Stateful session Beans Entity Beans

    All EntityBeans All SessionBeans All MessageDrivenBeans

    extends extends extends

    implements implements implementsInterface Interface Interface

    extends

    javax.ejb.SessionBean javax.ejb.MessageDrivenBean

    Implementing one of these interfacesindicates your JAVA class is an EJB.

    It is only a marker Interfaceand there are no methods to

    Implement.

    As all these are extending thetwo Interfaces hence they have

    the behavior of both the Interfaces.Serialization is the reason

    EJB is distributable.

    java.io.Serializable

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    27/93

    26. EJB Architecture

    RMI/IIOP

    Server A

    App Server

    EJB Container

    creates

    Naming Service suchas LDAP

    Server B

    JNDI

    Initial Context

    H

    H

    1

    SERVICES

    Naming Transaction Persistence Security

    DB

    EIS

    MainFrames

    3

    2

    4 5

    6

    7

    8

    9

    10

    11

    HomeInterface

    RemoteInterfaceApplicationClient

    EJB(Business Logic Class)

    We will write only this

    delegates request

    Container manages TRANSACTIONS, PERSISTENCE, SECURITY & POOLING

    Container implements/autogenerates code for the Interfaces

    Home Object(FACTORY)

    EJB Object(Wrapper)

    HomeObj

    Stub

    EJBObjStub

    Copyright 2004 Kanti Prasad All rights reserved

    H

    H

    we have written

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    28/93

    creates EJB Object

    27. EJB Flow Chart

    C

    ask JNDI Server for the Home Object 1

    Remote Interface then wrapsa request to the Bean class

    JNDI Server returns ref of Home Stub

    ask Home for the EJB Object

    returns reference of Remote Stub

    C

    goes to the JNDI Serverand gets the EJB Object

    invokes a business methodthru Remote Stub

    Clients receives the required info

    End

    Start

    2

    3

    4

    5

    6

    7

    8

    9

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    29/93

    App Server

    EJB Container

    28. Client View of EJB

    ApplicationClient

    RMI/IIOP

    Entity Beaninstance

    EJB Home orEJB Local Home

    e.gBank account balancePurchase order

    e.gStock trade messagesWork flow messages

    e.gBank tellerCredit Card authorization

    Message DrivenBean instance

    Session Beaninstance

    Copyright 2004 Kanti Prasad All rights reserved

    ENTITY BEANS are like NOUNS as they represent data or data related logic.

    MESSAGE DRIVEN BEANS have message oriented logic.

    If all the processing is done in the same Application server then we use

    EJB Local(Object & Home) interfaces. Using local interfaces are optional.Local interfaces pass by REFERENCE and EJB (Object/Home) pass by VALUE.Using local interfaces avoids stubs, skeletons, network and so it is faster.

    EJB Object orEJB Local Object

    JMS Destination

    SESSION BEANS are like VERBS as they represent action or business process related logic.

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    30/93

    29. EJB Client

    EJB clients

    utilizes the Java Naming and Directory Interface (JNDI) to look upfor the references to home interfaces

    use home and remote EJB interfaces to utilize all EJB-basedfunctionality

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    31/93

    30. EJB Home Interface

    EJB home interfaces extends javax.ejb.EJBHome

    EJB home interfaces provide operations for clients to create EJBs remove EJBs find handles to EJB remote interface objects have its stub placed into JNDI at startup

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    32/93

    31. EJB Remote

    EJB remote interfaces extends javax.ejb.EJBObject

    EJB remote interfaces provide business-specific functionality of an EJB are similar to RMI Remote interface

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    33/93

    32. EJB Implementation

    EJB implementation

    Class in which EJB developer codes the business methodsdefined in the beans component interface(s) to provide any

    application specific

    business method invocation

    creation removal finding activation passivation, database storage database loading logic

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    34/93

    33. Session Context

    The Container has already reference to the bean

    The bean interacts with the Container through SessionContext and

    retrieves home interfaces

    gets and sets transactions attributes

    obtains security attribute

    The setSessionContext method is used to inform the bean

    about the session context

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    35/93

    34. Stateless Session EJB

    Stateless session EJBs have the following behaviour

    provide a single use service

    do not maintain state on behalf of the client

    are relatively short lived

    do not survive EJB server crashes

    any two instances of the same stateless session EJBtype are always identical

    each instance can be shared by multiple clients

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    36/93

    J2EE EJB Container/Server

    35. Stateless Session EJBs View

    EJB Impl Developer ViewEJB gets requests and generates responses

    An instance can service multiple clients over time

    EJB Client Developer View

    creates it, uses it and then its done

    EJB Container View

    can pull instances from pool upon client request

    can shrink/grow pool as needed

    A few pooled beans can service thousands of clients

    Client Process

    EJBClient Remote

    Home

    Stateless Session

    LocalHome LocalEJB Client

    Network

    Logic

    input

    outputEJB Pool

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    37/93

    Pool of equivalentmethod ready instances

    ejbRemove()

    ejbCreate()

    Bean Instancedoes not exiist

    Container decided itneeds more instancesin the pool to service clients

    Client called remove()on the EJB object(or the client times out)

    Class.newInstance()

    setSessionContext()

    Each method call is aninvocation from the

    container to the Bean

    36. Life Cycle of Stateless Session Bean

    TransactionalBusiness Method

    Client called anotherTransactional business methodon the EJB Object.

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    38/93

    J2EE EJB Container/Server

    37. Stateful Session EJBs View

    EJB Impl Developer View

    EJB gets requests and generates responses

    An instance can service multiple clients over time

    EJB Client Developer Viewcreates it, uses it and then its done

    EJB Container View

    can pull instances from pool upon client request

    can shrink/grow pool as needed

    Client Process

    EJBClient Remote

    Home

    Stateful Session

    LocalHome Local

    EJB Client

    Network

    Logic

    input

    outputEJB Pool

    State

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    39/93

    If we implement Javax.ejb.SessionSynchronization then we need towrite these methods.

    Bean instance is inthe passive state

    Bean instance is readyto service method calls

    Non-TransactionalBusiness Method

    afterBegin()

    ejbRemove()

    ejbCreate(args)

    Bean Instancedoes not exiistClient called create(args)

    on the home Interface.

    Containers limit ofinstantiated beansare reached, so it mustswap your bean out.

    Client called remove()on the EJB object

    (or the client times out)

    Client called a transactionalbusiness method on theEJB Object

    Client called anon-transactional businessmethod on the EJBObject

    Class.newInstance()

    setSessionContext()

    ejbActivate()

    beforeCompletion()

    afterCompletion(true)

    ejbPassivate()

    Each method call is anInvocation from the

    container to the Bean

    38 .Life Cycle of Stateful Session Bean

    TransactionalBusiness Method

    Client called anotherTransactional business methodon the EJB Object.

    Client called a methodon a passivated bean, soContainer must swap your

    Bean back in

    Bean instance is withina transaction and readyto service method calls

    afterCompletion(false)

    If transaction endedin an abort.

    If transaction endedin a commit..

    Client times out

    We need to write all

    the methods that

    are there in the

    Implemented class

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    40/93

    39. Stateful vs Stateless

    Copyright 2004 Kanti Prasad All rights reserved

    e.g

    An EJB that unzips 100 bytes of data

    An EJB that checks to see if a stock symbol is valid

    e.g

    An EJB that books a flight and rents a car at a travel agents

    web site.

    A stateful bean contains a conversational state that is

    retained across method calls and transactions.

    The create method takes arguments

    e.g. create(String id) , create(int I , String id)There can be one or more arguments in a create method

    A stateless bean does not have any state between calls toits methods.

    The create method does not take arguments

    e.g create()

    There can be no arguments in a create method

    Stateful Bean Stateless Bean

    Method by method comparison can be seen in EJB20Matrix.doc at http://www.volantec.biz/cmp20.htm

    http://www.volantec.biz/cmp20.htmhttp://www.volantec.biz/cmp20.htm
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    41/93

    40. Entity Bean

    Entity Bean has the following behaviour

    They are a representation of persistent data

    They can survive a crash

    Multiple clients can be using EJBs that represent thesame data

    The EJB instance contains a copy of the data in thepersistent store

    has a Primary key like in a Database record.

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    42/93

    J2EE EJB Container/Server

    Client Process

    EJBClient Remote

    Home

    Entity Bean (BMP)

    LocalHome LocalEJB Client

    Network EJB Pool

    41. BMP Entity EJBs

    EJB Impl Developer View

    encapsulates data from a data source as objects

    implements object-relational mapping (often JDBC)

    implements inserts, deletes, queries and updates

    EJB Client Developer View

    creates, finds, updates and removes entity objects

    EJB Container View

    persists and manages concurrent access of instances

    (BMP = Bean-Managed Persistence)

    data

    input

    output

    HandCodedLogic

    Persisted objects (via hand-coding)

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    43/93

    42. Primary key class

    Applicable only to entity beans

    Uniquely differentiates instances sharing the sameEJBHome

    Class must be a legal value type in RMI-IIOP Implements java.io.Serializable

    all the members should be public

    It should implement hashCode() and equals(.. ) methods

    does not implement java.rmi.remote

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    44/93

    43. Shared Entity Bean

    When multiple clients share an Entity EJB they

    receive their own instance

    share the underlying data

    do not have to handle synchronization

    App Server

    EJB Container

    CLIENT

    Network

    DB

    CLIENTEJB

    EJB

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    45/93

    ReadyejbLoad() ejbStore()

    Pooled

    Passivates the Bean

    ejbCreate()

    ejbPostCreate()

    ejbRemove()

    ejbHome() ejbFind()

    Does not exiistContainer decided itneeds anotherEntity Bean insinstance

    Container decided itdoesnt need the

    Entity Bean instanceanymore

    Client called a finderMethod on the homeinterface

    Client called remove()on the EJB object(this will destroyDatabase data)

    Container determinedthat the database is out ofsynch with the bean. TheBean needs to store itsData into the Database

    Container determinedthat the database is out ofsynch with the bean. TheBean needs to load thenew Database data.

    Client called create() onthe home interface (this willCreate new database data)

    Client called instanceindependent ejbHome()

    Business method

    Activates the Bean

    newInstance()

    setEntityContext()

    unsetEntityContext()

    JVM will garbagecollectt and call finalize()

    ejbActivate()

    ejbLoad()

    ejbStore()\

    ejbPassivate()

    Each method call is anInvocation from the

    container to the Bean

    44. Life Cycle of BMP Entity Bean

    Business Method

    Client called a businessmethod on a EJBObject

    CMP E i EJB

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    46/93

    J2EE EJB Container/Server

    Client Process

    EJBClient Remote

    Home

    Entity Bean (CMP)

    LocalHome Local

    EJB Client

    Network EJB Pool

    data

    input

    output

    GeneratedLogic

    45. CMP Entity EJBs

    EJB Impl Developer View

    specifies CMP fields and relations among entities in DDs

    specifies queries via EJB-QL in DDsuses tools to map standard object view to specific relational view

    EJB Client Developer View

    creates, finds, updates and removes entity objects

    EJB Container View

    persists and manages concurrent access of instances

    (CMP = Container-Managed Persistence)

    PersistenceDDs

    Persisted objects (via container services)

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    47/93

    ReadyejbLoad() ejbStore()

    Pooled

    Passivates the Bean

    ejbCreate()

    ejbPostCreate()

    ejbRemove()

    ejbHome() ejbFind() or ejbSelect()

    does not exiistContainer decided itneeds anotherEntity Bean in

    Container decided itdoesnt need the

    Entity Bean instanceanymore

    Client called a findermethod on the homeInterface, or beancalled its own

    ejbSelect()method to locateDatabase data

    Client called remove()on the EJB object(this will destroyDatabase data)

    Container determinedthat the database is out ofSynch with the bean. TheBean needs to store itsData into the Database

    Container determinedthat the database is out ofSynch with the bean. TheBean needs to load thenew Database data.

    Client called create() onthe home interface (this willcreate new database data)

    Client called instanceindependent ejbHome()

    Business method

    Activates the Bean

    newInstance()

    setEntityContext()

    unsetEntityContext()

    JVM will garbagecollectt and call finalize()

    ejbActivate()

    ejbLoad()

    ejbStore()\

    ejbPassivate()

    Each method call is anInvocation from the

    container to the Bean

    46. Life Cycle of CMP Entity Bean

    Business Method

    Or ejbSelect()

    Client called a businessmethod on a EJBObject

    NOTE : BMP has no ejbSelect()

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    48/93

    47. BMP vs CMP

    Copyright 2004 Kanti Prasad All rights reserved

    We should start developing CMP beans, unless we require some kind of special bean, like multi-tables, that

    cannot be completely realized with a single bean. Then when we realize that we need something more or that

    we prefer handling the persistence (performance issue are the most common reason), we can change the bean

    from a CMP to a BMP

    Method by method comparison can be seen in EJB20Matrix.doc at http://www.volantec.biz/cmp20.htm

    BMP offers a tactical approach

    The developer takes care of handling persistenceBMP uses hard coded queries so we can optimize our

    queries

    Bean Managed Persistance

    CMP is more strategic

    Vendor takes care of everything by using O-R or OODBmappings using metadata.

    A developer cannot optimize performance as the vedortakes care of it

    Container Managed Persistance

    http://www.volantec.biz/cmp20.htmhttp://www.volantec.biz/cmp20.htm
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    49/93

    48. Message Driven Bean

    MDB has the following behaviour

    Is stateless

    is a JMS listener

    when a JMS message arrives the methodonMessage() is executed

    does not survive EJB server crashes

    provides a single-use service

    is relatively short lived is only a bean class no interfaces

    Copyright 2004 Kanti Prasad All rights reserved

    49 M D i EJB

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    50/93

    J2EE EJB Container/Server

    Network

    49. Message Driven EJBs

    MessagingService

    Message

    QueueProducer Process

    Message

    Producer

    Messaging

    API

    Message-Driven Bean

    Handler Logic

    input

    MessageListener

    MessageMessage

    EJB Impl Developer View

    gets async requests via messaging paradigm-specific interface

    An instance can service multiple clients over time

    EJB Client Developer View

    Messages sent to endpoint & handled by messaging service

    Specific to particular messaging paradigm used

    EJB Container View

    pulls instance from pool and delivers message

    EJB Pool

    Asynchronous messaging

    0 Lif C l f M D i B

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    51/93

    Pooled

    ejbCreate()

    Does not exiistContainer decided itneeds anotherMessage DrivenBeanInstance

    newInstance()

    setMessageDrivenContext()

    Each method call is anInvocation from the

    container to the Bean

    50. Life Cycle of Message Driven Bean

    onMessage()

    ejbRemove()

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    52/93

    51. Deployment

    Deployment involves taking an EJB compliant bean and

    creates XML that describes the EJB

    packages the bean and XML into a Jar

    generates container files for the EJB

    configures properties of the EJB Server

    Copyright 2004 Kanti Prasad All rights reserved

    BEAN Provider declares components middleware service requirements in a DEPLOYMENT DESCRIPTOR File.

    Bean Provider describes how the Container should perform the LifeCycle Management, Persistence, Transaction and Security.

    Declaring without programming helps the application assembler to change the XML file easily.

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    53/93

    52. Other interfaces and classes

    Local interfaces are used for access within server context

    javax.ejb.EJBLocalHome

    javax.ejb.EJBLocalObject

    Interfaces for serializing EJB references

    HomeHandle - reference to EJBHome

    Handle - reference to EJBObject

    EJBMetaData interface provides mechanism to gatherinformation about the bean

    reference to EJBHome object

    Home, component interface and primary key classes

    functions to determine bean type

    E.g.:Inter component callsServlet invocation

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    54/93

    53. Exceptions

    System exceptions are unchecked and propagated to theclient as java.rmi.RemoteException

    Application exceptions are checked and propagated to the

    client as a descendant of java.lang.Exception

    EJB-specific exceptions include FinderException,CreateException, RemoteException (all in javax.ejbpackage)

    Business method exceptions are at the discretion of theEJB developer

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    55/93

    Copyright 2004 Kanti Prasad All rights reserved

    EXAMPLE 1

    STATELESS BEAN

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    56/93

    Using the Jar utility create an EJB Jarfile containing STEP 2 & STEP 3 files

    54. Steps to Develop an EJB

    C

    Write .java files for the BEAN, HOMEand REMOTE interfaces

    1

    Write the Deployment descriptor

    Compile all the STEP 1 files into.class files

    Configure your EJB Server.E.g DB connections thread pooling etc

    Then copy the EJB Jar file

    C

    Connect to your EJB by writing a testClient .java file compile it and run it .

    Start your EJB container andconfirm that it has loadedthe EJB Jar file.

    End

    Start

    2

    3

    4

    6

    7

    Copyright 2004 Kanti Prasad All rights reserved

    5

    Please download the trial Application Server software from the links provided on the Reference slide at the end.

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    57/93

    We will apply the previous slide flow chart procedure to make up our first EJB

    example

    Copyright 2004 Kanti Prasad All rights reserved

    These Interfaces comes with Java 2 Platformjava.io.Serializablejava.rmi.Remote

    These Interfaces comes with EJB distributionJavax.ejb.EJBObject Javax.ejb.EJBHome

    Javax.ejb.EnterpriseBean

    Javax.ejb.SessonBean

    Supplied by the Bean Provider / Developer/ We will write !

    Hello world Remote Interface Hello World Home Interface

    Hello World Bean

    Implementation Class

    Generated for us by the Container verdors tools

    Hello world EJB Object Hello World Home Object

    We need to CODE only this block

    55. Hello World Object Model using RMI

    NOTE : Object implementationis Vendor specific. The containermay implement eitherA single object for each client orA single object for all the clients.

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    58/93

    56. Hello World Object Model using LOCAL

    Copyright 2004 Kanti Prasad All rights reserved

    These Interfaces comes with Java 2 Platformjava.io.Serializablejava.rmi.Remote

    These Interfaces comes with EJB distribution

    Javax.ejb.EJBLocalObject Javax.ejb.EJBLocalHomeJavax.ejb.EnterpriseBean

    Javax.ejb.SessonBean

    Supplied by the Bean Provider / Developer/ We will write !

    Hello world LocalInterface Hello World Local Home InterfaceHello World Bean

    Implementation Class

    Generated for us by the Container verdors tools

    Hello world EJB LocalObject Hello World Local Home Object

    We need to CODE only this block

    If all the processing is done in the same Application server then we use EJB Local (Object & Home) interfaces.Using local interfaces are optional. Local interfaces pass by REFERENCE and EJB (Object/Home) which is the

    previous slide model you saw will pass by VALUE. As these interfaces does not extend Java.rmi.Remote theoverhead of creating stubs, skeletons,network traffic is avoided and so it is faster but the drawback is if ourcode relies on Local interfaces then we cannot call a bean remotely.

    No Network soLOCAL IMROVESPERFORMANCE

    NOTE : Object implementationis Vendor specific. The containermay implement eitherA single object for each client orA single object for all the clients.

    57 HelloBean Home Interface

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    59/93

    57. HelloBean Home Interface

    package examples ;

    import java.io.Serializable;import java.rmi.RemoteException;

    import javax.ejb.CreateException;

    import javax.ejb.EJBHome;

    public interface HelloHome extends javax.ejb.EJBHome

    {Hello create() throws java.rmi.RemoteException,

    javax.ejb.CreateException;

    }

    Copyright 2004 Kanti Prasad All rights reserved

    Rules of Java says package declaration should be at the beginning and ends with a semi colon

    This is the Home Interface for the Home EJB (HelloBean).

    This method creates/manufactures the EJBObject and returns it . This create() method corresponds to theejbCreate() method in HelloBean.Note In Home Interface we are throwing 2 exceptions Remote and Create .

    NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.

    Our interface HelloHome is extending EJBHome means it has all the behaviour of EJBHome

    Interface methods should end with a semicolon ;

    EJB Example requirement :When the client interacts with the EJB we need to return a Hello World greeting.

    To provide an EJB with the above requirement we have to create Remote & HomeInterfaces , Bean Business logic class and a deployment descriptor. For clarity pleasesee the previous slide Hello World Object Model using RMI.

    Importing the required files

    As for every Interface we need implementation, so Container will implement (autogenerate code) for this Home Interface for us, which is the EJBHome Objec

    58 HelloLocalHome Interface

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    60/93

    58. HelloLocalHome Interface

    package examples ;

    import javax.ejb.EJBLocalHome;

    import javax.ejb.CreateException;

    import javax.ejb.FinderException;

    import java.util.Collection;

    public interface HelloLocalHome extends javax.ejb.EJBLocalHome

    {

    HelloLocal create() throws javax.ejb.CreateException;

    }Copyright 2004 Kanti Prasad All rights reserved

    Rules of Java says package declaration should be at the beginning and ends with a semi colon

    This is the LocalHome Interface for the Home EJB (HelloBean).

    This method creates/manufactures the EJBLocal Object and returns it . This create() method corresponds to theejbCreate() method in HelloBean.Note In LocalHome Interface we are throwing only Create and not Remote exception as there is no network

    So now lets code the HelloLocalHome Interface

    NOTE : Rules ofInterfaces states that there should be no implementation so you will find only method signatures.

    Our interface HelloLocalHome is extending EJBLocalHome means it has all the behaviour of EJBLocalHome

    Interface methods should end with a semicolon ;As for every Interface we need implementation, so Container will implement (autogenerate code) for this Local Home for us, which is the LocalHome Object

    59 HelloBean Remote Interface

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    61/93

    59. HelloBean Remote Interface

    package examples ;

    import java.util.*;

    import javax.ejb.EJBObject;

    import java.rmi.RemoteException;

    public interface Hello extends javax.ejb.EJBObject

    {public String hello() throws java.rmi.RemoteException;

    }

    Copyright 2004 Kanti Prasad All rights reserved

    Rules of Java says package declaration should be at the beginning and ends with a semi colon

    Clients interact with the EJB Object through this Remote interface that is why we need to write this interface.

    As for every Interface we need implementation, so Container will implement (autogenerate code) for this Remote Interface for us, which is the EJBObject

    As our requirement wants a business logic to greet Hello World a single method would be sufficient .As Remote interface is used to interact with the Bean we need to mirror all the method signatures whatare there in a Bean class so that is why we are writing only one method in this Remote interface.Note EJB specification states that all remote calls should throw RemoteException so we are throwing it.

    So lets code the Remote Interface

    NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.

    Our interface Hello is extending EJBObject means it has all the behaviour of EJBObject

    Interface methods should end with a semicolon ;

    Importing the required files

    60 HelloLocal Interface

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    62/93

    60. HelloLocal Interface

    package examples ;

    import javax.ejb.EJBLocalObject;

    public interface HelloLocal extends javax.ejb.EJBLocalObject{

    public String hello() ;

    }

    Copyright 2004 Kanti Prasad All rights reserved

    Rules of Java says package declaration should be at the beginning and ends with a semi colon

    Clients interact with the EJB Object through this Local interface when there is no network involved..

    As our requirement wants a business logic to greet Hello World a single method would be sufficient .As Local interface is used to interact with the Bean we need to mirror all the method signatures whatare there in a Bean class so that is why we are writing only one method in this Local interface.Note As there is no remote calls no Remote Exception is thrown

    NOTE : Rules of Interfaces states that there should be no implementation so you will find only method signatures.

    Our interface Hello is extending EJBLocalObject means it has all the behaviour of EJBLocalObject

    Interface methods should end with a semicolon ;

    As for every Interface we need implementation, so Container will implement (autogenerate code) for this Local Interface for us, which is the EJB Local Object

    61 The Bean Class

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    63/93

    61. The Bean Class

    package examples ;

    import java.util.*;

    import javax.ejb.*;

    public class HelloBean implements javax.ejb.SessionBean

    {

    private SessionContext ctx;

    public void ejbCreate() { System.out.println(ejbCreate()); }

    public void ejbRemove() { System.out.println(ejbRemove());}

    public void ejbActivate() { System.out.println(ejbActivate());}

    public void ejbPassivate() { System.out.println(ejbPassivate()); }public void setSessionContext(javax.ejb.SessionContext ctx) {

    this.ctx = ctx; }

    public String hello() { System.out.println(Hello());

    return Hello World! ; }

    }

    Copyright 2004 Kanti Prasad All rights reserved

    Rules of Java says package declaration should be at the beginning and ends with a semi colon

    This is where we will code our Business logic

    Note : this is a class and not an Interface like the other two (Home / Remote). This is implementing SessionBean so it is a Session Bean

    This ejbCreate() corresponds to the Homeobject Create(). NOTE : in Stateless Bean no arguments are sent

    So now lets code the actual EJB Class

    As per the below note in red we need to write all the methods what are in javax.ejb.SessionBean .

    Java does not support multiple inheritance so you can extend only one class. To overcome

    this they had given us the Implementation option . So when we use implement we need toimplement or write all the methods what are there in the interface we implemented.

    NOTE : If it is Entity Bean we will implement javax.ejb.EntityBean and if it is Message driven bean we will implement javax.ejb.MessagedrivenBean

    These are calledManagement or

    Call back methods

    Our Business method which matchesour Remote Interface method signature

    In Statelss Bean ejbActivateand ejbPassivate Do not apply

    There is nothing much to clean up.

    Storing the Context in a variable so that it can be queried later .NOTE : Because it is a Session Bean we are using setSessionContext for Entity Bean weuse setEntityContext and for Message Driven Bean we use setMessageDrivenContext.

    Importing the required files

    62 The Deployment descriptor

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    64/93

    62. The Deployment descriptor

    Hello

    examples.HelloHome

    examples.Hello

    examples.HelloLocalHome

    examples.HelloLocalexamples.HelloBean

    Stateless

    Container

    Copyright 2004 Kanti Prasad All rights reserved

    As a Bean provider we need to specify the Middleware needs through this descriptor.

    So now lets complete our EJB by writing the deployment descriptor.

    XML Standard requirement

    The nickname for this particular Bean

    The fully qualified name of the Home Interface

    The fully qualified name of the Remote Interface

    The fully qualified name of the Local HomeInterfaceThe fully qualified name of the Local Interface

    The fully qualified name of the EJB Class

    Whether the session bean is stateful or stateless

    THERE ARE MANYTOOLS WHICHCREATES THEDESCRIPTOR

    FOR US

    63 The Client

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    65/93

    63. The Client

    package examples;

    import javax.naming.Context;

    import javax.naming.InitialContext;

    import java.util.Properties;

    public class HelloClient {

    public static void main(String [] args) throws Exception{

    Properties props = System.getProperties();

    Context ctx = new InitialContext(props);

    Object obj = ctx.lookup(HelloHome);

    HelloHome home = (HelloHome) javax.rmi.PortableRemoteObject.narrow(

    obj, HelloHome.class);Hello hello = home.create();

    System.out.println(hello.hello());

    hello.remove();}}

    Copyright 2004 Kanti Prasad All rights reserved

    Rules of Java says package declaration should be at the beginning and ends with a semi colon

    So now lets code our Client to access our simple stateless session bean.

    importing the necessary files

    As there is static key word this main method executes first before any other method in that class

    Assigning props variable with properties information for JNDI initialization

    Obtaining the JNDI initial context is the starting point for connection to a JNDI tree

    Get a reference to the Home Object- the factory for Hello EJB Objects.

    We are casting HelloHome here, as Home Objects are RMI-IIOP objects and so weNeed to use a special RMI-IIOP cast.

    Use the factory to create the Hello EJB Object. We are then calling the hello() methodOn the EJB Object. The EJB object will delegate the call to the Bean,receive theResults and return it to us . We then print it on the screen.

    Once we are done with the EJB Object, we can remove it.

    By passing environment properties we will choose our JNDI driver,networklocation of the server etc.

    NOTE : To call Local Interface you need not cast with the PortableRemoteObject. So the

    block in red will be changed toObject obj = ctx.lookup(java:comp/env/HelloLocalHome); ( to get a ref to LocalHome Object)HelloLocalHome home = (HelloLocalHome)obj;

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    66/93

    64. EJB Jar File

    PropertiesFile

    Remote/LocalInterface

    HomeLocalHomeInterface

    EnterpriseBean Class

    Deployment

    Descriptor

    Jar

    Manifest

    JarfileJar Creator

    DEPLOYED

    Copyright 2004 Kanti Prasad All rights reserved

    Jar file is a .ZIP compression format . META-MF file is a listing file automatically created by the Jar utility.

    Or manually run C:\>Jar cf HelloWorld.jar *

    The folder structure within the Ejb-jar file is

    META-INF/MANIFEST.MFMETA-INF/ejb-jar.xmlexamples/HelloBean.classexamples/HelloLocalHome.classexamples/HelloLocal.classexamples/Hello.class

    Please read the Deployment instructions provided by the Application server as it is Vendor specific

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    67/93

    65. EJB Application Assembler

    .JAR .WARDeploymentDescriptor

    DeploymentTool

    Enterprise Archive

    (.EAR Files)(Application.XML)

    WEB ARCHIEVE (.war)

    JSP

    Servlets

    HTMLWEB.XML

    JAR ARC HIEVE (.jar)

    HOMEEJB

    REMOTEEJB-JAR.XML

    Copyright 2004 Kanti Prasad All rights reserved

    Jarfile

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    68/93

    Copyright 2004 Kanti Prasad All rights reserved

    EXAMPLE 2

    STATEFUL BEAN

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    69/93

    Stateful Session Remote Interface

    Copyright 2004 Kanti Prasad All rights reserved

    package declaration should be in the beginning

    Importing the required classes

    There will not be any implementation in Interfaces

    EJB spec says all remote interface methods need to throw remote exception

    Our bean class CartBean methods are mirrored here

    Remote Cart is extending EJBObject means Cart has all the behaviour of it

    package samples.ejb.stateful.simple.ejb;

    import java.util.*;

    import javax.ejb.EJBObject;

    import java.rmi.RemoteException;

    import samples.ejb.stateful.simple.tools.BookException;

    public interface Cart extends EJBObject

    {

    public void addBook(String title) throws RemoteException;

    public void removeBook(String title) throws BookException, RemoteException;

    public Vector getContents() throws RemoteException;

    }

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    70/93

    Stateful Session Home Interface

    Copyright 2004 Kanti Prasad All rights reserved

    package declaration should be in the beginning

    Importing the required classes

    There will not be any implementation in Interfaces

    EJB spec says all Home interface methods need to throw remote & create exceptions

    In a Stateful Bean you can have more than one create method taking arguments

    CartHome is extending EJBHome means CartHome has all the behaviour of it

    In our bean class CartBean these representejbCreate(String person) & ejbCreate(String person, String id)

    package samples.ejb.stateful.simple.ejb;

    import java.io.Serializable;

    import java.rmi.RemoteException;

    import javax.ejb.CreateException;

    import javax.ejb.EJBHome;

    public interface CartHome extends EJBHome {

    Cart create(String person) throws RemoteException, CreateException;

    Cart create(String person, String id) throws RemoteException,

    CreateException;

    }

    St t f l S i B Cl

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    71/93

    Stateful Session Bean Class

    Copyright 2004 Kanti Prasad All rights reserved

    package declaration should be in the beginning

    Importing the required classes

    as this is the Bean class we will implement the business logic here

    CartBean Class is implementing sessionbean means this bean class is a session bean

    NOTE : AS we are implementing and not extending we need to write all the methods that are there in the Sessionbean

    We defined this method in the Cart remote interface.This also represents the Home create(String person) method

    package samples.ejb.stateful.simple.ejb;

    import java.util.*;

    import javax.ejb.*;

    import samples.ejb.stateful.simple.tools.BookException;

    import samples.ejb.stateful.simple.tools.IdVerifier;

    public class CartBean implements SessionBean {

    String customerName;

    String customerId;

    Vector contents;

    public void ejbCreate(String person) throws CreateException {

    if (person == null) {

    throw new CreateException("Null person not allowed.");

    } else {

    customerName = person;

    }

    customerId = "0";

    contents = new Vector();

    }

    S f l S i B Cl

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    72/93

    // This block is a supporting business method written in idVerifier class

    Stateful Session Bean Class

    Copyright 2004 Kanti Prasad All rights reserved

    We defined this method in the Cart remote interfaceThis also represents the Home create(String person, String id) method we defined

    The new operator is instantiating the instance of a class

    We are calling the validate(id) method from the class ID Verifier

    We defined this method in the Cart remote interface

    We defined this method in the Cart remote interface

    We defined contents as a vector

    public void ejbCreate(String person, String id) throws CreateException {

    if (person == null) {throw new CreateException("Null person not allowed.");

    } else {

    customerName = person;

    }

    IdVerifier idChecker = new IdVerifier();

    if (idChecker.validate(id)) {

    customerId = id;

    } else {

    throw new CreateException("Invalid id: " + id);

    }

    contents = new Vector();

    }

    public void addBook(String title) {

    contents.addElement(title);

    }

    public void removeBook(String title) throws BookException {

    boolean result = contents.removeElement(title);

    if (result == false) {

    throw new BookException(title + " not in cart.");

    }

    }

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    73/93

    Stateful Session Bean Class

    Copyright 2004 Kanti Prasad All rights reserved

    We defined this method in the Cart remote interface

    We need to write these methods as we are implementing SessionBean

    Rules of implement states we need to implement all methods that are there in the implemented interface

    Bean class constructor

    public Vector getContents() {

    return contents;

    }

    public CartBean() {}

    public void ejbRemove() {}

    public void ejbActivate() {}

    public void ejbPassivate() {}

    public void setSessionContext(SessionContext sc) {}

    }

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    74/93

    CartJAR

    CartEJB

    CartEJB

    samples.ejb.stateful.simple.ejb.CartHome

    samples.ejb.stateful.simple.ejb.Cart

    samples.ejb.stateful.simple.ejb.CartBean

    Stateful

    Container

    Stateful Deployment Descriptor

    Copyright 2004 Kanti Prasad All rights reserved

    required by any XML document

    The nickname for this particular Bean

    The fully qualified name of the Home Interface

    The fully qualified name of the Remote Interface

    The fully qualified name of the EJB Class

    Bean type is mentioned here

    Closing session and ejb

    THERE ARE MANYTOOLS WHICHCREATES THEDESCRIPTOR

    FOR US

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    75/93

    Stateful Deployment Descriptor

    Copyright 2004 Kanti Prasad All rights reserved

    Passing Bean class methods and parameter info

    Passing Bean class methods and parameter info

    CartEJB

    Remote

    getContents

    Required

    CartEJB

    Remote

    removeBook

    java.lang.String

    NotSupported

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    76/93

    Stateful Deployment Descriptor

    Copyright 2004 Kanti Prasad All rights reserved

    Passing Bean class methods and parameter info

    CartEJB

    Remote

    addBook

    java.lang.String

    Required

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    77/93

    Stateful Session Client

    Copyright 2004 Kanti Prasad All rights reserved

    package declaration should be in the beginning

    Importing the required classes

    Client class

    As static is there this main method will execute first

    The new operator is instantiating the instance of a class

    Looking into JNDI

    Casting with a suitable RMI IIOP object

    Creating the object

    Invoking the bean class method through remote interface Cart

    adding books to the object

    package samples.ejb.stateful.simple.ejb;

    import java.util.*;

    import javax.naming.Context;

    import javax.naming.InitialContext;

    import javax.rmi.PortableRemoteObject;

    public class CartClient {

    public static void main(String[] args) {

    try {Context initial = new InitialContext();

    Object objref = initial.lookup("java:comp/env/ejb/SimpleCart");

    CartHome home =

    (CartHome)PortableRemoteObject.narrow(objref,

    CartHome.class);

    Cart shoppingCart = home.create("Duke DeEarl","123");

    shoppingCart.addBook("The Martian Chronicles");shoppingCart.addBook("2001 A Space Odyssey");

    shoppingCart.addBook("The Left Hand of Darkness");

    Vector bookList = new Vector();

    bookList = shoppingCart.getContents();

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    78/93

    Stateful Session Client

    Copyright 2004 Kanti Prasad All rights reserved

    We defined booklist as a vector

    After storing in the variable title we are printing it

    Removing a particular book using the bean class method removeBook throughremote interface Cartas we defined it this wayCart shoppingCart = home.create("Duke DeEarl","123");

    We had written a new class BookException and using its method to catch any errors

    Enumeration enumer = bookList.elements();

    while (enumer.hasMoreElements()) {

    String title = (String) enumer.nextElement();

    System.out.println(title);

    }

    shoppingCart.removeBook("Alice in Wonderland");

    shoppingCart.remove();

    System.exit(0);

    } catch (BookException ex) {

    System.err.println("Caught a BookException: " + ex.getMessage());

    System.exit(0);

    } catch (Exception ex) {

    System.err.println("Caught an unexpected exception!");

    ex.printStackTrace();System.exit(1);

    }

    }

    }

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    79/93

    Book Exception

    package samples.ejb.stateful.simple.tools;

    public class BookException extends Exception {

    /**

    * Default constructor.

    */public BookException() {

    }

    /**

    * Constructor with a String as a parameter.

    * @param msg message, describing the exception.

    */

    public BookException(String msg) {

    super(msg);}

    }

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    80/93

    ID Verifier

    package samples.ejb.stateful.simple.tools;

    public class IdVerifier {

    /**

    * Default constructor.

    */public IdVerifier() {

    }

    public boolean validate(String id) {

    boolean result = true;

    for (int i = 0; i < id.length(); i++) {

    if (Character.isDigit(id.charAt(i)) == false)

    result = false;

    }return result;

    }

    }

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    81/93

    Copyright 2004 Kanti Prasad All rights reserved

    ALL EXAMPLESCAN BE SEEN AT

    http://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.htmlhttp://my.execpc.com/~gopalan/java/entity.htmlhttp://java.sun.com/developer/onlineTraining/Beans/EJBTutorial/http://developers.sun.com/prodtech/javatools/jsstandard/reference/techart/entitybeans.html

    http://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.htmlhttp://my.execpc.com/~gopalan/java/entity.htmlhttp://java.sun.com/developer/onlineTraining/Beans/EJBTutorial/http://developers.sun.com/prodtech/javatools/jsstandard/reference/techart/entitybeans.htmlhttp://developers.sun.com/prodtech/javatools/jsstandard/reference/techart/entitybeans.htmlhttp://java.sun.com/developer/onlineTraining/Beans/EJBTutorial/http://my.execpc.com/~gopalan/java/entity.htmlhttp://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.htmlhttp://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.htmlhttp://www.weblogic.com/docs/examples/ejb/Package-examples.ejb.html
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    82/93

    EJB

    Can implement the Remote or Local Interface

    ActiveX

    Uses Microsofts architecture for determining how clients

    invocation requests are sent to components. DCOM used asunderlying transport mechanism

    CORBAORB makes use of GIOP and other protocols to perform IPC

    66. Component Comparison

    Component Distributability

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    83/93

    EJB

    exports operations through Remote Interface

    ActiveX

    exports operations in the same interface

    CORBA

    exports methods through Interface Repository

    67. Component Comparison

    Components provide interfaces in the form of Operations

    Copyright 2004 Kanti Prasad All rights reserved

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    84/93

    EJB

    Containers inject code to handle transactions, database management,

    security, distributability and other customisable services. Containers

    can be provided independent of App Server and EJB providers

    ActiveX

    Transactions, database management, legacy integration have to be coded

    into the logic of the component. Security policy can be inherited from

    NTLM. Transactions can be aided through MTS

    CORBA

    CORBAServices have different APIs. CORBAServices can be complicated

    to code with. CORBAServices are not supported by all ORBs

    68. Component Comparison

    Self Container Components

    Copyright 2004 Kanti Prasad All rights reserved

    C C

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    85/93

    EJB

    Properties are not explicitly exported but can be

    mimicked through accessor operations

    ActiveX

    exports Properties in the same interface

    CORBA

    Properties not explicitly exported but can be

    mimicked through attributes

    69. Component Comparison

    Components provide interfaces in the form of Properties.

    Copyright 2004 Kanti Prasad All rights reserved

    C C i

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    86/93

    EJB

    Events supported through JMS with Message

    Driven Bean

    ActiveX

    exports Events in the same interface

    CORBAEvents supported through Event Service but cannotbe exported

    70. Component Comparison

    Components provide interfaces in the form of Events.

    Copyright 2004 Kanti Prasad All rights reserved

    71 C C i

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    87/93

    EJB

    Incorporating the contents of an EJB can be done

    in two ways: by having the new EJB use the services of an old

    EJB as a direct client

    or

    by writing an EJB class that inherits from an

    existing one

    These two methods of leveragability give developers

    maximum flexibility

    71. Component Comparison

    Component Reusability

    Copyright 2004 Kanti Prasad All rights reserved

    72 C C i

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    88/93

    Active X

    Incorporating the contents of an ActiveX can be done

    in two ways:

    by having the new ActiveX use the services of anold ActiveX as a client

    or

    by Delegation

    The Components being reused must be registered on

    the development machine

    72. Component Comparison

    Component Reusability

    Copyright 2004 Kanti Prasad All rights reserved

    73 C t C i

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    89/93

    CORBA

    Every CORBA object has to have its own interfacedefinition

    CORBA objects can use the services of other Objects

    No mechanism for inheritance or Object reuse

    inherently supported, though

    73. Component Comparison

    Component Reusability

    Copyright 2004 Kanti Prasad All rights reserved

    74 C t C i

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    90/93

    EJB

    Application Server makes multiple instances of EJB Objects. Client

    contexts can be stored in different thread contexts. Different types

    of EJBs identify levels of shareability.

    ActiveX

    uses Microsoft's inprocess/out-of-process architecture for sharing

    multiple ActiveX components and Client components.

    CORBA

    ORB makes multiple instances of CORBA objects. Clients contexts are

    managed by ORB but can behave differently based upon vendors

    Implementation.

    74. Component Comparison

    Components Shareability

    Copyright 2004 Kanti Prasad All rights reserved

    75 Conclusion

  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    91/93

    If you have any comments or appreciations then please email him [email protected], [email protected]

    He likes to hear your feed back!

    CONGRATULATIONS!Now you knowas much as heknow of EJB

    75. Conclusion

    Copyright 2004 Kanti Prasad All rights reserved

    We successfully completed a Tour on EJB . We looked at how an EJB is identified. How many

    different types of EJBs are there and what each EJB type implements. Why

    LocalInterfaces were introduced. We disected the EJB and went deeper into each part i.e. BEAN

    Class, Remote Interface, EJB Object, Local Object, Local Interface, Home Object. We looked

    Into the deployment descriptor and also seen all the files in EJBJar. We looked into each Beans

    Methods and also learned why we needed those methods. We had done 2 different Beans

    examples and we were directed to the Web links where all the examples are demonstrated. Once

    you can get an idea of all the Interfaces, methods & exceptions raised, you can attempt to try

    some examples to get familiar and master EJB. There are nearly 100s of Application servers

    but in this presentation you can see a few majorly used AppServers sample implementation

    web links. Just download any one of them and try out for yourself.

    76. References

    mailto:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    92/93

    Application Servers download information . Most of them are either free or have a 60 day trial version

    REDHAT Application Server and Examples

    http://www.redhat.com/docs/manuals/rhaps/jonas-guide/

    WebSphere downloads and examples

    http://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.html

    Application Server Information , EJB Documentation & Tutorials are found here

    http://my.execpc.com/~gopalan/java/java_tutorial.html

    EJB Documentation http://java.sun.com/products/ejb/javadoc-2_0-fr/

    http://www.theserverside.com/Mastering Enterprise Java Beans

    by Ed Roman , Scott Ambler & Tyler Jewel.

    BEA WebLogic downloads and exampleshttp://commerce.bea.com/index.jsp , http://www.weblogic.com/docs/examples/index.html

    http://dev2dev.bea.com/codelibrary/code/examples_ejb20.jsp

    Copyright 2004 Kanti Prasad All rights reserved

    Most of EJBs related information can be seen at http://www.volantec.biz/ejb.htm

    SUNs downloads and examples

    http://developers.sun.com/prodtech/javatools/jsstandard/reference/docs/s1s5/partsuppliers.html

    http://java.sun.com/j2se/1.4.2/download.html ,http://java.sun.com/j2ee/1.4/docs/tutorial/doc/

    http://java.sun.com/developer/onlineTraining/EJBIntro/EJBIntro.html

    For JBOSSOpen Source go to http://www.jboss.org/downloads/index

    http://www.kevinboone.com/jboss_tut_1.html

    Notes on Deploying on different Application Servers.

    The Art of EJB Deployment http://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.html

    Covers90 % of the

    MARKET

    http://www.redhat.com/docs/manuals/rhaps/jonas-guide/http://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.htmlhttp://my.execpc.com/~gopalan/java/java_tutorial.htmlhttp://java.sun.com/products/ejb/javadoc-2_0-fr/http://www.theserverside.com/http://commerce.bea.com/index.jsphttp://www.weblogic.com/docs/examples/index.htmlhttp://dev2dev.bea.com/codelibrary/code/examples_ejb20.jsphttp://java.sun.com/j2se/1.4.2/download.html%20,http://java.sun.com/j2ee/1.4/docs/tutorial/doc/http://java.sun.com/developer/onlineTraining/EJBIntro/EJBIntro.htmlhttp://www.kevinboone.com/jboss_tut_1.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.javaworld.com/javaworld/jw-08-2001/jw-0803-ejb.htmlhttp://www.kevinboone.com/jboss_tut_1.htmlhttp://java.sun.com/developer/onlineTraining/EJBIntro/EJBIntro.htmlhttp://java.sun.com/j2se/1.4.2/download.html%20,http://java.sun.com/j2ee/1.4/docs/tutorial/doc/http://java.sun.com/j2se/1.4.2/download.html%20,http://java.sun.com/j2ee/1.4/docs/tutorial/doc/http://dev2dev.bea.com/codelibrary/code/examples_ejb20.jsphttp://www.weblogic.com/docs/examples/index.htmlhttp://commerce.bea.com/index.jsphttp://www.theserverside.com/http://www.theserverside.com/http://java.sun.com/products/ejb/javadoc-2_0-fr/http://java.sun.com/products/ejb/javadoc-2_0-fr/http://java.sun.com/products/ejb/javadoc-2_0-fr/http://java.sun.com/products/ejb/javadoc-2_0-fr/http://java.sun.com/products/ejb/javadoc-2_0-fr/http://my.execpc.com/~gopalan/java/java_tutorial.htmlhttp://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.htmlhttp://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.htmlhttp://www-306.ibm.com/software/webservers/appserv/doc/v20dcadv/doc/howto/ep001.htmlhttp://www.redhat.com/docs/manuals/rhaps/jonas-guide/http://www.redhat.com/docs/manuals/rhaps/jonas-guide/http://www.redhat.com/docs/manuals/rhaps/jonas-guide/
  • 8/2/2019 A Practical Approach to EnterPrise Java Beans_site

    93/93