Enterprise JavaBeans

Document Sample
Enterprise JavaBeans Powered By Docstoc
					Enterprise JavaBeans




                       Template 2.4
Enterprise JavaBeans
Course Objectives

   By the end of this course you will be able to...
      Describe the basic technologies and architectural concepts of Enterprise
       JavaBeans (EJB)
      Develop, configure and deploy both Session and Entity EJBs using an
       EJB compliant application server (BEA WebLogic)
      Implement clients and servers using Remote Method Invocations(RMI),
       Java Naming & Directory Interface (JNDI) and Java Transaction Service
       (JTS) APIs
      Describe the basics of database access using the Java Database
       Connectivity (JDBC) API




                               Enterprise JavaBeans                2.0       2
Enterprise JavaBeans
Contents

   Distributed Architectures
   Introduction to EJB
   Using JNDI
   Stateless SessionBeans
   Stateful SessionBeans
   Container Managed EntityBeans
   Advanced EJB Concepts




                                Enterprise JavaBeans   2.0   3
Introduction
Proposed Course Agenda

           Day One            Day Two          Day Three       Day Four
            Introduction
                                   JNDI           Stateful    Bean Managed
                                 (lecture)      SessionBean     EntityBean
                                                  (lecture)      (lecture)
            Distributed
           Architectures

        Introduction to EJB       JNDI            Stateful    Bean Managed
              (lecture)           (lab)         SessionBean    Entity Bean
                                                    (lab)         (lab)




        Introduction to EJB                     Container
                                Stateless
              (lecture)                          Managed
                              Session Beans                   Advanced Topics
                                                EntityBean
                                 (lecture)
                                                 (lecture)

         App Server Setup
                 &                               Container
                               Stateless
         Simple EJB Client                       Managed          Q&A
                              SessionBean
               (lab)                             EntityBean      Wrap up
                                 (lab)
                                                    (lab)




                                     Enterprise JavaBeans                       2.0   4
Introduction
Proposed Course Agenda

                 Day One                Day Two         Day Three
                  Introduction
                                          Stateless       Container
                                        Session Beans      Managed
                                           (lecture)      EntityBean
                  Distributed                              (lecture)
                 Architectures

               Introduction to EJB                          Container
                                         Stateless
                     (lecture)                              Managed
                                        SessionBean
                                                            EntityBean
                                           (lab)
                                                               (lab)



               App Server Setup
                       &                  Stateful      Bean Managed
               Simple EJB Client        SessionBean       EntityBean
                     (lab)                (lecture)        (lecture)

                      JNDI
                    (lecture)                           Advanced Topics
                                          Stateful
                                        SessionBean
                      JNDI                  (lab)             Q&A
                      (lab)                                  Wrap up



                                     Enterprise JavaBeans                 2.0   5
Distributed Architectures




                            Template 2.4
Distributed Architectures
Contents

   From 2-tier to 3-tier
   Communication Middleware




                            Enterprise JavaBeans   2.0   7
Distributed Architectures
Why New Architectures?
                                  Time To Market


                                          Quicker


        Business                      Information
                                         Reactivity
                                                                Technological
        Changes                          system                   Changes




                    Cost                                    Quality
   A system’s reactivity mainly depends on architecture and technological choices
   Scalability, reliability and maintainability


                                     Enterprise JavaBeans                 2.0        8
From 2-tier to 3-tier
2-Tier Client-Server on the Internet


                                       Internet                 Database




     No control over the client operating           Security
      system and hardware                               Database Administrators (DBA) do
                                                         not accept the risks of putting the
     No place to store user files                       database on the Internet
     Fat clients are slow to download                  Internet security should be at the
                                                         service level, not at the data level
                                                     SQL access can generate lots of
                                                      network requests




                                     Enterprise JavaBeans                       2.0         9
    From 2-tier to 3-tier
    Moving to 3-Tier Architectures

                               Embedded                   Embedded
                               Business                   Business   Database
                               Logic                      Logic




                                      Middle Tier Services



                                                                                Database




   From the outside, the Middle Tier                 On the inside, the Middle Tier
    looks like the domain, not like the                implements the business rules and
    technology                                         processes


                                          Enterprise JavaBeans                    2.0      10
From 2-tier to 3-tier
3-Tier Architecture Benefits

                                 Middle Tier Services

                                                                           Database


    Manage changes to business rules and processes
        Separation between GUI and processing

        A change to the business rules is recovered by all applications

        The business object model can be designed for extensibility

    Integrate multiple technologies
        Can support both Java and non-Java clients or servers (incremental migration)

        Can change server or database technology without re-deploying clients

    Control performance
        Server hardware is easier to upgrade than client hardware

        You control the communications between client and server

    Reduce administration costs



                                   Enterprise JavaBeans                       2.0        11
From 2-tier to 3-tier
3-Tier Internet Architecture Benefits

                                            Middle Tier Services

                     Internet                                              Database


    Improved performance
        Use faster protocols than http or ODBC

        Download the GUI, but leave the rest of the logic on the server


    Manage security
       The server is not restricted by applet security rules

       The server can control access to a database


    Manage user application context
       The server can remember user data

       Users can access their context from any Web client




                                    Enterprise JavaBeans                     2.0      12
From 2-tier to 3-tier
3-Tier Enables Architecture Reuse



                                       Middle Tier Services

                                                                   Database
Application 1




Application 2

                           Reuse of Middle Tier Services
                            leverages the server-side investment
                            in architecture and modeling



                                 Enterprise JavaBeans                 2.0     13
Distributed Architectures
Contents

   From 2-tier to 3-tier
   Communication Middleware




                            Enterprise JavaBeans   2.0   14
 Communication middleware
 Distributed Object Architectures


                        Business Services
Application 1
                                                    Database




Application 2    Middleware (CORBA, RMI, DCOM, …)    Legacy

                       Infrastructure Services




                        Enterprise JavaBeans         2.0       15
Communication Middleware
Many to Choose From

   HTTP-CGI
   CORBA
   COM-DCOM
   Java RMI
   Message-Oriented Middleware
   TP Monitors
   Roll your own middleware based on sockets
   Traditional two-tier client server RAD tools




                              Enterprise JavaBeans   2.0   16
Communication Middleware
Static HTML pages

   The Web is based on two multi-platform standards:
   http=Hypertext Transport Protocol
      A protocol on top of TCP/IP for requesting files

      slow protocol (a new connection for each request)

      No session management (multi-form transactions difficult to implement)


   HTML=Hypertext Markup Language
      A page formatting and layout language



       Client                                     Web Server
                            1. Request a page

             Web           2. Download the page       HTML
            Browser                                   Page




                               Enterprise JavaBeans                2.0      17
Communication Middleware
CGI

   CGI=Common Gateway Interface
   An interface for calling programs instead of fetching documents
      The browser can pass parameters to a server-side program

      The program can generate a new HTML page and return it


   A CGI request looks like a URL with encoded parameters:
      http://www.valtech.com/cgi-
       bin/myProgram?param1=John+Smith&param2=74&param3=%6f

     Client                                      Server
                          1. Download a page

              HTML       2. Send a CGI request
              Page                                    Web       CGI
                          3. Return a new page       Server   Program




                              Enterprise JavaBeans             2.0      18
Communication Middleware
Distributed Objects : CORBA
   CORBA is a standard for object interoperability
      Communications over the network

      Support for different languages

      Support for different platforms

      Additional services (Distributed transactions, events, ... )

   CORBA specifies a standard Object Request Broker (ORB)
      Standard language bindings

      Standard communication protocol : IIOP

   An ORB provides object oriented remote procedure calls whereas
    HTTP/CGI provides HTML form processing on the server
   CORBA is defined by the Object Management Group (OMG)
      Exists since 1989

      First version of CORBA was in 1991




                            Enterprise JavaBeans              2.0     19
Communication Middleware
Stubs Make Remote Objects Look Local

   A stub is a local object that represents a remote object
      The stub is automatically generated by tools provided with an ORB

      The stub implements the proxy pattern


   The stub presents the interface of the remote object
      If the remote object is in C++, and the client is in Java, the stub will be in
       Java
              Client Process                             Server Process
                                                             implementation
                               stub




                                      CORBA Software Bus (IIOP)

                                      Enterprise JavaBeans                    2.0   20
Communication Middleware
What is Java RMI?

   Java RMI is an all-Java ORB that is built into the JDK 1.1
      Java only

      RMI provides transparent and easy distribution

      Simpler to use than CORBA


   Java RMI takes advantage of an all-Java world
      Distributed garbage collection

      Distributed Java exceptions

      Pass-by-value


   Currently no interoperability with languages other than Java
      Does not yet use IIOP




                              Enterprise JavaBeans                 2.0   21
Communication Middleware
Stubs Make Remote Objects Look Local

   Like all ORBs, RMI uses stubs to implement remote communication
   Stubs are generated using tools provided with the JDK




            Client Process (Java)                   Server Process (Java)
                                                       Java implementation
                           RMI stub




                             Java Remote Method Protocol

                                Enterprise JavaBeans                         2.0   22
Communication Middleware
Java RMI Integration with CORBA

   JavaSoft has announced that it will allow RMI to run on top of IIOP
      CORBA clients can call RMI servers

      RMI clients can call CORBA servers


   Requires changes to CORBA (CORBA 3)
   Based on the OMG's work on "Pass-By-Value”
   WebLogic will support RMI on top of IIOP once finalized by JavaSoft




                             Enterprise JavaBeans                2.0      23
 Server-Side Components
 Integrated Server Component System


                            Business Services
                          Business Components
Application 1
                                                                 Database


                                             Business logic

                  Container                  Infrastructure
Application 2                    Middleware management of
                                    Automated                     Legacy
                                      infrastructure services

                   Standard Infrastructure Services
                        Infrastructure Services
                     Services   Services   Services   Services




                            Component System


                           Enterprise JavaBeans                   2.0       24
Distributed Architectures
Summary

   Many applications today require more complicated architectures
      3-tiers or more

      Distributed transactions

      Thin client Internet/Intranet & scalability

      HTTP gateways

      etc.

   Communication :
      Form processing : HTTP and CGI

      Remote objects : RMI or CORBA

   Communication middleware like RMI and CORBA is a tool
      A lot of infrastructure code is still required

      Server-side development is still quite complicated

   Developers need a way to simplify server-side development


                            Enterprise JavaBeans              2.0    25
Introduction To EJB




                      Template 2.4
Introduction to EJB
Summary

   Overview
   EJB Architecture
   EJB Services
   EJB Servers




                       Enterprise JavaBeans   2.0   27
EJB Overview
EJB: Logical View


   Client                         Application Logic         Data


              As a Web Server
            (BEA WebLogic only)
    HTML



                                    Application
                  As an               Server
                Application
                  Server




                              Enterprise JavaBeans    2.0          28
EJB Overview
An Application Server - BEA WebLogic
                                                        Transaction
                                                        Coordinator


                           Application
                             Server
                         JHTML
                                               JTS        RDBMS
      HTTP      HTTP     Servlets                         ODBMS
     HTTPS                                    JDBC
     TCP/IP                                    JNDI
                                    EJB EJB
                                     EJB
      SSL                              EJB                Directory
                                               COM
      RMI       Socket                                     Server
                                              CORBA
      IIOP                     Events
      COM                                     JNI
                                    RMI
                                                         COM
                                                      CORBA
      Administration                                          C/C++
        Console
                             Enterprise JavaBeans          2.0        29
   EJB Overview
      Components and Containers
     A component:
        has a separate interface and implementation

        the implementation is instantiated within a server container


     A container:
        intercepts communication between the client and the component to allow
         automation of infrastructure code such as transactions and security.
        communicates with the component using direct function calls.


                                      Server                   Component Server and Container
Client                                                             infrastructure implementation

                   stub

                            network


                                                                       Server-Side Component
                                     Container acts as a               business logic implementation
                                   distributed object server

                                  Enterprise JavaBeans                              2.0            30
EJB Overview
The EJB specification

   EJB is a specification, not a product
      Current release is 1.1


   Written by SUN with Oracle, IBM, BEA...
   Specify the interface between:
      A client and an EJB

      An EJB and the EJB container



   The EJB specification is based on the Java API:
      JNDI - Java Naming and Directory Interface : naming service

      JTS - Java Transaction Service: transactional service

      JMS - Java Message Service: messaging service

      JDBC - Java Database Connectivity: SQL interface




                              Enterprise JavaBeans                   2.0   31
EJB Overview
What is an EJB? 1/2

   A distributed and transactional Java component
      No relationship with JavaBeans (client side components)


   Must be installed into a component server compliant with the EJB
    specification
   Two types of EJB components:
      Entity EJB: persistent and shared. Typically a business object

          Example: a product sells on an e-commerce Web site

      Session EJB: manage a client session

          Example: a buy/sell session on an e-commerce Web site


   So, EJB are Java components that are
      Portable, Object-Oriented, Robust...




                               Enterprise JavaBeans                 2.0   32
EJB Overview
What is an EJB? 2/2

When an EJB is installed in an EJB server, it automatically becomes
   Transactional
      EJB services can run inside of a distributed transaction, and can be
       committed or rolled back.
   Re-entrant or thread safe
      Many services can be executed at the same time by different clients.


   Secure
      Access rights can be defined on each of the services.


   Persistent
      The Entity EJB may come from a database or another application.

      EJB server automatically adds persistence to EJB....

      ... or the persistence can be directly managed by the EJB through JDBC




                               Enterprise JavaBeans                 2.0       33
EJB Overview

Standard Infrastructure Needs
     Directory services
     Distributed transaction management
     Security management
     Concurrent access management (multi-thread)
     Persistence management
     Resource pooling (ex: database connections)
     Administration interface
     Load balancing
     Fault tolerance




                             Enterprise JavaBeans   2.0   34
EJB Overview

The APIs
   Java Platform for the Enterprise (JPE)               WebLogic services
      Java Naming and Directory Service (JNDI)             Events

      Remote Method Invocation (RMI)                       Time service

      Java Database Connectivity (JDBC)                    File Service

      Enterprise Java Beans (EJB)                          Workspaces

      Java Transaction Service (JTS)                       htmlKona

      Servlets /JHTML




                               Enterprise JavaBeans                  2.0      35
EJB Overview
Separation of Roles
   Server/Container Provider
      Third-party middleware or database server vendor

   Tool Vendor
      RAD tools for developing EJB components

      RAD tools for developing Applications on top of EJB components

   Component Developer
      Can be your developers

      Can be a third-party software vendor (for example, ERP packages)

   Deployer
      Server/containers provide tools to add run-time behavior to components

      Security, transactions, load balancing, Application Partitioning

   Application Developer
      client-side developer, GUI developer




                              Enterprise JavaBeans                2.0       36
EJB Architecture
Summary

   Overview
   EJB Architecture
   EJB Services
   EJB Servers




                       Enterprise JavaBeans   2.0   37
EJB Architecture
EJB server: an integrated Infrastructure

   The Business Logic is based on a Technical Infrastructure
      The Infrastructure is design to support the Architecture

      Supply base services such as: persistence, transaction, security,
       distribution, naming and so on...
   Implementing a Technical Infrastructure is a complex and risky task
      Use the standard services from the ORBs

      The developers usually spend more time developing the technical
       Infrastructure rather than develop the Business Logic


   An EJB server provides a complete and integrated Technical
    Infrastructure
       The developers are focused on the Business Logic, no more on low-level
        technical points.

                               Enterprise JavaBeans                 2.0    38
EJB Architecture
A portability Standard, but...

   An EJB can be deployed in servers coming from different vendors
      The EJB server hides the technological heterogeneity.


   At deployment time, the EJB server adds code around the EJB
    component to support basic EJB services
      Distribution (IDL generation, Stub/Skeleton generation), Transaction,
       Synchronization, Persistence, Security etc...
                                    EJB


      EJB server                             EJB server



             EJB spec                                  EJB spec
      RMI API      JTS   JNDI                RMI API      JTS     JNDI
      CORBA        OTS Naming                DCOM         DTC     Wins

                                Enterprise JavaBeans                     2.0   39
EJB Architecture
…not an interoperability standard !

   EJB servers from different vendors do not necessarily communicate
    with each other
      … unless they are based on interoperable technologies


   CORBA is a de facto standard for distributed object-oriented systems
      But, take care because services should also be interoperable.

      Not true right now.
                                            Portability of the EJB

        Server EJB             Server EJB                   Server EJB




          EJB spec               EJB spec                      EJB spec
        CORBA+OTS              CORBA+OTS            No!      DCOM+MTS



                             Enterprise JavaBeans                         2.0   40
EJB Architecture
Server Administration

   Distributed software administration is a critical issue.
      Each application should supply a solution

      You must develop administration services in the
       Infrastructure to allow administration and supervision.
   The EJB provide such services: administration GUI
    and supervision (SNMP support?)
      Out of the scope of the EJB specification




                               Enterprise JavaBeans              2.0   41
EJB Architecture
The 3 logical levels 1/2

   Application: application specific processing.
   Business: rules and objects relative to the Business, not to the
    application.
   Infrastructure: technical services.

                       Application Application Application

                                    Business

                                  Infrastructure


   The Business services should be:
      shared by all the applications of an IT software.

      infrastructure independent.


                                 Enterprise JavaBeans            2.0   42
EJB Architecture
The 3 logical levels 2/2

   2 tier Client/Server
      Application and Business
        logic are mixed                    Application
      Platform and infrastructure
                                            Business
        dependent.                        Infrastructure

   Multi tier architecture
      Good separation of the
       Business and application logic
                                                             Business
      Infrastructure dependent
                                          Application
                                                           Infrastructure


   Enterprise Java Beans
      Good separation of the 3           Application        Business
       logical partitions: Application,
       Business and Infrastructure                          EJB spec
                                                           Infrastructure

                                 Enterprise JavaBeans                       2.0   43
EJB Architecture
EJB Tools

   EJB based RAD (Rapid Application Development) tools will appears.
   Such tools should allow one to graphically:
      create a GUI by gathering JavaBeans

      execute an EJB service to handle a user interaction

      create and deploy an EJB component in the EJB server

      debug an EJB component installed in an EJB server


   Most of the Java tool editors have announced future availability of such
    tools
                                     RAD tools
                                          EJB
                                        compliant

               Client                                          EJB server
               JavaBeans



                             Enterprise JavaBeans               2.0         44
EJB Architecture
Server, Container, Component

   The server supplies the basic services:
      transaction, persistence management….

      should come from: database editors, transaction
                                                           Server
       monitors editors, middleware editors, OS editors.   Container
      Oracle, Sybase, Inprise, BEA, IBM, Microsoft...
                                                           Component
      A server contain one or more EJB containers


   The Container supplies an implementation of the
    EJB spec over the EJB server:
      The EJB components lays inside the EJB container

      The EJB container is based on the EJB server

      The Container/Component interface is part of the
       EJB spec, but not the Container/Server interface.
   A component is installed inside the Container
      The container control the Components.


                               Enterprise JavaBeans        2.0         45
EJB Architecture
Session EJB
   Manages a client session.
   Examples:
      The Cart in a virtual supermarket.

      A buy/sell session of financial products, for a home banking application.


   A Session EJB is not transactional but can be transaction aware.
      Not persistent

      Call-backs notify commit and rollback success/failure of a
       transaction.
   A Session EJB is an extension of the client code on the server side
      Balance the code from a Thin-Client to the server.


   An EJB server can manage many Session EJB simultaneously.



                               Enterprise JavaBeans                  2.0       46
EJB Architecture
Stateless and stateful session EJB

   A stateless Session EJB doesn’t store any information relative to the
    session’s state.
      The same EJB can be used to serve different clients (one at a time)

      Example: A Session EJB to compute statistics on the billing from an
       accounting application
   A stateful EJB stores conversational information, i.e. dependent of the
    session state (conversational state)
      The EJB can also be used to server only one client

      Example: a session EJB "shopping bag" in a Web based supermarket.




                              Enterprise JavaBeans               2.0         47
EJB Architecture
Entity EJB

   Optional feature in EJB 1.0, mandatory in EJB 1.1 and following
   Entity lifetime in not dependent on the client connection.
   Persistent: stored in a database or come from another wrapped
    application.
   Shared data between clients.
   An EJB server cached objects in memory
      And maintains the transactional integrity of the cache.


   EJB components can collaborate
      The EJB client may be another EJB


   Entity Persistence can be managed:
      By the EJB itself through JDBC

      Automatically by the EJB container


                               Enterprise JavaBeans              2.0   48
EJB Architecture
Overall view



  Client



  Client               EJB Pool


       Server
       Container
       Entity EJB
       Session EJB

                     Enterprise JavaBeans   2.0   49
Introduction to EJB
Summary

   Overview
   EJB Architecture
   EJB Services
   EJB Servers




                       Enterprise JavaBeans   2.0   50
EJB Services
Resource Pooling

   Management of resources shared by Clients
   An application doesn’t create pooled resources
      It asks the resource manager for an available resource

      If the resource exists, it is returned from the resource pool

   An application doesn’t free pooled resources
      If the pool is full, resources are freed by the pool manager

      LRU - Least Recently Used: older resources in the Pool are freed first

   Can be used to manage: Thread, memory, DB connection...
      EJB container Implementation issue, not in the EJB spec.




                                           LRU
                   free     Pool                         delete
    EJB
    EJB
     EJB
                    get                                   create

                               Enterprise JavaBeans                 2.0         51
EJB Services
Thread management

   An EJB server is multi-thread
      One thread per client request, one thread per client

      Thread policy is up to the EJB container supplier


   Threads are usually managed in a Pool
   An EJB cannot create a private Thread
      Forbidden by the EJB spec.


   An EJB component becomes automatically re-entrant (thread safe) at
    deployment time
      No extra code needed to synchronize the EJB




                               Enterprise JavaBeans           2.0        52
EJB Services
Thread management

    Client 1 starts a service on an EJB

                           EJB server

    Client 1                                          Thread Pool

    Client 2


    Client 3




                               Enterprise JavaBeans            2.0   53
EJB Services
Thread management

The server obtain a thread from the thread pool
   The thread pool creates a new thread
                        EJB server

 Client 1                                         Thread Pool

 Client 2


 Client 3




                           Enterprise JavaBeans            2.0   54
EJB Services
Thread management

The server executes a service for client 1

                         EJB server

 Client 1                                          Thread Pool

 Client 2


 Client 3




                            Enterprise JavaBeans            2.0   55
EJB Services
Thread management

Clients 2 wants to invoke a service

                        EJB server

 Client 1                                         Thread Pool

 Client 2


 Client 3




                           Enterprise JavaBeans            2.0   56
EJB Services
Thread management

The server obtains a thread from the thread pool
   The thread pool creates a new thread
                        EJB server

 Client 1                                          Thread Pool

 Client 2


 Client 3




                           Enterprise JavaBeans             2.0   57
EJB Services
Thread management

The server executes services for clients 1 and 2

                        EJB server

 Client 1                                          Thread Pool

 Client 2


 Client 3




                           Enterprise JavaBeans             2.0   58
EJB Services
Thread management

The request for client 2 ends : the thread goes back to the pool

                         EJB server

 Client 1                                             Thread Pool

 Client 2


 Client 3




                            Enterprise JavaBeans               2.0   59
EJB Services
Thread management

Client 3 wants to invoke a service

                        EJB server

 Client 1                                         Thread Pool

 Client 2


 Client 3




                           Enterprise JavaBeans            2.0   60
EJB Services
Thread management

The server obtains a thread from the thread pool
   The thread pool reuse the existing thread
                        EJB server

 Client 1                                          Thread Pool

 Client 2


 Client 3




                           Enterprise JavaBeans             2.0   61
EJB Services
Thread management

The server executes requests for clients 1 and 3

                        EJB server

 Client 1                                          Thread Pool

 Client 2


 Client 3




                           Enterprise JavaBeans             2.0   62
EJB Services
Thread management

The request for client 3 ends, the thread goes back to the pool

                        EJB server

 Client 1                                             Thread Pool

 Client 2


 Client 3




                            Enterprise JavaBeans               2.0   63
EJB Services
Thread management

The request for client 1 ends, the thread goes back to the pool

                        EJB server

 Client 1                                             Thread Pool

 Client 2


 Client 3




                            Enterprise JavaBeans               2.0   64
EJB Services
Thread management

   An EJB server can balance the load across a set of machines.
      EJB server implementation detail

      Out of the EJB spec




                            Enterprise JavaBeans              2.0   65
EJB Services
Memory management

   EJB components are sent to an EJB Pool after usage
      Avoid to many create/delete round trip

      Included in the EJB spec.


   The EJB container is responsible for creating and deleting the EJB
    components
      The EJB should try to optimize the EJB server performance


   An EJB component can be Activated/Passivated by the EJB container
      EJB passivation: the EJB is sent to the Pool

      The Pool management policy is dependent of the container
       implementation
   An EJB server can optimize and control memory usage
      It should find a compromise between memory and CPU usage.




                             Enterprise JavaBeans              2.0       66
EJB Services
Connections management

   Opening a new database connection is a very time consuming
    operation
   Connections are shared between clients.
   The EJB container supply specific JDBC drivers managing a Pool of
    open connections
      Configuration parameters can be: maximum and minimum number of
       open connections, timeout to close a connection.




                            Enterprise JavaBeans             2.0        67
EJB Services
Transactions Management

   A Transactional Resource (TR) is an application resource with a state
    that can change during a transaction.
       A database.


   The Transactional context remembers all the TR changes during a
    specific transaction
      The transactional context is propagated through the EJB calls.


   A Transactional Coordinator (TC) manages the transactional contexts
    and the transaction commits/rollbacks
      Implements a 2 phase commit process


   TR and TC should talk directly during a transaction
      Use a standard protocol: XA




                             Enterprise JavaBeans               2.0     68
EJB Services
Begin                                                        Transactional
                                                                Context

                                             TC
                    JTS
  1 begin                                           4 Add (XA)               7 Add (XA)

               2 service                    3 SQL
  Client


                           5 service


                                            6 SQL



       EJB server
       Transactional Resource


                                 Enterprise JavaBeans                  2.0        69
EJB Services
2 Phase Commit                                                Transactional
                                                                 Context

                                             TC
 1 commit           JTS
                                     6 OK             2 prepare      4 commit

  Client


                                               7 OK
                                                             3 prepare         5 commit




       EJB server
       Transactional Resources


                                 Enterprise JavaBeans                    2.0       70
EJB Services
Rollback                                                     Transactional
                                                                Context

                                            TC
 1 commit           JTS
                                    6 KO             2 prepare        4 rollback

  Client


                                              7 KO
                                                            3 prepare           5 rollback

                                                                 Failed


       EJB server
       Transactional Resource


                                Enterprise JavaBeans                      2.0        71
EJB Services
Transaction Management

   Reliable Distributed Transaction management is a complex task.
      Don't try to write a specific Distributed Transaction Coordinator for your
       project !
   Distributed Transaction are usually implemented by
      CORBA OTS: Object transaction Service

          Standard interface to access a transaction Coordinator.

      DCOM: MTS (Microsoft Transaction Server) including DTC (Distributed
       Transaction Coordinator)
          DCOM interface

          protocol between DTC and TR: OLE-TX

          XA compliant, bridge to CICS

      Transaction Monitors

          IBM CICS, BEA Tuxedo ...




                                Enterprise JavaBeans                  2.0       72
EJB Services
Transaction Management

   An EJB server manages the transactions:
      Supply the low level protocols

      Implements 2 phase commit

      Propagate the transactional context

   During the deployment of an EJB, you must describe the transactional
    behavior of its services:
      Can run outside of a transaction, need a transaction, need to create a
       new transaction etc…
      Set at deployment time.

   Nested transactions are not supported by EJB
   The EJB container should supply JDBC 2.0 drivers (XA compliant)
   Applications controls the transaction boundaries with:
      javax.jts.UserTransaction




                              Enterprise JavaBeans                2.0      73
EJB Services
Distribution Management

   Based on RMI API
   RMI is the Java interface to access a remote object
   RMI API is independent of the underlying protocol
      application /session/transport levels

   RMI = RMI API + JRMP
      Default proprietary RMI protocol

   RMI API will be available over IIOP (CORBA)
      The RMI to CORBA mapping is describe in a document




                                 RMI API



               JRMP              CORBA                DCOM


                            Enterprise JavaBeans             2.0   74
EJB Services
Security Management

   An EJB server should supply the implementation of the java.security
    package interfaces to allow:
      Access Control (mandatory feature of the EJB spec)

      Signature management

      Encryption...


   An EJB can get the identity of the caller
      The EJB can determine the caller’s role in the application in order to
       allow or deny actions.
   The access grants are set at the deployment time are through the
    administration GUI of the EJB server.
   The security context is propagated through the EJB calls.



                                Enterprise JavaBeans                  2.0       75
EJB Services
Administration

   An EJB server should supply tools to administer the EJB components
    and the EJB server itself
      Out of the EJB spec




   An EJB server should be supervised
      Out of the EJB spec.




                            Enterprise JavaBeans            2.0      76
Introduction to EJB
Summary

   Overview
   EJB Architecture
   EJB Services
   EJB Servers




                       Enterprise JavaBeans   2.0   77
EJB servers
Typology


   Servers for mission critical applications requiring high throughput -
    transactions per second (TPS)
       BEA WebLogic, IBM Websphere


   Servers for mission critical applications with medium transaction
    throughput
       Oracle, Objectivity, Sybase, Microsoft, Netscape, Lotus


   Cheap servers coming from small companies:
      GemStone, Allaire, Inprise, NetDynamics (bought by SUN) , BlueStone,
       Apptivity etc...




                              Enterprise JavaBeans               2.0        78
EJB servers
Availability
   Application Servers coming from the Transactional world:
      BEA WebLogic (http://www.beasys.com)

      IBM Websphere (http://www.ibm.com)

   Database Oriented Application Servers:
      Oracle OAS 4.1 (http://www.oracle.com) EJB compliant application server

      Sybase Enterprise Application Studio (www://sybase.com) application server
       over Jaguar CTS and PowerJ tool
      Gemstone (http://www.gemstone.com) implements EJB

   Other Application Server vendors
      Iona’s EjbHome (http://www.ejbhome.com)

      Netscape Application Server (http://www.netscape.com)

      Sun NetDynamics (http://www.sun.com) application server




                                Enterprise JavaBeans                    2.0         79
Introduction to EJB
Summary

   EJB = Server + Container + Component
      EJB server supply the basic services.

      EJB container lay in an EJB server and implements EJB spec.

      EJB component lay inside an EJB container


   An Entity EJB is a shared and persistent component
   A Session EJB is not persistent
      Stateless Session EJB don't store any data

      Stateful Session EJB store conversational data


   EJB container supply services such as:
      Thread, Memory and DB connection management

      Transaction, security and load balancing

      This services are part or not of the EJB spec




                              Enterprise JavaBeans               2.0   80
        Using the
      Java Naming
            &
Directory Interface (JNDI)




                             Template 2.4
    JNDI
    Serialization


   What is Java Serialization?
      This mechanism allows a complete object to be written to a binary stream.

      It allows you to send an object to a file (persistence management), or
       across the network.
      Mechanism is standardized, provides a default implementation (any object
       can be serialized without writing a line of code).

                                          Java
                                          Object                        Another
           File Stream                             Socket Stream        Machine
                           Disk
                           File




                                  Enterprise JavaBeans               2.0       82
    JNDI
    Serialization

   How does Java Serialization
    work?                                                     Order
      The complete object tree is
       automatically serialized.
      All concerned classes must
       implement the « Serializable »
       interface. (like a Flag)                  Ordered Item         Address
      No implementation code is
       needed.
      Attributes marked "transient" are
       not serialized.                              Product
      Most objects included in the JDK
       implement Serializable (Vector,
       Date, …)


                                 Enterprise JavaBeans                   2.0     83
JNDI and Naming
What is JNDI?

   Java Naming and Directory Interface
      Java defines the interface (API)

      An implementation is provided by the Application Server vendor


   Standard interface to a traversable tree of objects
      Nodes and objects can be named

      Nodes and objects can be bound to other nodes


   Also supports a directory service
      Objects bound to nodes with associated attributes




                              Enterprise JavaBeans                2.0   84
  Prerequisite
  JNDI Introduction

JNDI allows you to use a lookup service for objects (scalable)
Naming service implementation(s) are hidden from application
Application gets back the object directly




                              Enterprise JavaBeans               2.0   85
 JNDI and WebLogic Naming
 JNDI and the Application Server
                                            Java Object
                  Context                    Reference


                                Application Server
Client




     Client has API
       access to
       JNDI tree                      JNDI Tree lives in the
                                     Application Server as a
                                   collection of Named Object
                                            References
                            Enterprise JavaBeans                2.0   86
JNDI and WebLogic Naming
How JNDI is structured

   File system analogy is a good place to                /
    start
      File system has nodes (directories) and
        leaves (files)                             etc   usr         dev
      Top-level of file system is a directory
        which can contain zero or more
        subdirectories. This pattern repeats             local
        forming the entire directory tree
   JNDI initially looks like a file system              bin
      Has nodes which are called “contexts”

      Each context can contain zero or more
       objects or other contexts



                                Enterprise JavaBeans           2.0     87
JNDI and Naming
JNDI tree

 A binding is the association                          Initial context
  of an object with a logical
     name and a context




        Context bound
         into another
            context




                          Same object bound into two
                              different contexts
                                Enterprise JavaBeans                     2.0   88
JNDI and Naming
Compound naming and JNDI

   Compound names in a file system
      c:\weblogic\lib\weblogicaux.jar

          Three contexts: “c”, “weblogic”, “lib”

          One object: “weblogicaux.jar”


   Implicitly referencing subcontexts and explicitly creating them
      JNDI supports dot-delimited (“.”) referencing of existing objects in child
       contexts.
      JNDI does NOT support implicitly creating subcontexts during act of
       binding
          you have to create all the subcontexts before you can bind an object




                                Enterprise JavaBeans                 2.0       89
JNDI and Naming
Using JNDI with WebLogic

   Simple usage: binding and looking up objects by name
   Putting Objects into JNDI (binding objects into the name space)
     1) Get an initial context - the first handle into the name space
     2) Bind object to context
   Getting Objects out of JNDI (resolving objects out of the name space)
     1) Get an initial context - the first handle into the name space
     2) Object lookup
   Other parts of API support dynamic browsing and directory interaction
   Usage very similar to CORBA Naming Service




                              Enterprise JavaBeans               2.0    90
JNDI and Naming
Obtaining an Initial Context 1/2

   javax.naming.InitialContext is a subclass of javax.naming.Context
   Javasoft attempted to create a vendor-neutral approach for
    initialization that would not require recompilation of code
   Obtaining initial context leverages java.util.Properties objects and
    system properties for initialization
   If within same VM as WebLogic Server, InitialContext is available by
    calling the no-argument constructor of InitialContext




                              Enterprise JavaBeans                2.0      91
JNDI and Naming
Obtaining an Initial Context 2/2



 public SimpleJNDIClient()
 {
   try
   {
     //Create a hashtable to initialize out
     //initial context. Note that we don't have
     //to create a T3Client
     Hashtable ht = new Hashtable();
     ht.put(Context.INITIAL_CONTEXT_FACTORY,
                  "weblogic.jndi.T3InitialContextFactory" );
     ht.put(Context.PROVIDER_URL, “t3://localhost:7001”);
     //Create the initial context
     Context context = new InitialContext(ht);
   }
   catch (NamingException e)
   {}
 …




                               Enterprise JavaBeans            2.0   92
JNDI and Naming
Binding objects into JNDI

   May want to create child context(s) before binding to server object
      Remember that binding with a compound name is not supported by the
       spec.
        javax.naming.Context subContext =
                  initialContext.createSubcontext(contextName);

   Once target context is obtained, use bind(…) or rebind(…)
    method
      bind(…) will fail if binding already exists (throws an Exception)

      rebind(…) will replace existing bindings with the same name.




                              Enterprise JavaBeans                2.0      93
JNDI and Naming
Binding objects into JNDI 1/2

   Name structure lives on Server
   If client binds object into JNDI
       Local objects are serialized and moved into the Server

            These objects must be serializable

       Remote objects (RMI objects) stay on the client, a remote reference
         (stub) lives on the server

   If a client requests an object
       Local object are serialized and moved into the client

       Remote objects are passed by reference (only a stub is passed to the
         client)



                               Enterprise JavaBeans                 2.0        94
 JNDI and Naming
 Binding objects into JNDI 2/2


public static InitialContext getInitialContext() throws NamingException
{
  Hashtable ht = new Hashtable();
  ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.T3InitialContextFactory" );
  ht.put(Context.PROVIDER_URL, “t3://localhost:7001”);
  InitialContext Context = new InitialContext(ht);
  return Context;
}

//…
//Obtain the initial context
InitialContext initialContext = getInitialContext();

//Create a Bank object
Bank myBank = new Bank();

//Bind the impl into the JNDI tree
initialContext.rebind(”theBank", myBank);




                                  Enterprise JavaBeans                  2.0       95
JNDI and Naming
Resolving references from JNDI 1/2

   As with binding, first get context
   Unlike with binding, you can reference objects in child-contexts using
    dot-delimited (“.”) compound names
   Returned object always of type java.lang.Object -- cast appropriately
   Remote objects bound into tree will be returned as remote references
    to remote clients




                              Enterprise JavaBeans              2.0         96
 JNDI and Naming
 Resolving references from JNDI 2/2


public static InitialContext getInitialContext() throws NamingException
{
  Hashtable ht = new Hashtable();
  ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.T3InitialContextFactory");
  ht.put(Context.PROVIDER_URL, “t3://localhost:7001”);
  InitialContext Context = new InitialContext(ht);
  return Context;
}

//…
//Obtain the initial context
InitialContext context = getInitialContext();

//Retrieve the object using lookup
MyObject myObj = (MyObject) context.lookup(“foo.moo.myObjectName”);
…




                                 Enterprise JavaBeans                   2.0       97
JNDI and Naming
Summary

   JNDI is all about the context
   JNDI primary operations
      Find initial context, bind, resolve

   rebind(…) often more convenient that bind(…)
      replace the previous version of the object if it exists


   No implicit creation of sub-contexts with compound name bind




                                Enterprise JavaBeans             2.0   98
Enterprise JavaBeans   TM
    Basic Concepts




                            Template 2.4
               EJB Basic Concepts
               Objectives

                  By the end of this section, you will be able to:
                     Develop, deploy and use a Session EJB

                     Develop, deploy and use an Entity EJB




SpObjectives                                  Enterprise JavaBeans    2.0   100
            EJB Basic Concepts
            Contents

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB


SpContent                              Enterprise JavaBeans   2.0   101
            EJB Basic Concepts
            Prerequisites

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   102
Prerequisite
    Serialization Introduction

    What is Java Serialization?
       This mechanism allows a complete object to be written to a binary
        stream.
       It allows you to send an object to a file (persistence management), or
        across the network.
       Mechanism is standardized, provides a default implementation (any
        object can be serialized without writing a line of code).

    How does Java Serialization work?
       The complete object tree is automatically serialized.

       All concerned classes must implement the « Serializable » interface.
        (like a Flag)
       attributes marked "transient" are not serialized.

       No implementation code is needed.




                                 Enterprise JavaBeans                  2.0       103
   Prerequisite
   Serialization Sample

import java.io.* ;
public class SerializationSample
{
    public static void main (String[] argv)                         Any Stream !
    {                                                        ByteArray{Out/In}putStream
        String object = "Duke" ;
        // serialize the String object into a file
        try {
            ObjectOutputStream filter = new ObjectOutputStream (
                                            new FileOutputStream (f.ser)) ;
            filter.writeObject (object) ; // implicit upcasting
        } catch (IOException e) {}
        // release the unique reference on the String object
        object = null ;
        // deserialize the String object from the file
        try {
            ObjectInputStream filter = new ObjectInputStream (
                                           new FileInputStream (f.ser)) ;
            object = (String)(filter.readObject ()) ; // explicit downcasting
        } catch (IOException e) {}
        // print the String object
        System.out.println (object) ; // print "Duke"
    }
}

                                   Enterprise JavaBeans                    2.0      104
  Prerequisite
  RMI Introduction
     Remote Method Invocation API

Method calls send messages to remote object
Remote objects have an “Illusion of being local”.
All the methods must throw a Remote Exception.
Supported Method Parameters:

   Base types (long, short,…) (passes by value)

   Serializable objects (passed by value)
                                             Not Shared

   Remote objects (passed by reference)



                              Enterprise JavaBeans        2.0   105
  Prerequisite
  JNDI Introduction

JNDI allows you to use a lookup service for objects (scalable)
Naming service implementation(s) are hidden from application
Application gets back the object directly




                              Enterprise JavaBeans               2.0   106
            EJB Basic Concepts
            Develop a Stateless Session EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   107
            Develop a Stateless Session EJB
            Definition

               Theoretically, dedicated to only one client
               May be re-used by several clients at the same time
               Does not represent any persistent data of the information system
               However, it may use some persistent data
               May be involved in a transaction
               The life cycle depends on the load management
                  heavy load : many instances in the EJB instance pool

                  light load : few instances in the EJB instance pool




SpContent                                 Enterprise JavaBeans             2.0     108
            Develop a Stateless Session EJB
            EJB Delegation Pattern
               A client always accesses an EJB (called EJB instance) through a
                Remote Object
               The "Delegation pattern" is used by the container for total control on
                technical services
               The EJB "wrapping" is totally transparent to the client




                                                                  EJB Container

                EJB Client

                                                                   EJB instance




SpContent                                 Enterprise JavaBeans               2.0         109
Develop a Stateless Session EJB
Intervening party



        Home Interface              Remote Interface

     “Create”                     Business                   Bean instance
                                  Methods              Implementation of Business methods
                                                         and Container-contract' methods
            Signatures                  Signatures




    Home Object              Remote Object




                                     Enterprise JavaBeans                         2.0       110
Develop a Stateless Session EJB
Lookup and Use an EJB Instance


                           Home Interface               EJB Container

                        Home Object
                                            “Create”


                                     Remote Interface

                                  Remote Object
                                                             EJB instance
  EJB Client




                         Enterprise JavaBeans                      2.0      111
Develop a Stateless Session EJB
What the developer needs to write?
   Write a Home interface : definition of the creation method(s) for this
    EJB
   Write a Remote interface : definition of the business services provided
    by the EJB
   Write the Bean instance : implementation of the business methods and
    the Container-contract methods

       1.                     2.                             3.

        Home Interface        Remote Interface
      “Create”              Business
                            Methods
                                                         Bean instance
            Signatures             Signatures     Implementation of Business methods
                                                    and Container-contract methods




                              Enterprise JavaBeans                          2.0        112
            Develop a Stateless Session EJB
            Class diagram

                                <<Interface>>
                                   Remote
                                (from rmi)




             <<Interface>>                                  <<Interface>>                          <<Interface>>     <<Interface>>
               EJBHome                                        EJBObject                            SessionBean      SessionContext
             (from ejb)                                     (from ejb)                          (from ejb)         (from ejb)




                            1                                             2                                  3
             <<Interface>>                                  <<Interface>>                          TraderBean
             TraderHome                                         Trader                           (from sample)
            (from sample)                                   (from sample)




       TraderHomeImpl                                   TraderRemoteImpl
      (from container)                                 (from container)
                                             creates                                        Delegates


SpContent                                                                   Enterprise JavaBeans                   2.0               113
                           Develop a Stateless Session EJB
                           Class description                                                                                                        1/3
                           <<Interface>>
                             Remote
                           (from rmi)

                                                                                                               The RMI Remote interface
                                                                                                                  Implemented by any RMI remote object
           <<Interface>>                           <<Interface>>          <<Interface>>     <<Interface>>
            EJBHome                                 EJBObject                              SessionContext
                                                                       SessionBean
           (from ejb)                              (from ejb)          (from ejb)          (from ejb)




           <<Interface>>                           <<Interface>>         TraderBean
           TraderHome                                 Trader            (from sample)
          (from sample)                            (from sample)




      TraderBeanHomeImpl                        TraderBeanEOImpl
                                    creates                        delegates
     (from container)                         (from container)




                                                                                                                The TraderHome interface
                           <<Interface>>
                             Remote




                                                                                                            
                           (from rmi)




                                                                                                                  Provided by the developer
          <<Interface>>                           <<Interface>>           <<Interface>>     <<Interface>>
           EJBHome                                 EJBObject                               SessionContext
                                                                       SessionBean
          (from ejb)                              (from ejb)           (from ejb)         (from ejb)




                                                                                                                  Manage the EJB life cycle (create, destroy)
          <<Interface>>                           <<Interface>>          TraderBean
          TraderHome                                 Trader             (from sample)
          (from sample)                           (from sample)




      TraderHomeImpl                           TraderRemoteImpl
                                   creates                         delegates
     (from container)                         (from container)




                                                                                                                The TraderHomeImpl class
                           <<Interface>>
                             Remote
                           (from rmi)




                                                                                                            

                                                                                                                  Generated by the container.
          <<Interface>>                           <<Interface>>          <<Interface>>     <<Interface>>
           EJBHome                                 EJBObject                              SessionContext
                                                                      SessionBean
          (from ejb)                              (from ejb)          (from ejb)          (from ejb)




                                                                                                                  Implements life cycle management services defined in
          <<Interface>>                           <<Interface>>         TraderBean
          TraderHome                                 Trader            (from sample)
         (from sample)                            (from sample)




                                                                                                                   the TraderHome interface
      TraderHomeImpl                           TraderRemoteImpl
                                   creates                         delegates
     (from container)                         (from container)




SpContent                                                                                                                Enterprise JavaBeans                    2.0   114
                           Develop a Stateless Session EJB
                           Class description                                                                                                       2/3
                           <<Interface>>
                             Remote
                           (from rmi)
                                                                                                               The Trader remote interface
           <<Interface>>
            EJBHome
           (from ejb)
                                                   <<Interface>>
                                                    EJBObject
                                                   (from ejb)
                                                                          <<Interface>>
                                                                       SessionBean
                                                                       (from ejb)
                                                                                            <<Interface>>
                                                                                           SessionContext
                                                                                           (from ejb)
                                                                                                                  Provided by the developer
           <<Interface>>
           TraderHome
          (from sample)
                                                   <<Interface>>
                                                      Trader
                                                   (from sample)
                                                                         TraderBean
                                                                        (from sample)
                                                                                                                  Define business services provided by the EJB
      TraderBeanHomeImpl                        TraderBeanEOImpl
                                    creates                        delegates
     (from container)                         (from container)




                           <<Interface>>
                             Remote
                           (from rmi)
                                                                                                               The TraderRemoteImpl class
          <<Interface>>                           <<Interface>>           <<Interface>>     <<Interface>>
                                                                                                                  Generated by the container

                                                                                                                  Implements services defined in the Trader remote
           EJBHome                                 EJBObject                               SessionContext
                                                                       SessionBean
          (from ejb)                              (from ejb)           (from ejb)         (from ejb)




                                                                                                                   interface using delegation
          <<Interface>>                           <<Interface>>          TraderBean
          TraderHome                                 Trader             (from sample)
          (from sample)                           (from sample)




                                                                                                                  Clients only manipulates instance of this class
      TraderHomeImpl                           TraderRemoteImpl
                                   creates                         delegates
     (from container)                         (from container)




                           <<Interface>>
                             Remote
                           (from rmi)
                                                                                                               The TraderBean class
          <<Interface>>
           EJBHome
          (from ejb)
                                                  <<Interface>>
                                                   EJBObject
                                                  (from ejb)
                                                                         <<Interface>>
                                                                      SessionBean
                                                                      (from ejb)
                                                                                           <<Interface>>
                                                                                          SessionContext
                                                                                          (from ejb)
                                                                                                                  Provided by the developer

                                                                                                                  Implements business services
          <<Interface>>                           <<Interface>>         TraderBean
          TraderHome                                 Trader            (from sample)
         (from sample)                            (from sample)




                                                                                                                  Implements the Container-contract methods
      TraderHomeImpl                           TraderRemoteImpl
                                   creates                         delegates
     (from container)                         (from container)




                                                                                                                  Does not Implement Remote




SpContent                                                                                                                Enterprise JavaBeans                2.0      115
                          Develop a Stateless Session EJB
                          Class description                                                                                                    3/3
                          <<Interface>>
                            Remote
                          (from rmi)

                                                                                                          The SessionContext class
                                                                                                             Provides services to obtain the runtime context of a
          <<Interface>>                         <<Interface>>         <<Interface>>    <<Interface>>
           EJBHome                               EJBObject                            SessionContext
                                                                   SessionBean
          (from ejb)                            (from ejb)         (from ejb)         (from ejb)




          <<Interface>>
          TraderHome
         (from sample)
                                                <<Interface>>
                                                   Trader
                                                (from sample)
                                                                     TraderBean
                                                                    (from sample)                             Bean instance
                                                                                                                 current transaction,
      TraderBeanHomeImpl                     TraderBeanEOImpl
                                  creates                       delegates
     (from container)                       (from container)




                                                                                                                 environment properties,

                                                                                                                 client identity…

                                                                                                             Provides a service to obtain the Remote Object
                                                                                                              associated with the EJB Instance




SpContent                                                                                                            Enterprise JavaBeans                 2.0        116
            Develop a Stateless Session EJB
            The Home Interface

               Must follow a naming convention

                public interface <BeanName>Home
                    extends javax.ejb.EJBHome
                {
                    public <BeanName> create ()
                        throws javax.ejb.CreateException,
                               javax.rmi.RemoteException ;
                }
               Must extend the javax.ejb.EJBHome interface
               Must define one (and only one) parameter-less creation method
               The creation method must return a Remote Object reference
               It must have the specified << throws >> clause


SpContent                                 Enterprise JavaBeans              2.0   117
         Develop a Stateless Session EJB
         A Home Interface Sample

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

         public interface TraderHome
             extends EJBHome
         {
             public Trader create ()
                 throws CreateException,
                        RemoteException ;
         }




SpCode                                  Enterprise JavaBeans   2.0   118
            Develop a Stateless Session EJB
            The Remote Interface

               Must follow a naming convention
                public interface <BeanName>
                    extends javax.ejb.EJBObject
                {
                    public <rmiRV> <businessMethod> (<rmiParams>)
                        throws [<businessException>,...]
                                javax.rmi.RemoteException ;
                }
               Must extend the javax.ejb.EJBObject interface
               Must define the signature of all business methods
               All business methods must have the specified throws clause
                  May include business exceptions

                    Must include RemoteException
               Their signature must only use RMI-compliant parameters

SpContent                                Enterprise JavaBeans                2.0   119
         Develop a Stateless Session EJB
         A Remote Interface Sample


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

 public interface Trader
     extends EJBObject
 {
   public TradeResult buy (String customerName, String stockSymbol, int shares)
       throws ProcessingErrorException, RemoteException ;

     public TradeResult sell (String customerName, String stockSymbol, int shares)
         throws ProcessingErrorException, RemoteException ;
 }

 public class TradeResult implements Serializable {
   public int    numberTraded ;                              You must ensure that
   public double priceSoldAt ;                         Your parameters are RMI-compliant
 }

 public class ProcessingErrorException extends Exception {
   public ProcessingErrorException(String message) { super (message) ; }
 }



SpCode                                Enterprise JavaBeans                   2.0     120
Develop a Stateless Session EJB
The Mapping Pattern of the Bean Class

          Interface Signatures                                       Bean Class
                   Home Interface                           Implementation of Business methods
                                                              and Container-contract' methods

    public void create ()
                                                                  public void ejbCreate ()
                                                                  {
                                                                    // implementation
                                                                  }


                  Remote Interface                                … <businessMethod1> (...)
                                                                  {
  … <businessMethod1> (...)                                         // implementation
                                                                  }

  … <businessMethod2> (...)                                       ... <businessMethod2> (...)
                                                                  {
                                                                      // implementation
                                                                  }




                                     Enterprise JavaBeans                             2.0        121
            Develop a Stateless Session EJB
            The Bean Class                                       1/3

               Must follow a naming convention

                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                {
                    public <rmiRV> <businessMethod> (<rmiParams>)
                        throws [<businessException>,...]
                                javax.rmi.RemoteException
                    { /* implementation */ }

                    //… other business methods
                }
               Must be a non-abstract class
                and must implement the javax.ejb.SessionBean interface
               Must define the implementation of all business methods

SpContent                                Enterprise JavaBeans            2.0   122
            Develop a Stateless Session EJB
            The Bean Class                                        2/3

               Must define the Home Create method (e.g., mapping pattern)

                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                {
                    public void ejbCreate ()
                        throws [javax.ejb.CreateException]
                               [,javax.rmi.RemoteException]

                     { /* implementation */ }

                     // … other ejbXXX and business methods
                }
               In general, the implementation is left empty
               This method is also part of the Container-contract’s methods

SpContent                                  Enterprise JavaBeans                2.0   123
            Develop a Stateless Session EJB
            The Bean Class                                         3/3

               Must implement the SessionBean Container-contract’s methods
                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                {
                    private SessionContext _context ;
                    public void setSessionContext (SessionContext)
                    { /* must keep a reference on the Context */ }

                     public void ejbRemove ()            { /* implem. */ }

                     public void ejbActivate () { /* implem. */ }
                     public void ejbPassivate () { /* implem. */ }
                     // ...
                }
               The ejbActivate/Passivate methods will be explained later


SpContent                                 Enterprise JavaBeans              2.0   124
         Develop a Stateless Session EJB
         A Bean Class Sample                                   1/2

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

 public class TraderBean
     implements SessionBean
 {
   // Container-contract’s methods
   private SessionContext _ctx ; // Mandatory code pattern for Context
   public void setSessionContext (SessionContext ctx)
   {
      _ctx = ctx ;
   }

     public void ejbCreate   () {}
     public void ejbRemove   () {}

     public void ejbActivate () {}
     public void ejbPassivate () {}

     // Business methods implementation
     //...




SpCode                                Enterprise JavaBeans               2.0   125
         Develop a Stateless Session EJB
         A Bean Class Sample                                      2/2


     // Business methods implementation
     public TradeResult buy (String customerName, String stockSymbol, int shares)
         throws ProcessingErrorException, java.rmi.RemoteException
     {
       Properties props = _ctx.getEnvironment () ;
       try {
         int stockPrice = Integer.parseInt ((String)(props.get (stockSymbol))) ;
         // buy the stockSymbol on the market...
         return new TradeResult (shares, price) ;
       }catch (Exception e) {
         throw new ProcessingErrorException (e.getMessage ()) ;
       }
     }

     public TradeResult sell (String customerName, String stockSymbol, int shares)
         throws ProcessingErrorException, java.rmi.RemoteException
     {
       // sell the stockSymbol on the market...
     }

 }



SpCode                                Enterprise JavaBeans                   2.0     126
            Develop a Stateless Session EJB
            Allocation of a new Bean instance in the Pool


                                      Does not exist



                1.newInstance()
                2.setSessionContext(sc)
                3.ejbCreate()



                                      Method-ready
                                          pool




SpContent                                 Enterprise JavaBeans   2.0   127
         Develop a Stateless Session EJB
         Allocation of a new Bean instance in the Pool
                                                              <Bean Instance>
                                           : Session
                     Container                                : TraderBean
                                             Context

                                 new


                                        new


                                  setSessionContext()

                                          ejbCreate()




SpCode                                 Enterprise JavaBeans                     2.0   128
         Develop a Stateless Session EJB
         Create method invoked by a client




                                         <Home Object>            <Remote Object>
                   : Client              : TraderHomeImpl           : TraderObject

                              create()
                                                            new




SpCode                                        Enterprise JavaBeans                   2.0   129
            Develop a Stateless Session EJB
            Business method invoked by a client


                                        Does not exist




                    method ()           Method-ready
                                            pool


                 For every method() invoked by a client :
                 1.- A Bean instance is taken out from the pool,
                 2.- The method is executed by this Bean instance and then,
                 3.- The Bean instance is sent back to the pool.


SpContent                                Enterprise JavaBeans                 2.0   130
         Develop a Stateless Session EJB
         Business method invoked by a client
                                               <Remote Object>                 <Bean Instance>
              : Client                             : TraderObject                  : TraderBean



                         Business method




                                           Business method
                                                              Obtain a free Bean instance from the pool

                                                                Business method
                                                                    “Delegation”




SpCode                                            Enterprise JavaBeans                                    2.0   131
         Develop a Stateless Session EJB
         Remove method invoked by a client
                                <Remote Object>                                      <Bean Instance>

                 : Client        : TraderObject                 Container                 : TraderBean




                            remove()

                                                     notify()


                                                          May Reuse the Instance
                                                              and after ...


                                                                            ejbRemove()




SpCode                                            Enterprise JavaBeans                             2.0   132
            Develop a Stateless Session EJB
            Remove a Bean instance from the Pool


                                     Does not exist




                                                ejbRemove()




                                     Method-ready
                                         pool




SpContent                            Enterprise JavaBeans     2.0   133
         Develop a Stateless Session EJB
         Remove a Bean instance from the Pool
                                                                <<BeanInstance>>

                 JVM                 Container                  : TraderBean



                                                 ejbRemove( )


                       finalize()




SpCode                              Enterprise JavaBeans                 2.0       134
            EJB Basic Concepts
            Deploy a Stateless Session EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   135
    Deploy a Stateless Session EJB
    Business Model 1/2

   Follow the component business model :
      Business component providers

      Application built with off the shelf business components

      Business components catalog



         Libraries of business components
         Need for a standard component packaging




                                  Enterprise JavaBeans            2.0   136
  Deploy a Stateless Session EJB
  Business Model 2/2
3 main roles:                            3 main tasks:
   Bean provider                            Pure business logic
                                            development

   Bean deployer                             technical choices

                                             Component assembly
   Application developer




        Technical architecture choice must be separate
                    from bean development
                            Enterprise JavaBeans             2.0   137
Deploy a Stateless Session EJB
What is a Deployment Descriptor ?

   A Deployment Descriptor is a Java              Used for storing information about the
    object                                          EJB
      Package javax.ejb.deployment                   Meta-information

      Serializable class (Persistent Java            Technical information
        class)
                                                   Evolution of deployment descriptors
                                                      EJB 1.0 - Vendor specific

                                                      EJB 1.1 - Standards based




                    DeploymentDescriptor
                                                                   Home
                                                                 Interface
                  Technical          Meta
                 information      information                     Remote
                                                                 Interface
                 Security         Class
                  policy          names                             Bean
                                                                  instance


                                    Enterprise JavaBeans                      2.0         138
    Deploy a Stateless Session EJB
    Deployment Descriptor Information

    EJB meta-information
       EnterpriseBeanClassName

       RemoteInterfaceClassName

       HomeInterfaceClassName

       BeanHomeName : JNDI name for the Home object




    Session information
       ManagementType : STATELESS or STATEFUL

       SessionTimeout   : the maximal life-time of the Session Bean




                                     Enterprise JavaBeans              2.0   139
Deploy a Stateless Session EJB
DeploymentDescriptor Classes
                               DeploymentDescriptor
                     (from deployment)




                         getEnterpriseBeanClassName()
                         setEnterpriseBeanClassName()
                         getHomeInterfaceClassName()
                         setHomeInterfaceClassName()
                         getRemoteInterfaceClassName()
                         setRemoteInterfaceClassName()
                         getBeanHomeName()
                         setBeanHomeName()




                                SessionDescriptor
                      (from deployment)




                          getSessionTimeout()
                          setSessionTimeout()
                          getStateManagementType()
                          setStateManagementType()


                                          Enterprise JavaBeans   2.0   140
Deploy a Stateless Session EJB
How to build a DeploymentDescriptor
   You need a program to :
      Create an instance of Deployment Descriptor

       (SessionDescriptor for Session Beans)
      Populate this instance with correct information

      Serialize this instance (obtain a .ser file).


                                                                               Serialized
newInstance()                           Customized
                                                                               instance
                                         instance
                        set(...)                               serialize
    Deployment                             Deployment
                                                                             Descriptor.ser
     Descriptor                             Descriptor


   Other possibilities :
      Generate the serialized instance from a text file or any other file

      Use a graphical tool provided by an EJB server vendor

      The deployment process may be integrated in RAD tools




                                       Enterprise JavaBeans                      2.0          141
Deploy a Stateless Session EJB
EJB-Jar Files
   An EJB component is packaged into an ejb-jar file
      Standard packaging used for every EJB component

      Single file, simple to manipulate

      Similar to client-side Java components packaging

                                                             EJB
                                                            Portable
                          Components.jar
                            Manifest file
         Name: PropertyDD.ser   Enterprise-Bean:true
         Name: PersonDD.ser      Enterprise-Bean:true

         PersonDD.ser                  PropertyDD.ser
         PersonHome.class              PropertyHome.class
         Person.class                  Property.class
         PersonBean.class              PropertyBean.class


                                 Enterprise JavaBeans        2.0       142
Deploy a Stateless Session EJB
Creates an EJB-Jar Files

   Write a Manifest file for your EJB(s)

    Name: PropertyDD.ser         //Deployment Descriptor file
    Enterprise-Bean:true

    Name: PersonDD.ser           //Deployment Descriptor file
    Enterprise-Bean:true

   Create a DeploymentDescriptor file for each EJB
   Create the jar file using any jar tool
   JDK jar syntax:
                       jar -cfm <filename> Manifest.mf rootDirectory




                                     Enterprise JavaBeans              2.0   143
Deploy a Stateless Session EJB
The EJB Development Life-Cycle


                 The EJB provider
                    Develops the Java classes

                    Creates a default DeploymentDescriptor

                    packages the EJB into an ejb-jar file




                 The EJB deployer
                    Edits and modifies the DeploymentDescriptor

                    Install the components in the EJB Server




                 The application developer
                    Uses the EJB in a Java application




                                 Enterprise JavaBeans              2.0   144
            EJB Basic Concepts
            Use a Stateless Session EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   145
            Use a Stateless Session EJB
            Review : The EJB Architecture


                                          Home Interface               EJB Server

                                    Home Object
                                                           “Create”


                                                    Remote Interface

                                                 Remote Object
                                                                           EJB instance
              EJB Client




SpContent                            Enterprise JavaBeans                        2.0      146
            Using a Stateless Session EJB
            Obtain the Home Object reference
                 Each Home object is registered in JNDI with a specific name


                 The EJB server is responsible for registering the Home into the JNDI
                  naming service


                 The client only knows the JNDI name of the Home object
                 It uses the JNDI naming service to localize the Home object




SpContent                                Enterprise JavaBeans               2.0     147
            Using a Stateless Session EJB
            Obtain a Remote Object reference
                 Ask the Home interface for a reference to the EJB
                    Use the creation services




                 Ask another EJB
                    An EJB method may take another EJB as a parameter or return
                     another EJB




SpContent                                Enterprise JavaBeans               2.0    148
            Using a Stateless Session EJB
            Create a stateless Trader instance


                         : Client       :InitialContext       : TraderHome



                            lookup (HomeName)


                                            create()




SpContent                              Enterprise JavaBeans                  2.0   149
            Using a stateless Session EJB
            Life cycle from the client side                           A method call to
                                                                    the reference throws
                                                                  NoSuchObjectException


                     Does not exist     Drop the reference         Does not exist
                           and                                           and
                   is not referenced                                is referenced

                                                                               Ref.remove()
                                                                                     or
        Server Crash/timeout                                                home.remove(…)
                                                                                     or
                                                                           Server Crash/timeout



                         Exists        Handle.getEJBObject()             Exists
                          and                                             and
                   is not referenced                                 is referenced
                                        Drop the reference


                                                               Method calls to the reference

SpContent                              Enterprise JavaBeans                         2.0        150
            Using a Stateless Session EJB
            A Client Sample                                            1/2

                                                                       Obtain the root context
      import    javax.ejb.* ;
      import    javax.naming.* ;
                                                                        of the naming service
      import    java.rmi.* ;
      import    java.util.Properties ;

      public class Client                                                  JNDI name of the
      {                                                                     Home interface
        public static void main (String[] argv)
        {
          Context ctx = getInitialContext () ;
          TraderHome traderHome = (TraderHome)(ctx.lookup ("TraderHome")) ;
          Trader trader = traderHome.create () ;                 Create an anonymous Trader
          //...
          try{
            trader.remove () ;                               The client may indicate that
          } catch (Exception e) {}                         the EJB is not needed anymore
        }
        static public Context getInitialContext() throws Exception
        {
          Properties p = new Properties();
          p.put(Context.INITIAL_CONTEXT_FACTORY,
                "weblogic.jndi.T3InitialContextFactory");
          return new InitialContext(p);
        }
      }                                 Enterprise JavaBeans                       2.0      151
SpContent
            Using a Stateless Session EJB
            A Client Sample                                           2/2

             try{
               double cashBalance = 0.0;
               for (int i = 1 ; i <= 5; i++) {
                 // Buying
                 stockName = "WEBL" ;
                 shareNumber = 100 * I ;
                 TradeResult tr = trader.buy (customerName, stockName, shareNumber) ;
                 // Keep track of the change in the Cash Account
                 cashBalance -= (tr.numberTraded * tr.priceSoldAt) ;
                 // Selling
                 stockName = "INTL" ;
                 shareNumber = 100 * (i+1) ;
                 tr = trader.sell (customerName, stockName, shareNumber) ;
                 // Keep track of the change in the Cash Account
                 cashBalance += (tr.numberTraded * tr.priceSoldAt) ;
               }
               System.out.println ("CashBalance is :" + cashBalance) ;
             }catch (ProcessingErrorException pe) {
               System.out.println("Processing Error: " + pe);
             }




SpContent                                 Enterprise JavaBeans                   2.0    152
            EJB Basic Concepts
            Develop a Stateful Session EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   153
            Develop a Stateful Session EJB
            Definition
               Used only by one client during the client session
                  Does not represent any persistent information of the system

                  May however use some persistent data, needed for the client


               Maintain a conversational state
                  Group of attributes related to the client session

                  May contain connection resources such as file, socket, database
                   connection, …

               May be activated or passivated by the container
                  to improve resource management




SpContent                                  Enterprise JavaBeans                  2.0   154
Develop a Stateful Session EJB
Passivation - Activation
During passivation, the state of the EJB instance is stored automatically
by the container.

During activation, the state of the EJB instance is loaded automatically
by the container.

An EJB instance may be passivated if none of its methods are invoked
during a specified amount of time (customizable)

An EJB instance is activated by any method call (if not active).

Must be aware of the Passivation-Activation mechanism if connection
resources are involved


                            Enterprise JavaBeans              2.0      155
            Develop a Stateful Session EJB
            Class diagram

                                <<Interface>>
                                   Remote
                                (from rmi)




             <<Interface>>                                  <<Interface>>                          <<Interface>>     <<Interface>>
               EJBHome                                        EJBObject                            SessionBean      SessionContext
             (from ejb)                                     (from ejb)                          (from ejb)         (from ejb)




                            1                                             2                                  3
             <<Interface>>                                  <<Interface>>                          TraderBean
             TraderHome                                         Trader                           (from sample)
            (from sample)                                   (from sample)




       TraderHomeImpl                                   TraderRemoteImpl
      (from container)                                 (from container)
                                             creates                                        Delegates


SpContent                                                                   Enterprise JavaBeans                   2.0               156
            Develop a Stateful Session EJB
            The Home Interface

               Must follow a naming convention

                public interface <BeanName>Home
                    extends javax.ejb.EJBHome
                {                                      New
                    public <BeanName> create (<rmiParams>)
                        throws [<businessException>,]...
                               javax.ejb.CreateException,
                               javax.rmi.RemoteException ;
                    //...
                }

                                                                 New
               Must define, at least, one creation method
                                                                              New
               The throws clause may include some Business Exception

SpContent                                 Enterprise JavaBeans          2.0     157
         Develop a Stateful Session EJB
         A Home Interface Sample

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

         public interface TraderHome
             extends EJBHome
         {
             public Trader create (String traderName)
                 throws CreateException,
                        RemoteException ;
         }




SpCode                                  Enterprise JavaBeans   2.0   158
            Develop a Stateful Session EJB
            The Remote Interface

               Must follow a naming convention
                public interface <BeanName>
                    extends javax.ejb.EJBObject
                {
                    public <rmiRV> <businessMethod> (<rmiParams>)
                        throws [<businessException>,]...
                                javax.rmi.RemoteException ;
                }
               Must extend the javax.ejb.EJBObject interface
               Must define the signature of all business methods
               All business methods must have the specified throws clause
                  May include business exceptions
                    Must include RemoteException
               Their signature must only use RMI-compliant parameter

SpContent                                Enterprise JavaBeans                2.0   159
         Develop a Stateful Session EJB
         A Remote Interface Sample


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

 public interface Trader
     extends EJBObject
 {
   public TradeResult buy (String customerName, String stockSymbol, int shares)
       throws ProcessingErrorException, RemoteException ;

     public TradeResult sell (String customerName, String stockSymbol, int shares)
         throws ProcessingErrorException, RemoteException ;
                                                                    You may use a
     public double getBalance ()
                                                                 Converstional State
         throws RemoteException ;
 }

 public class TradeResult implements Serializable {
   //...
 }

 public class ProcessingErrorException extends Exception {
   //...
 }

SpCode                                Enterprise JavaBeans                   2.0       160
            Develop a Stateful Session EJB
            The Bean Class 1/3

               Must follow a naming convention

                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                {
                    public <rmiRV> <businessMethod> (<rmiParams>)
                        throws [<businessException>,…]
                                javax.rmi.RemoteException
                    { /* implementation */ }

                    // ...
                }
               Must be a non-abstract class
                and must implement the javax.ejb.SessionBean interface
               Must define the implementation of all business methods

SpContent                                Enterprise JavaBeans            2.0   161
            Develop a Stateful Session EJB
            The Bean Class 2/3

               Must define an ejbCreate method corresponding to each create method
                of the Home interface (e.g., mapping pattern)

                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                {
                    public void ejbCreate (<rmiParams>)
                        throws [javax.ejb.CreateException,]
                               [javax.rmi.RemoteException]
                    { /* implementation */ }

                     // ...
                }
               In general, the implementation is left empty
               This method is also part of the Container-contract methods

SpContent                                  Enterprise JavaBeans              2.0   162
            Develop a Stateful Session EJB
            The Bean Class 3/3

               Must implement the SessionBean Container-contract methods
                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                {
                    private SessionContext _context ;
                    public void setSessionContext (SessionContext)
                    { /* must keep a reference on the Context */ }

                     public void ejbRemove ()            { /* implem. */ }

                     public void ejbActivate () { /* implem. */ }
                     public void ejbPassivate () { /* implem. */ }
                     // ...
                }
               The ejbActivate/Passivate methods will be explain later


SpContent                                 Enterprise JavaBeans            2.0   163
         Develop a Stateful Session EJB
         A Bean Class Sample 1/2

 import javax.ejb.* ;
 import java.rmi.* ;
 public class TraderBean
     implements SessionBean
 {
   // Container-contract' methods
   private SessionContext _ctx ; // Mandatory code pattern for Context
   public void setSessionContext (SessionContext ctx) { _ctx = ctx ; }

     // May define a Conversational State (some attributs)
     public String _traderName ;
     public double _tradingBalance ;      New
                                                         Must explicitely initialize
     public void ejbCreate (String traderName)
            throws java.rmi.RemoteException              each attributes of the
     {                                                   Conversational state
       _traderName     = traderName ;                    (don't use default value)
       _tradingBalance = 0.0 ;
     }
     public void ejbRemove     () {}

   public void ejbActivate () {}
   public void ejbPassivate () {}
 //...

SpCode                                Enterprise JavaBeans                      2.0    164
         Develop a Stateful Session EJB
         A Bean Class Sample 2/2

     // Business methods implementation
     public TradeResult buy (String customerName, String stockSymbol, int shares)
         throws ProcessingErrorException, java.rmi.RemoteException
     {
       Properties props = _ctx.getEnvironment () ;
       try {
         int stockPrice = Integer.parseInt ((String)(props.get (stockSymbol))) ;
         // buy the stockSymbol on the market…
         _tradingBalance -= shares * stockPrice ; // update Conversational State
         return new TradeResult (shares, price) ;
       }catch (Exception e) {
         throw new ProcessingErrorException (e.getMessage ()) ;
       }
     }
     public TradeResult sell (String customerName, String stockSymbol, int shares)
         throws ProcessingErrorException, java.rmi.RemoteException
     {
       // sell the stockSymbol on the market...
     }

     public double getBalance ()
         throws RemoteException
     { return _tradingBalance ; }
 }

SpCode                                Enterprise JavaBeans                   2.0     165
            Develop a Stateful Session EJB
            Allocation of a new Bean instance in the Pool

                                         does not exist
                  create(args)


               1.newInstance()
               2.setSessionContext(sc)
               3.ejbCreate()

                                         method-ready           passive
                                                (Active)




SpContent                                Enterprise JavaBeans   2.0       166
         Develop a Stateful Session EJB
         Create method invoked by a client
                           <<HomeObject>> <<RemoteObject>>                                  <<BeanInstance>>

 : Client                  TraderHomeImpl         : TraderObject         : SessionContext     : TraderBean




            create(args)
                                            new


                                                        new

                                                                   new

                                                        setSessionContext(sc)

                                                            ejbCreate(args)




SpCode                                            Enterprise JavaBeans                                2.0      167
            Develop a Stateful Session EJB
            Business method invoked by a client

                                     does not exist




                                     method-ready            passive
               Business method               (Active)




SpContent                             Enterprise JavaBeans   2.0       168
         Develop a Stateful Session EJB
         Business method invoked by a client
                                               <Remote Object>                 <Bean Instance>
              : Client                             : TraderObject                  : TraderBean



                         Business method




                                           Business method



                                                                Business method
                                                                    “Delegation”




SpCode                                            Enterprise JavaBeans                            2.0   169
            Develop a Stateful Session EJB
            Remove method invoked by a client

                                     does not exist

                                                ejbRemove


                                                remove()

                                     method-ready            passive
                                             (Active)




SpContent                             Enterprise JavaBeans   2.0       170
         Develop a Stateful Session EJB
         Remove method invoked by a client


                                       <<Remote Object>>       <<Bean Instance>>

                        : Client        : TraderImpl            : TraderBean


                                   remove()
                                                       ejbRemove()




SpCode                                  Enterprise JavaBeans                       2.0   171
            Develop a Stateful Session EJB
            Passivation / Activation
               An instance of a stateful EJB may be passivated and activated by the
                container for performance and scalability issues.
               Automatic persistence for the conversational state is managed by the
                container.
               Connection-type resources (database connection, files, sockets) must
                be closed during passivation and re-opened during activation.

                    ejbPassivate() : called just before the passivation process
                     close your connections before the instance is destroyed

                    ejbActivate() : called just after the activation process
                     open your connections just after the instance has been created
                     (this should also be done in the ejbCreate() method)



SpContent                                    Enterprise JavaBeans                  2.0   172
            Develop a Stateful Session EJB
            Passivation / Activation

                                     does not exist



                                                               LRU

                                                             ejbPassivate()
                                     method-ready                             passive
                                              (Active)
                                                             ejbActivate()


                                                               method


                                   When ever the container
                                         wants to..




SpContent                             Enterprise JavaBeans                    2.0       173
         Develop a Stateful Session EJB
         Passivation / Activation
                                             <<Bean Instance>>
                    Container                    : TraderBean             Persistent
                                                                          storage

            Passivation phase


                                ejbPassivate()                                           Close the
                                                                                         connections



                                  Save the conversational state


           Activation phase

                                     Load the conversational state
                                 ejbActivate()


                                                                                  Establish the
                                                                                  connections




SpCode                                                  Enterprise JavaBeans                           2.0   174
         Develop a Stateful Session EJB
         The Bean Class Sample With Passivation

 // import...
 public class TraderBean
     implements SessionBean
 {
   // Container-contract' methods
   //...
   // May define a Conversational State (some attributs)
   //…

     // May have some sensitive resources according to Passivation mechanism
     private FileOutputStream _stream ;                 New
   public void ejbPassivate ()
   {
     try { _stream.close () ;
     } catch (Exception e) { System.out.println (e) ; }
   }
   public void ejbActivate ()
   {
     try { _stream = new FileOutputStream (this + ".log", true ) ;
     } catch (Exception e) { System.out.println (e) ; }
   }
 //...


SpCode                                Enterprise JavaBeans                     2.0   175
            EJB Basic Concepts
            Deploy a Stateful Session EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   176
    Deploy a Stateful Session EJB
    Deployment Descriptor Information

    EJB meta-information
       EnterpriseBeanClassName

       RemoteInterfaceClassName

       HomeInterfaceClassName

       BeanHomeName : JNDI name for the Home object




    Session information                                     New
       ManagementType : STATELESS or STATEFUL

       SessionTimeout   : the maximal life-time of the Session Bean




                                    Enterprise JavaBeans               2.0   177
            EJB Basic Concepts
            Use a Stateful Session EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   178
            Using a Stateful Session EJB
            A Client Sample 1/2
    import     javax.ejb.* ;
    import     javax.naming.* ;                                                        New
    import     java.rmi.* ;
    import     java.util.Properties ;                            The instance has a State

    public class Client
    {
      public static void main (String[] argv)
      {
        Context ctx = getInitialContext () ;
        TraderHome traderHome = (TraderHome)(ctx.lookup ("TraderHome")) ;             New
        Trader trader = traderHome.create ("Terry", "1234-1090") ;
        //...                                                The instance is really removed
        try{
          trader.remove () ;
        } catch (Exception e) {}
      }
      static public Context getInitialContext() throws Exception
      {
        Properties p = new Properties();
        p.put(Context.INITIAL_CONTEXT_FACTORY,
              "weblogic.jndi.T3InitialContextFactory");
        return new InitialContext(p);
      }
    }

SpContent                               Enterprise JavaBeans                     2.0          179
            Using a Stateful Session EJB
            A Client Sample 2/2

             try{                                                The client doesn’t need to
               double cashBalance = 0.0;                       update the conversational state
               for (int i = 1 ; i <= 5; i++) {
                 // Buying
                 stockName = "WEBL" ;
                 shareNumber = 100 * I ;
                 TradeResult tr = trader.buy (customerName, stockName, shareNumber) ;
                 // Keep track of the change in the Cash Account
                 // cashBalance -= (tr.numberTraded * tr.priceSoldAt) ;
                 // Selling
                 stockName = "INTL" ;
                 shareNumber = 100 * (i+1) ;
                 tr = trader.sell (customerName, stockName, shareNumber) ;
                 // Keep track of the change in the Cash Account
                 // cashBalance += (tr.numberTraded * tr.priceSoldAt) ;
               }
                                                                                New
               System.out.println ("CashBalance is :" + trader.getBalance ()) ;
             }catch (ProcessingErrorException pe) {
               System.out.println("Processing Error: " + pe);
             }




SpContent                                   Enterprise JavaBeans                     2.0         180
           EJB Basic Concepts
           Stateless / Stateful
                  Stateless                                       Stateful
       Better suited to heavy load management.       Less suitable for heavy load
       No client context is managed.                 management.
       Is not synchronized with the current          Able to manage a client context :
       transaction.                                  conversational state.
       Cannot manage a state buffer in a             The conversational state must be
       transactional context                         managed in a transactional context.
                                                     May synchronize a buffer with a
                                                     database in a transactional context.




                      The choice mostly depends on the kind of
              business process represented: with or without internal state

SpVersus                                Enterprise JavaBeans                   2.0          181
            EJB Basic Concepts
            Using a Stateless / Using a Stateful EJB

               Client java code for either type of EJB is very similar
                  Use the Home and Remote interfaces

                  No real technical difference




               A Stateful EJB maintains a conversational state:
                  This state depends on the client context : information exchanged
                   between client and Session EJB during the process execution.


               The client can use specific create methods provided by the Home
                interface to initialize the conversational state
               The client doesn’t have to manage the conversational state



SpContent                                  Enterprise JavaBeans                2.0    182
 EJB Basic Concepts
 Understanding the difference
Which one would you choose:


   Check if a stock symbol name is valid ?


   Booking a flight and holiday, at a travel agent’s web site ?


   Find out the billing price for a local telephone call ?


   Ordering spare parts for a Volvo, as a dealership application ?


   Manage a person’s bank account details ?

                              Enterprise JavaBeans                2.0   183
            EJB Basic Concepts
            Prerequisite : Persistence

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   184
    Prerequisite : Persistence
    Persistence Management
   The attributes of the object must be stored using a persistent mechanism
   Examples of persistence management:
      Use Java serialization mechanism

      Use a relational database through JDBC




              Object in memory
                                                        persistent storage



                                                                        database,
                                                                        files,
                                                                        etc...


                                 Enterprise JavaBeans                  2.0     185
    Prerequisite : Persistence
    Object-relational Mapping

      Associate a database table with a class
       Each instance of the class (each object) is stored in a row
      Associate a database column with an attribute of the class
                                                                      Client
                                               java class
                                                              clientId
                                                              Corporatename
                           Primary
                                                              address
                             key
                                                              town
Database table                                                Postcode



  clientId Corporatename             address           town   Postcode

  411MEB MEB                    1, Lichfield Road B ’ham B7 4TU
  411PIT PITCH                  34, London Road Chester C60 7YJ
  411WC World Company           1, The Strand     London W1 8PL


                                     Enterprise JavaBeans                2.0   186
            EJB Basic Concepts
            Develop a Container-Managed Entity EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   187
            Develop a container-managed Entity EJB
            Definition
               Represents persistent data or an entity of the information system or the
                application
               long-lived object
                   Is not limited to the client session

                   Depends on the entity or data lifetime in the application or in the
                    information system
               should be transactional in most cases
               May be accessed by multiple clients concurrently
                  Concurrent access is managed by the container or by the underlying
                   database
               Persistence may be managed by the container or by the EJB itself




SpContent                                    Enterprise JavaBeans                   2.0   188
 Develop a container-managed Entity EJB
 Intervening party



         Home Interface           Remote Interface

      “Create”                 Business                    Bean instance
New   “Find”                   Methods               Implementation of Business methods
                                                       and Container-contract' methods
             Signatures               Signatures




      Home Object            Remote Object




                                   Enterprise JavaBeans                         2.0       189
Develop a container-managed Entity EJB
Lookup and Use an EJB Instance


                           Home Interface               EJB Container

                        Home Object
                                            “Create”
                                              “Find”     New
                                     Remote Interface

                                  Remote Object
                                                               EJB instance
  EJB Client




                         Enterprise JavaBeans                        2.0      190
Develop a container-managed Entity EJB
What the developer needs to write?
    Write a Home interface : definition of the creation and lookup methods
     for this EJB
    Write a Remote interface : definition of the business services provided
     by the EJB
    Write the Bean instance : implementation of the business methods and
     the Container-contract methods

        1.                    2.                             3.

         Home Interface       Remote Interface
       “Create”              Business
New    “Find”                Methods
                                                         Bean instance
             Signatures            Signatures     Implementation of Business methods
                                                    and Container-contract methods




                               Enterprise JavaBeans                         2.0        191
            Develop a container-managed Entity EJB
            Class diagram

                                <<Interface>>                                        <<Interface>>
                                   Remote                                             Serializable
                                (from rmi)
                                                                                  (from io)




             <<Interface>>                                  <<Interface>>                                 <<Interface>>           <<Interface>>
               EJBHome                                        EJBObject                                   EntityBean             EntityContext
             (from ejb)                                     (from ejb)                                   (from ejb)             (from ejb)
                                                                                                                          New                New

                            1                                             2                                           3
             <<Interface>>                                  <<Interface>>            AccountPK             AccountBean
             AccountHome                                        Account                                   (from sample)
            (from sample)                                   (from sample)

                            New                                                               New


       AccountHomeObject                                AccountRemoteObject
      (from container)                                 (from container)
                                             creates                                                 Delegates


SpContent                                                                   Enterprise JavaBeans                                2.0               192
                         Develop a container-managed Entity EJB
                         Class description
                              <<Interface>>
                                Remote
                              (from rmi)
                                                                                <<Interface>>
                                                                                Serializable
                                                                             (from io)                                                                 The AccountHome interface
           <<Interface>>
            EJBHome
           (from ejb)
                                                          <<Interface>>
                                                           EJBObject
                                                          (from ejb)
                                                                                                        <<Interface>>
                                                                                                     EntityBean
                                                                                                     (from ejb)
                                                                                                                             <<Interface>>
                                                                                                                            EntityContext
                                                                                                                            (from ejb)
                                                                                                                                                          Provided by the developer

           <<Interface>>
           AccountHome
          (from sample)
                                                          <<Interface>>
                                                             Account
                                                          (from sample)
                                                                                AccountPK
                                                                              (from sample)
                                                                                                        AccountBean
                                                                                                      (from sample)
                                                                                                                                                          Manage the EJB life cycle (create, find, destroy)

       AccountHomeObject                               AccountRemoteObject
                                      creates                                                    delegates
      (from container)                                (from container)




                                                                                                                                                    The Primary Key AccountPK class
                                                                                                                                                       represents the identity of the EJB within its Home
                               <<Interface>>                                    <<Interface>>
                                 Remote                                         Serializable
                               (from rmi)                                    (from io)




                                                                                                                                                       Java class implementing Serializable.
            <<Interface>>                                 <<Interface>>                                  <<Interface>>        <<Interface>>
             EJBHome                                       EJBObject                                                         EntityContext
                                                                                                      EntityBean
           (from ejb)                                     (from ejb)                                  (from ejb)            (from ejb)




                                                                                                                                                 New
                                                                                                                                                       provided by the EJB developer
            <<Interface>>                                 <<Interface>>         AccountPK               AccountBean
            AccountHome                                      Account          (from sample)            (from sample)
           (from sample)                                  (from sample)




       AccountHomeObject                               AccountRemoteObject
                                       creates                                                     delegates
      (from container)                                (from container)




                                                                                                                                                       The AccountBean class
                                 <<Interface>>
                                   Remote
                                 (from rmi)
                                                                                   <<Interface>>
                                                                                   Serializable
                                                                                (from io)
                                                                                                                                                          Provided by the developer

              <<Interface>>
               EJBHome
                                                             <<Interface>>
                                                              EJBObject
                                                                                                            <<Interface>>
                                                                                                         EntityBean
                                                                                                                                 <<Interface>>
                                                                                                                                EntityContext
                                                                                                                                                          Implements business services

                                                                                                                                                          Implements the Container-contract methods
              (from ejb)                                     (from ejb)                                  (from ejb)            (from ejb)




               <<Interface>>                                 <<Interface>>        AccountPK                  AccountBean
               AccountHome                                      Account          (from sample)            (from sample)
              (from sample)                                  (from sample)




          AccountHomeObject                               AccountRemoteObject
                                            creates                                                  delegates
         (from container)                                (from container)




SpContent                                                                                                                                                         Enterprise JavaBeans                 2.0     193
            Develop a container-managed Entity EJB
            The primary key                    New
               Must be a Serializable class
               The attributes must be declared as public
               Must have a default (parameter-less) constructor
               The primary key attributes must be a subset of the container-managed
                attributes of the Entity Bean Class.
               The primary key attributes must have the same name and type as
                found in the Entity Bean Class. (Hence no accessor methods needed)


            public class AccountPK implements java.io.Serializable {

                public String accountId;

            }




SpContent                                  Enterprise JavaBeans           2.0     194
            Develop a container-managed Entity EJB
            The Home Interface

               Must follow a naming convention

                public interface <BeanName>Home
                    extends javax.ejb.EJBHome
                {
                    public <BeanName> create (<rmiParams>)
                        throws [<businessException>,]...
                               javax.ejb.CreateException,
                               javax.rmi.RemoteException ;
                    //...
                }


               Must define, at least, one creation method
               The throws clause may include some Business Exception

SpContent                                 Enterprise JavaBeans          2.0   195
            Develop a container-managed Entity EJB
            The Home interface 1/2
           Must define a findByPrimaryKey method
            public interface <BeanName>Home
                extends javax.ejb.EJBHome
            {
                public <BeanName> findByPrimaryKey (<PrimaryKey>)
                    throws [<businessException>,...]
                           javax.ejb.FinderException,
                           javax.rmi.RemoteException ;

             //...
            }


           Must return a Remote Object
           Must throw the RemoteException and FinderException



SpContent                            Enterprise JavaBeans        2.0   196
            Develop a container-managed Entity EJB
            The Home interface 2/2
               May define other finder methods
                  to find a single EJB

                     public <BeanName> findXXX (<rmiParams>)
                             throws [<businessException>,]...
                                    javax.ejb.FinderException,
                                    javax.rmi.RemoteException ;

                    to find a group of EJBs
                      public Enumeration findXXX (<rmiParams>)
                             throws [<businessException>,]...
                                    javax.ejb.FinderException,
                                    javax.rmi.RemoteException ;


               findXXX methods returning an Enumeration populate this enumeration
                with <RemoteInterface> objects



SpContent                                      Enterprise JavaBeans     2.0     197
            Develop a container-managed Entity EJB
            Finder methods
               Their description (implementation information) is provided at
                deployment time using a tool provided by the container

               Their Java implementation is generated in the Home class (generated
                by the container)

               Sun has not defined a standard language for object queries, the
                implementation descriptions are tool-specific




SpContent                                Enterprise JavaBeans               2.0   198
         Develop a container-managed Entity EJB
         The Accout EJB Home interface


          package beanManaged.interfaces;

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

          public interface AccountHome extends EJBHome {

              public Account create(String accountId, double initialBalance)
                throws CreateException, RemoteException;

              public Account findByPrimaryKey(AccountPK primaryKey)
                throws FinderException, RemoteException;

              public Enumeration findBigAccounts(double balanceGreaterThan)
                throws FinderException, RemoteException;
          }




SpCode                                    Enterprise JavaBeans                 2.0   199
            Develop a container-managed Entity EJB
            The Remote Interface

               Must follow a naming convention
                public interface <BeanName>
                    extends javax.ejb.EJBObject
                {
                    public <rmiRV> <businessMethod> (<rmiParams>)
                        throws [<businessException>,]...
                                javax.rmi.RemoteException ;
                }
               Must extend the javax.ejb.EJBObject interface
               Must define the signature of all business methods
               All business methods must have the specified throws clause
                  May include business exceptions
                    Must include RemoteException
               Their signature must only use RMI-compliant parameter

SpContent                                Enterprise JavaBeans                2.0   200
         Develop a container-managed Entity EJB
         The Account Remote interface

          package beanManaged.interfaces;

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

          public interface Account extends EJBObject {
            public double deposit(double amount)
              throws ProcessingErrorException, RemoteException;

              public double withdraw(double amount)
                throws ProcessingErrorException, RemoteException;

              public double balance()
                throws RemoteException;
          }

          public class ProcessingErrorException extends Exception {

               public ProcessingErrorException() {}

               public ProcessingErrorException(String message) {super(message);}
          }




SpCode                                    Enterprise JavaBeans                     2.0   201
            Develop a container-managed Entity EJB
            The Bean Class                                         1/4

               Must follow a naming convention
                public class <BeanName>Bean
                    implements javax.ejb.EntityBean
                {
                    public <Serializable type> <Attribute>;
                 // ...                                                         New

                     public <rmiRV> <businessMethod> (<rmiParams>)
                         throws [<businessException>,…]
                                 javax.rmi.RemoteException
                     { /* implementation */ }

                     // ...
                }
               Each attribute representing the persistent state must be public and
                Serializable


SpContent                                 Enterprise JavaBeans               2.0      202
            Develop a container-managed Entity EJB
            The Bean Class                                            2/4

               Must define a corresponding ejbCreate method for each create method
                of the Home interface (e.g., mapping pattern)

                public class <BeanName>Bean
                    implements javax.ejb.EntityBean
                {
                    public void ejbCreate (<rmiParams>)
                        throws [javax.ejb.CreateException,]
                               [javax.rmi.RemoteException]
                    { /* implementation */ }

                     // ...
                }


               Used to initialize the persistent state of the bean

SpContent                                   Enterprise JavaBeans            2.0   203
            Develop a container-managed Entity EJB
            The Bean Class                                         3/4

               Must define a corresponding ejbPostCreate method for each create
                method of the Home interface (e.g., mapping pattern)
      New
                     public void ejbPostCreate (<rmiParams>)
                         throws [javax.ejb.CreateException,]
                                [javax.rmi.RemoteException]
                     { /* implementation */ }

                     // ...



               This method is called after the EJB has been completely created
               It may be used to pass a reference to the EJB to any other object


SpContent                                 Enterprise JavaBeans               2.0    204
            Develop a container-managed Entity EJB
            The Bean Class                                    4/4

           Must implement the EntityBean Container-contract methods
            public class <BeanName>Bean
                implements javax.ejb.EntityBean
            {
                private entityContext _context ;
                public void setEntityContext (EntityContext)
                { /* must keep a reference on the Context */ }
                public void unsetEntityContext (EntityContext)
                { /* free the context reference */ }      New

                public void ejbRemove ()           { /* implem. */ }

                public void ejbActivate () { /* implem. */ }
                public void ejbPassivate () { /* implem. */ }
                // ...
            }


SpContent                              Enterprise JavaBeans            2.0   205
         Develop a container-managed Entity EJB
         The AccountBean class (persistent State)

          package beanManaged.server;

          public class AccountBean implements EntityBean {
            private EntityContext ctx;

              public            String      accountId;
              public            double      balance;

          //…




          public class AccountPK implements java.io.Serializable {

              public String accountId;

          }



SpCode                                   Enterprise JavaBeans        2.0   206
            Develop a container-managed Entity EJB
            Add an instance in the pool
                                            does not exist


                  1. newInstance()
                  2. setEntityContext(ec)



                                               pooled




                                                ready


SpContent                                   Enterprise JavaBeans   2.0   207
            Develop a container-managed Entity EJB
            Add an instance in the pool
                                                            <<Bean instance>>
                        Container         : EntityContext      : AccountBean



                                          newInstance ()
                                    new

                                      setEntityContext(ec)




SpContent                                 Enterprise JavaBeans                  2.0   208
            Develop a container-managed Entity EJB
            Remove an instance from the pool
                                    does not exist



                                                 1.unsetEntityContext()
                                                 2.finalize()


                                       pooled




                                        ready


SpContent                            Enterprise JavaBeans                 2.0   209
            Develop a container-managed Entity EJB
            Remove an instance from the pool
                                                                 <<Bean instance>>

                   JVM                Container                    : AccountBean


                                                  unsetEntityContext()


                         finalize()




SpContent                             Enterprise JavaBeans                       2.0   210
            Develop a container-managed Entity EJB
            Create an Entity EJB
                                      does not exist




                                            pooled


                    ejbCreate(args)
                    ejbPostCreate(args)




                                             ready

                                                 Business method
SpContent                                 Enterprise JavaBeans     2.0   211
            Develop a container-managed Entity EJB
            Create an Entity EJB
                  <<Home object>>                    <<Remote object>>               <<Bean instance>>
                : AccountHomeImpl                   : AccountImpl                      : AccountBean     Persistent
 : Client                                                                                                storage


        create(args)
                                                     ejbCreate(args)

                               Find the persistent state of the instance
                                                                    Create the entity in the database


                                     new
 Association of
 the EJB object with the                         ejbPostCreate(args)
 primary key object
 generated by the container

 The EJB creation is
 complete

                              Business method
                                                                     Business method




SpContent                                                     Enterprise JavaBeans                          2.0       212
         Develop a container-managed Entity EJB
         The AccountBean class (create and postCreate)


         //…
          public void ejbCreate(String accountId, double initialBalance)
             throws CreateException
         {
             this.accountId = accountId;
             this.balance   = initialBalance;

         }

         public void ejbPostCreate(String accountId, double initialBalance)
           throws RemoteException
         {
           //Log some information concerning the creation of the bean
           //Give a reference to the EJB to another object
         }

         public   void   ejbActivate() { /* if needed */}
         public   void   ejbPassivate() {/* if needed */}
         public   void   ejbLoad() {/* if needed */}
         public   void   ejbStore() {/* if needed */}
         //…



SpCode                                       Enterprise JavaBeans             2.0   213
         Develop a container-managed Entity EJB
         The AccountBean class (Update business state)


         //…
          public double deposit(double amount) throws ProcessingErrorException {
             balance += amount;
             return balance;
           }


          public double withdraw(double amount) throws ProcessingErrorException {
             if (amount > balance) {
               throw new ProcessingErrorException("Request to withdraw $" +
                                                   amount +
                                                  " more than balance " +balance"
             }
             balance -= amount;
             return balance;
           }
         //…




SpCode                                  Enterprise JavaBeans                  2.0   214
            Develop a container-managed Entity EJB
            Delete an Entity
                                    does not exist




                                       pooled



                                                ejbRemove()
                                                       Not only put the instance
                                                       back in the pool,
                                        ready          but also delete the persistent
                                                       record of the Entity EJB


SpContent                            Enterprise JavaBeans                2.0       215
            Develop a container-managed Entity EJB
            Delete an Entity

                           <<Remote object>>                <<Bean instance>>

                                : AccountImpl                    : Account              Persistent
              : Client
                                                                   Bean                 storage

                         remove()
                                                ejbRemove()

                                        Delete the entity from the persistent storage




SpContent                                       Enterprise JavaBeans                    2.0          216
Develop a container-managed Entity EJB
Delete an Entity from the Client

   Two methods for destroying an Entity Bean instance


   Using the remote object interface:
      remote.remove()

      Destroys “this” instance




   Using the home interface:
      home.remove( PrimaryKey )

      Avoids overhead of lookup, remote object construction, etc.




   Both techniques invoke ejbRemove() on the EntityBean, result in
    destruction of bean and persistent data

                               Enterprise JavaBeans                  2.0   217
         Develop a container-managed Entity EJB
         The AccountBean class (Automatic state removal)

         //…
          public void ejbRemove() throws RemoteException
         {
               System.out.println("Removing $" + balance +"at : " +
                                         new Date() + "\n")

         }




         After the ejbRemove call, the instance will be deleted from the
         persistent storage!

              ejbRemove method can be used to record, or notify others of its
              removal.



SpCode                                   Enterprise JavaBeans         2.0       218
            Develop a container-managed Entity EJB
            Find an Entity EJB
                                   <<Home object>>                   <<Remote object>>

                                     : AccountHomeImpl                   : AccountImpl            Persistent
              : Client
                                                                                                  storage


                  find<METHOD>(args)


                                                       Find the entity/entities in the database


                                                             new



                         Association of the EJB object(s) with
                         the primary key objects generated
                         by the container


SpContent                                            Enterprise JavaBeans                         2.0          219
            Develop a container-managed Entity EJB
            Load/Store mechanism
               Allows you to perform some operation on the persistent state before
                the container saves it, in persistent storage.
                   compress the data

                   transform complex objects into basic attributes

                   ...


               Two methods are called by the container before and after each access
                to the database:
                   ejbStore() : called just before the persistent state is written
                    (compress or convert your data)

                    ejbLoad() : called just after the persistent state has been loaded from the
                     database
                     (uncompress or convert your data)



SpContent                                    Enterprise JavaBeans                   2.0      220
            Develop a container-managed Entity EJB
            Activation / Passivation
                                       does not exist




                                          pooled



                       ejbActivate()               ejbPassivate()
                       ejbLoad()                   ejbStore()



                                           ready


SpContent                              Enterprise JavaBeans         2.0   221
            Develop a container-managed Entity EJB
            Passivate an EJB instance
                                               <<Bean Instance>>
                  Container                     : AccountBean           Persistent
                                                                        storage

                                     ejbStore()

                                 Find the persistent state of the EJB

                                Update the database

                                  ejbPassivate()



                                ejbActivate()

                          Load the entity state from the database
                        Update the EJB
                                   ejbLoad()



SpContent                                       Enterprise JavaBeans                 2.0   222
         Develop a container-managed Entity EJB
         The AccountBean class(Load/Store object conversion)

          package beanManaged.server;

          public class AccountBean implements EntityBean {
            private EntityContext ctx;

            public            String         accountId;
            public            double         balance;
            public            String         ownerName;
            public            String         ownerAddress;

            private transient Person owner

            public void ejbStore() throws RemoteException {
                   ownerAddress = owner.getAddress();
                   ownerName = owner.getName();
            }


            public void ejbLoad() throws RemoteException {
                   owner = new Person(ownerName, ownerAddress);
            }




SpCode                                  Enterprise JavaBeans      2.0   223
            EJB Basic Concepts
            Deploy a Container-Managed Entity EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   224
Deploy a Container-Managed Entity EJB
How to deploy Entity EJB



               DeploymentDescriptor
                                                       Home
                                                     Interface
            Technical         Meta
            information    information                Remote
                                                     Interface
            Security        Class
             policy         names                      Bean
                                                     instance




   Manage Primary Keys
   Manage Persistence


                              Enterprise JavaBeans               2.0   225
          Deploy a Container-Managed Entity EJB
          EntityDescriptor

                    DeploymentDescriptor
                    (from deployment)                                    Entity Beans use a separate descriptor :
                                                                          EntityDescriptor

                                                                              PrimaryKeyClassName :
 SessionDescriptor                                EntityDescriptor
                                        (from deployment)
                                                                               the primary key class for this bean
(from deployment)



                                                                              ContainerManagedFields : persistent state
                                           getPrimaryKeyClassName()
                                           setPrimaryKeyClassName()            managed by the container
                                           getContainerManagedFields()
                                           setContainerManagedFields()




                    ContainerManagedFields must be non-empty for container-
                    managed Beans (automatic persistence)


                                                                     Enterprise JavaBeans                    2.0     226
    Deploy a Container-Managed Entity EJB
    Persistence Management
   The EJB specification doesn’t specify any particular persistence
    mechanism
      Implementation up to the vendor

   Examples of persistence management:
      Use Java serialization mechanism

      Use a relational database through JDBC

      Use a legacy application



               EJB in memory
                                                       EJB storage



                                                                     database,
                                                                     files,
                                                                     etc...


                                Enterprise JavaBeans                 2.0    227
Deploy a Container-Managed Entity EJB
Using JDBC and a database

The deployment descriptor will include server-specific information:
 Provide database information:

    How to access the database

 Provide data storage information:

    How these attributes should be stored in the database

        Object to relational mapping




                            Enterprise JavaBeans               2.0    228
            EJB Basic Concepts
            Use a Container-Managed Entity EJB

               Prerequisites
               Develop a Stateless Session EJB
               Deploy a Stateless Session EJB
               Use a Stateless Session EJB
               Develop a Stateful Session EJB
               Deploy a Stateful Session EJB
               Use a Stateful Session EJB
               Prerequisite : Persistence
               Develop a Container-Managed Entity EJB
               Deploy a Container-Managed Entity EJB
               Use a Container-Managed Entity EJB

SpContent                              Enterprise JavaBeans   2.0   229
Use a Container-Managed Entity EJB
Lookup and Use an Entity EJB


                           Home Interface                EJB Server

                        Home Object
                                            “Create”
                                                “Find”
                                     Remote Interface

                                  Remote Object
                                                             EJB instance
  EJB Client




   Use Entity EJB with Primary Keys

                         Enterprise JavaBeans                      2.0      230
            Use a Container-Managed Entity EJB
            Difference with Session EJBs

               Similar to using a Session Bean
                  Use the Home and Remote interfaces

                  Main differences :

                      Use finder methods on the Home interface

                      Use a Primary Key




               May be concurrently accessed by multiple clients
                  Concurrent access is transparent and managed by the container




SpContent                                Enterprise JavaBeans                2.0   231
            Use a Container-Managed Entity EJB
            Find an account or a collection of accounts
                                      <<JNDI NameSpace>>     << Bean Instance >>

                   : Client             :InitialContext      : AccountHome
                                                                             Find an
                        lookup (HomeName)                                    Account by
                                                                             Specifying its
                                 findByPrimaryKey(key)                       Primary key

                                 create(id,initialBalance)                     Find a collection of
if (FinderExceptionl)
                                                                               Account having their
                                                                               balance greater than
                                                                               “balance”
                          findBigAccounts(balanceGreaterThan)




SpContent                                    Enterprise JavaBeans                             2.0     232
            Use a Container-Managed Entity EJB
            Find or create an Account

      package client;
       public class Client {
        static String accountId = "10020";
        public static void main(String[] args) {

             double balance = 3000;
             AccountPK accountKey = new AccountPK();
             accountKey.accountId = accountId;
             Context ctx = getInitialContext();
             AccountHome home=(AccountHome)ctx.lookup( "AccountHome" );
             // Find the Account or create it.
             Account ac = null;
             try {
                 ac = (Account) home.findByPrimaryKey(accountKey);
             }catch (FinderException e) {
                 ac = home.create(accountId, balance);
             }
      //…




SpContent                                  Enterprise JavaBeans           2.0   233
            Use a Container-Managed Entity EJB
            Find a collection of Accounts



      //…

               Enumeration e = home.findBigAccounts(300);

               if (e != null) {
                 while (e.hasMoreElements()) {
                   Account bigAccount= (Account) e.nextElement();
                   System.out.println("Account " + bigAccount.getPrimaryKey() +
                                      "; balance is $" + bigAccount.balance());

                   }
               }
      //…




SpContent                                  Enterprise JavaBeans                   2.0   234
            Use a Container-Managed Entity EJB
            Destroy an Account


      //…

             try{
                 //using the Remote interface
                 ac.remove() ;

                //Using the Home interface and a primary key
                home.remove (ac.getPrimaryKey()) ;

             }catch (Exception e) {

          }
      }//end of the client




SpContent                                  Enterprise JavaBeans   2.0   235
            Use a Container-Managed Entity EJB
            Entity EJB life cycle from the client side
                                                                          A method call to
                                                                        the reference throws
                                                                      NoSuchObjectException



                     Does not exist          Drop the reference       Does not exists
                           and                                               and
                   is not referenced                                   is referenced

                                                                                   Ref.remove()
                                                                                         or
                             Home.remove(…)                                      home.remove(…)
      Direct insertion               or                                                  or
                             direct suppression                                 suppression directe

                                           Handle.getEJBObject()
                         Exists                     or                       Exists
                           and                home.find(…)                    and
                   is not referenced                                     is referenced
                                             Drop the reference

                                                                   Metod call to the reference

SpContent                                   Enterprise JavaBeans                       2.0       236
            EJB Basic Concepts
            Summary
               The aim of The EJB model is to provide a technical framework for
                developing server-side Java components
               A SessionEJB is meant to represent a business process with or
                without internal state
                  The conversational state consistency is managed by the EJB


               An Entity EJB is meant to represent a business entity
                  The persistent state can be automatically managed.


               A deployment descriptor contains additional information about the
                bean.
                  Meta-information

                  Technical information




SpContent                                Enterprise JavaBeans              2.0      237
Enterprise JavaBeans TM
 - Advanced Concepts -




                          Template 2.4
               Advanced concepts
               Objectives

                  Understand EJB Transaction concepts
                  Understand JDBC programming
                  Be able to develop a Transactional client
                  Be able to use Transaction attributes at deployment time
                  Be able to enforce a security policy at deployment time
                  Be able to develop an Entity with Bean-managed persistence
                  Be able to develop a Session Bean with SessionSynchronization




SpObjectives                                Enterprise JavaBeans              2.0   239
            Advanced concepts
            Contents
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   240
            Advanced concepts
            Advanced EJB client : Handles
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   241
            Advanced EJB client : handles
            What is an EJB handle ?


                A serializable object referencing an EJB


                May be stored and reused anytime
                   A handle may be stored using Java Serialization




                May be obtained by asking the Remote interface


                The validity depends on the EJB type




SpContent                                 Enterprise JavaBeans        2.0   242
            Advanced EJB client : handles
            Serializing in a file

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

      import statelessSession.interfaces.*;
       public class Client {
        public static void main(String[] args) {
          Context ctx = getInitialContext () ;
          TraderHome traderHome = (TraderHome)(ctx.lookup ("TraderHome")) ;
          Trader trader = traderHome.create () ;
          String traderName   = "Terry" ;
          HandleSerialize (trader.getHandle() , traderName) ;
        }

            static public void HandleSerialize(Handle handle, String file) throws
                             Exception
            {
                FileOutputStream      fo = new FileOutputStream(file)   ;
                ObjectOutputStream    o  = new ObjectOutputStream (fo) ;
                o.writeObject(handle) ;
                o.close () ;
            }
      }



SpContent                                  Enterprise JavaBeans                     2.0   243
            Advanced EJB client : handles
            Obtain an EJB reference from a serialized handle


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

      import statelessSession.interfaces.*;
      public class Client {
        public static void main(String[] args) {
        String traderName   = "Terry" ;

            Handle handle = HandleDeSerialize (traderName)         ;

            Trader trader = (Trader)handle.getEJBObject()          ;

            static public Handle HandleDeSerialize(String file) throws Exception {
              FileInputStream fi = new FileInputStream(file) ;
              ObjectInputStream o = new ObjectInputStream (fi) ;
              Handle handle = (Handle)o.readObject() ;
              o.close () ;
              return handle ;
            }
      }




SpContent                                   Enterprise JavaBeans                     2.0   244
            Advanced concepts
            Prerequisite : Distributed Transactions
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   245
Prerequisite : Distributed Transactions
What is a Transaction?

   A transaction is an all-or-nothing unit of work
      Can span several screens, several CORBA requests, several database
        updates
   The classic transaction example: Transferring Money
      First, take $10000 from your account

      Then, add it to my account

      If the system goes down in between, what happens?

      If another user looks at our accounts, what happens?


   Transactions manage updates to Resources




                              Enterprise JavaBeans             2.0      246
Prerequisite : Distributed Transactions
ACID Properties

   Atomicity
      All modifications in a transaction must be all-or-nothing


   Consistency
      The system cannot be in an intermediate state


   Isolation
       Other users cannot see changes made in an incomplete transaction


   Durability
      Once the transaction is terminated, the changes cannot be lost




                                Enterprise JavaBeans               2.0     247
Prerequisite : Distributed Transactions
Begin                                                       Transactional
                                                               Context

                                            TC
                    JTS
  1 begin                                          4 Add (XA)               7 Add (XA)

              2 service                    3 SQL
  Client


                          5 service


                                           6 SQL



       EJB server
       Transactional Resource


                                Enterprise JavaBeans                  2.0       248
Prerequisite : Distributed Transactions
2 Phases Commit                                               Transactional
                                                                 Context

                                             TC
 1 commit           JTS
                                     6 OK             2 prepare      4 commit

  Client


                                               7 OK
                                                             3 prepare         5 commit




       EJB server
       Transactional Resources


                                 Enterprise JavaBeans                    2.0       249
Prerequisite : Distributed Transactions
Rollback                                                     Transactional
                                                                Context

                                            TC
 1 commit           JTS
                                    6 KO             2 prepare        4 rollback

  Client


                                              7 KO
                                                            3 prepare           5 rollback

                                                                 Failed


       EJB server
       Transactional Resource


                                Enterprise JavaBeans                      2.0        250
Prerequisite : Distributed Transactions
JTS and the UserTransaction interface

   It is possible to demarcate transactions using JTS
    (Java Transaction Service, package javax.jts)
   The UserTransaction interface
      high-level API to demarcate transactions : begin, commit, rollback

      forbid a commit on a transaction

      obtain the status of the transaction

      set a timeout for a transaction                    <<Interface>>
                                                         UserTransaction

                                                      begin()
                                                      commit()
                                                      rollback()
                                                      setRollbackOnly()
                                                      getStatus()
                                                      setTransactionTimeout()




                               Enterprise JavaBeans                    2.0      251
            Advanced concepts
            Advanced EJB client : Transactions
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   252
Advanced EJB client : Transaction management
Using the UserTransaction interface

   An EJB client will typically use JTS to demarcate transactions


   It is up to the EJB server to provide an implementation of the
    UserTransaction interface
       Nested transactions are not supported


   The specifications do not specify how the client can gain access to the
    UserTransaction implementation
      Server-specific client code
                                                          <<Interface>>
                                                         UserTransaction
      using JNDI is one possible solution
                                                      begin()
                                                      commit()
                                                      rollback()
                                                      setRollbackOnly()
                                                      getStatus()
                                                      setTransactionTimeout()


                              Enterprise JavaBeans                 2.0          253
            Advanced EJB client : Transaction management
            Using Transaction demarcation
      package client;
       public class Client {                                          JNDI name of the
        public static void main(String[] args) {                       UserTransaction
          AccountPK accountKey_1 = new AccountPK();
          accountKey_1.accountId = 10020;
          AccountPK accountKey_2 = new AccountPK();
          accountKey_2.accountId = 10040;

           Context ctx = getInitialContext();
           AccountHome home = (AccountHome)ctx.lookup("AccountHome");
           UserTransaction current=
                 (UserTransaction)ctx.lookup("javax.jts.UserTransaction") ;
           Account ac_1 ; Account ac_2 ;
           ac_1 = (Account) home.findByPrimaryKey(accountKey_1) ;
           ac_2 = (Account) home.findByPrimaryKey(accountKey_2) ;
                                current.setTransactionTimeout(120) ;
         try{
           current.begin () ;
                ac_1.withdraw(1000) ;
                ac_2.deposit (1000) ;
           current.commit () ;
         }catch (javax.rmi.RemoteException e) {
           current.rollback () ;
         }
        }

SpContent                                Enterprise JavaBeans                  2.0       254
            Advanced EJB client : Transaction management
            Standard EJB exceptions
                 System exception
                    java.rmi.RemoteException

                    indicates a system-level error to the client

                       socket error, DBMS error, etc.

                       May be thrown by the container or the EJB


                 Application exception
                    java.lang.Exception

                    indicates an application-level error to the client

                       The exception semantic is defined by the application and is

                        application-specific
                    The EJB model defines three standard application exceptions:

                       javax.ejb.CreateException, javax.ejb.RemoveException,

                        javax.ejb.FinderException

SpContent                                  Enterprise JavaBeans                 2.0   255
            Advanced EJB client : Transaction management
            Within a transactional context 1/2

                 javax.jts.TransactionRolledBackException
                     indicates that the transaction will be rolled back

                     Any try to commit the transaction is useless


                 javax.jts.HeuristicRolledbackException
                     Indicates that a heuristic decision has been taken during the
                      transaction: one or more resources have been rolled back (The
                      transaction will be rolled back).
                 javax.jts.HeuristicCommitException
                     Indicates that a heuristic decision has been taken during the
                      transaction: one or more resource have been committed




SpContent                                    Enterprise JavaBeans                 2.0   256
            Advanced EJB client : Transaction management
            Within a transactional context 2/2

                 javax.rmi.TransactionRequiredException
                     The client must start a transaction before invoking this method


                 java.rmi.RemoteException
                     Difficult to know if the method has been executed

                     It is recommended to rollback the transaction


                 Other Exceptions
                    The client may continue to work within the same transactional context




SpContent                                   Enterprise JavaBeans                  2.0    257
            Advanced concepts
            Advanced Deployment : Transactions
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   258
Advanced Deployment : Transaction attributes
DeploymentDescriptor : Transactions
   Explicit transaction management using JTS
      Client-managed transaction

      Bean-managed transaction



   Implicit transaction management:
       Container-managed transaction




   Information contained in the deployment descriptor :
       TransactionAttribute : who manages the transactions?


        IsolationLevel : are the changes visible before the commit?
        RunAsMode & RunAsIdentity : Identity of the component
         (related to security)




                                       Enterprise JavaBeans            2.0   259
Advanced Deployment : Transaction attributes
EJB ControlDescriptor




                         Enterprise JavaBeans   2.0   260
  Advanced Deployment : Transaction attributes
   Who manages transactions?
                                                        Account
          begin                             deposit     Bean 1
          ac1.deposit     Container
          ac2.withdraw                     withdraw     Account
 Client   commit                                        Bean 2



                                         1-begin
          ac1.deposit    Container       2-deposit      Account
                                         3-commit        Bean
Client



                                                              1-begin
          ac1.deposit    Container         deposit    Account 2-deposit
                                                       Bean   3-commit
Client


                             Enterprise JavaBeans             2.0    261
Advanced Deployment : Transaction attributes
EJB Transaction Attributes

   The EJB Specification defines 6 transaction attributes:

        TX_NOT_SUPPORTED
        TX_SUPPORTS
        TX_MANDATORY
        TX-REQUIRED
        TX_REQUIRES_NEW
        TX_BEAN_MANAGED




                             Enterprise JavaBeans             2.0   262
Advanced Deployment : Transaction attributes
EJB Transaction Attributes

   TX_NOT_SUPPORTED
      The EJB does not support transactions

      The container never implicitly starts a transaction for this EJB

      If the client call is associated with a transaction, the client transaction is
       suspended during the method execution
      Client calls included in a transaction will not be executed within the
       scope of the transaction.

              1-begin
              2-deposit           Container              deposit         Account
                                                                          Bean
    Client    3-commit



                  deposit        Container               deposit         Account
                                                                          Bean
    Client

                                  Enterprise JavaBeans                    2.0       263
Advanced Deployment : Transaction attributes
EJB Transaction Attributes

   TX_SUPPORTED
      A call to an EJB’s method may be included in a transaction

      The container never implicitly start a transaction

      EJB’s methods execute within client-managed transactions




             1-begin                                                Account
             2-deposit         Container              deposit        Bean
    Client   3-commit



                deposit       Container               deposit       Account
                                                                     Bean
    Client

                               Enterprise JavaBeans                  2.0      264
Advanced Deployment : Transaction attributes
EJB Transaction Attributes

   TX_MANDATORY
      A call to an EJB’s method must be included in a transaction

      The container never implicitly starts a transaction

      Transactions must be managed by the client

      Client calls not included in a transaction will result in a runtime
       exception (TransactionRequiredException)


              1-begin                                                    Account
              2-deposit           Container              deposit          Bean
     Client   3-commit



                  deposit         Container                              Account
                                                                          Bean
     Client

                                  Enterprise JavaBeans                       2.0   265
Advanced Deployment : Transaction attributes
EJB Transaction Attributes

   TX_REQUIRED
      EJB methods always execute within a transaction

      EJB methods execute within the client transaction if any

      The container implicitly starts a new transaction if the client call is not
       associated with a transaction


              1-begin                                                    Account
              2-deposit           Container              deposit          Bean
    Client    3-commit


                                                 begin
                  deposit        Container            deposit            Account
                                                                          Bean
    Client                                        commit

                                  Enterprise JavaBeans                    2.0        266
Advanced Deployment : Transaction attributes
EJB Transaction Attributes

   TX_REQUIRES_NEW
      The container always starts a new transaction before delegating a
       method call to the EJB and attempt to commit the transaction after the
       method execution
      If the client call is associated with a transaction, the client transactions
       is suspended during the execution of the business method


              1-begin                            begin
                                  Container                               Account
              2-deposit                                   deposit          Bean
     Client   3-commit                           commit

                                                  begin
                  deposit         Container           deposit            Account
                                                                          Bean
     Client                                       commit

                                   Enterprise JavaBeans                   2.0         267
  Advanced Deployment : Transaction attributes
  EJB Transaction Attributes
     TX_BEAN_MANAGED
         The EJB supports transaction

         The container never starts a transaction for this EJB

         The Bean developer can use jts UserTransaction to demarcate transactions manually
          within the Bean.
         If the client call is associated with a transaction, the client transactions is suspended
          during the method execution and resumed after the method execution
     More flexible customization, but technical code is included within the EJB Java
      implementation




                                                                                    begin
                deposit          Container                 deposit          Account   deposit
                                                                             Bean
Client                                                                              commit


                                         Enterprise JavaBeans                           2.0           268
Advanced Deployment : Transaction attributes
EJB Transaction isolation levels

   When a transaction has been started, what is visible for me

        Do I read data updated by other users before transaction commit?
        Can I read the same data twice and have different results?
        Can I access rows deleted by other users before transaction commit?

   The EJB specification defines 4 isolation levels :
      TRANSACTION_READ_UNCOMMITTED

      TRANSACTION_READ_COMMITTED

      TRANSACTION_REPETABLE_READ

      TRANSACTION_SERIALIZABLE




                                     Enterprise JavaBeans                      2.0   269
Advanced Deployment : Transaction attributes
TRANSACTION_READ_UNCOMITTED (Dirty read)

   It is possible to read modifications of data being carried out by another
    transaction (incomplete).

                                            Goal = 0
                         Transaction 1                  Transaction 2


       Update Goal = 1

                                                                    Read : Goal = 1
                                                                          You read the TX
                                                                        Prepared information

                                                                   !! Goal May be rolled back !!
                                                                   but you read the intermediate
                   commit                                                     data !!!
                                         Goal = 1 (If committed)
                                         Enterprise JavaBeans                         2.0      270
Advanced Deployment : Transaction attributes
TRANSACTION_READ_COMMITED

        Dirty reads are prevented - uncommitted data cannot be accessed.

        Repeatable reads are not prevented - Two access to the same data
         could result in different values if another transaction has modify this data
         and has committed.

        Phantom reads are not prevented - Data inserted or deleted by another
         transaction (which has committed) are accessible. This could lead to
         different results to the same reading request.


                                         Goal = 0
                              Transaction 1            Transaction 2                Dirty Read Prevented
                                                                                   Repeatable Read allowed,
                                                                 First Read : Goal = 0
          Update : Goal = 1


               Commit
                                                                 Second Read : Goal = 1

                                              Commit
                                        Enterprise JavaBeans                                 2.0          271
Advanced Deployment : Transaction attributes
TRANSACTION_REPEATABLE_READ
     Two successive accesses to a same data give the same result.
     Dirty reads are prevented
      (uncommitted updates are not visible)
     Repeatable reads are prevented
      (updates are not visible if committed after a first read occurred)
     Phantom reads are not prevented
      (all committed inserts or deletes are visible)
                  Transaction 1
                                    Fixtures        Transaction 2

                                  Manchester = 1                     Manchester = 1
 Manchester = 2
 London = 0
                                                                    Manchester = 1
                                  Manchester = 2                    London = 0          Number Total
                                                                                        goals = 1
              Commit              London = 0
                                                   Transaction 3

      Insert in Soccer Score,                                                               Number of total
      new insert is visible to                                        Manchester = 2
                                                                                            goals = 2
        second transaction                                           London = 0
                    Update is Not Visible
                                    Enterprise JavaBeans                              2.0           272
Advanced Deployment : Transaction attributes
TRANSACTION_SERIALIZABLE
          Dirty reads are prevented

          Repeatable reads are prevented

          Phantom reads are prevented
    The transactions virtually run one after another
                     Transaction 1
                                       Fixtures        Transaction 2

                                     Manchester = 1
    Manchester = 2                                                      Manchester = 1
    London = 0

                                     Manchester = 2
                                                                       Manchester = 1
                 Commit              London = 0
                                                      Transaction 3    Commit

                                                                        Manchester = 2
                                                                        London = 0


                                       Enterprise JavaBeans                              2.0   273
Advanced Deployment : Transaction attributes
Customizing transaction management

   A transaction management defines:
      A transaction attribute

      A transaction isolation level


   A default transaction management can be associated with the entire EJB
   Another transaction management can be associated with each EJB’s method
   If a transaction management is specified for a method, it overrides the default
    transaction attribute




                                    Enterprise JavaBeans                      2.0     274
Advanced Deployment : Transaction attributes
EJB transaction restrictions 1/2

   TX_BEAN_MANAGED value cannot be mixed with other transaction attributes values.
       If one of the method has been deployed with TX_BEAN_MANAGED as transaction
        attribute, the entire bean must be deployed with TX_BEAN_MANAGED.
   UserTransaction inside beans can only be used with EJBs deployed as
    TX_BEAN_MANAGED
   Transaction isolation levels must be consistent within the same transaction
       If method-level ControlDescriptors are used, the isolation levels of all method invoked on
        the EJB instance during one transaction must be the same (the isolation level may not
        change during the transaction)




                                       Enterprise JavaBeans                         2.0         275
         Transaction Management
         EJB transaction restrictions 2/2
            When using explicit transaction demarcation on a session Bean, a
             client should not invoke methods in a way that would lead to :
               The EJB instance is already associated with a transaction
              AND
               The container invoke a method on this instance requiring a new transaction or no
                transaction.
            The container will throw a RemoteException if any conflict with these
             restrictions is encountered at runtime.

                          TX-Required
                                                                           deposit
         1-Begin
         2-Deposit                                                                             Account
                                              Container
         3-Withdraw                                                                             Bean
Client                   TX-RequiresNew                        Begin
         4-Commit
         4-Rollback
                                                                         Withdraw


                                             Enterprise JavaBeans                        2.0       276
            Advanced concepts
            Prerequisite : Database access with JDBC
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   277
          JDBC
Java DataBase Connectivity




                             Template 2.4
JDBC




   Relational Databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   279
JDBC
Relational Databases


   Relational Databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   280
Relational databases
Table, Column, Primary key

               Client                                    0..n          Invoice

     clientId                                                   clientId
     corporateName                                              number
     address                                                    dateIssue
                                          Primary
     town                                                       amount
                                            key
     Postcode                                                   amountVAT

                                          Table

                                          Column


   The relational schema structures information in Tables.
   A Table is defined by:
        a group of columns defined by a name, a type, a default value...
        A primary key allowing information to be located.




                                      Enterprise JavaBeans                       2.0   281
Relational databases:
Primary keys
   Client
   clientId   corporateName              address            town      postcode

   411EDF EDF-GDF                        1, rue du gaz       Paris    75017
   411PIT PITCH                          2916 Preston        Dallas   75240
   411WC World Company                   12 Court Road      London    100001

                                                                                     row
                                         Column
   Invoice

   clientId   number          dateIssue            amount             amountVAT

   411EDF 9701                31/01/97             10.000             12.600
   411WC 9702                 31/01/97              1.000             1.260
   411WC 9703                 29/02/97             20.000             24.120




                                Enterprise JavaBeans                           2.0    282
Relational databases:
SQL: Standard Query Language

   Standard language allowing manipulation of data in a relational database.
        SELECT * FROM Client WHERE town = 'PARIS';
        SELECT clientId, corporateName FROM Client;
        SELECT amount FROM Invoice WHERE clientId = '411WC';
        DELETE FROM Invoice WHERE number = 9701;
        UPDATE Invoice SET[amountVAT] = [amount] * 1.206;
        INSERT INTO Client (clientId, corporateName) VALUE ('411SUN', 'SUN');
        CREATE TABLE Client (clientId TEXT, corporateName TEXT,
             CONSTRAINT clientId PRIMARY KEY);
        DROP TABLE Invoice;



                                      Enterprise JavaBeans                      2.0   283
Relational databases
SQL types
                       SQL type           Java type
                       CHAR               String
                       VARCHAR            String
                       LONGVARCHAR        String
                       NUMERIC            java.lang.Bignum
                       DECIMAL            java.lang.Bignum
                       BIT                boolean
                       TINYINT            byte
                       SMALLINT           short
      Mapping of SQL
                       INTEGER            int
       types in Java
          / JDBC       BIGINT             long
                       REAL               float
                       FLOAT              double
                       DOUBLE             double
                       BINARY             byte[]
                       VARBINARY          byte[]
                       LONGVARBINARY      byte[]
                       DATE               java.sql.Date
                       TIME               java.sql.Time
                       TIMESTAMP          java.sql.Timestamp


                       Enterprise JavaBeans                    2.0   284
Relational databases:
Stored procedures

   RDBMS allow procedures to be stored in the database.
   Can be invoked following a change in the data
      Destruction (before, after), Creation, modification.

      Allow data integrity to be maintained.

      E.g.: if Invoice.amount is changed, so Invoice.amountVAT is recalculated
       by a stored procedure.
   Can be invoked on request.
   Not supported by all RDBMS.
   Written stored procedures:
      proprietary languages

      C, …

      some Java



                              Enterprise JavaBeans                 2.0      285
Relational databases:
Data server

   Some RDBMS can be used in client-server
      SQL data server.


                   SELECT * From Client

    Client                                       SQL Server   Database

                          Result


   Use of a proprietary protocol.
      Oracle: SQL*NET

      Sybase: OpenServer


   JDBC defines a protocol that is vendor-independent
      Each vendor has to provide a compatible server.


   Some JDBC Drivers use proprietary protocols.

                                   Enterprise JavaBeans        2.0       286
JDBC
Introduction


   Relational databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   287
Introduction:
What is JDBC ?

   Java Data Base Connectivity
      Interface based on X/Open SQL CLI (Call Level Interface)


   Like ODBC on Win32
      JDBC is much simpler to use and more robust.


   JDBC is based on SQL2
      Access standard for relational databases.

      Numerous suppliers add proprietary extensions.


   Allows data to be retrieved and modified.
      The JDBC source code is independent of the database (Oracle,
        Sybase...).
   A FAQ on JDBC is available at:
      http://java.sun.com/products/jdbc/jdbc-frequent.html



                               Enterprise JavaBeans               2.0   288
introduction:
A first example

   This code allows:
  1    Connect to an RDBMS,
  2    Create an SQL request
       Execute the SQL request
  3
       Process the request's results
  4
                                                                    Demo
                                                                 SimpleSelect
  1    Connection cxt  = DriverManager.getConnection (
                      "jdbc:odbc:client", "tibo", "secret");
  2    Statement stmt = cxt.createStatement();

  3    ResultSet rs = stmt.executeQuery(
              "SELECT invoiceId, amount FROM Invoice ");

       while (rs.next()) {
              String invoiceId = rs.getString("invoiceId");
  4
              float amount = rs.getFloat("amount");
       }


                                  Enterprise JavaBeans         2.0      289
JDBC
Connection


   Relational databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   290
Connection:
Classes                                                                 1/4


     Connection                  Statement
createStatement()          executeQuery(String)
prepareStatement(String)   executeUpdate(String)
prepareCall(String)        execute(String)
getMetaData()              getMoreResults()
                           getResultSet()
                           getUpdateCount()
                                                         ResultSet
                                                    getInt(int)
                                                    getInt(String)
                           PreparedStatement
   DriverManager                                    getString(int)
                           executeQuery()           getString(String)
 getConnection             executeUpdate()
                           execute()
                           setInt(int, int)
                           setString(int, String)


                            CallableStatement
                           getInt(int)
                           getString(int)
                           Enterprise JavaBeans              2.0        291
Connection:
Opening a database

   The class java.sql.DriverManager allows you to:
      Obtain a list of available Drivers.

      Open a database.

   Connection DriverManager.getConnection(String url, String user,
    String passwd)
   Connection DriverManager.getConnection(String url, Properties info)
      url = jdbc:subprotocol:subname

          subprotocol: name of Driver to be used

          subname: identification of the database. Format depends on Driver.

          Example :
                  jdbc:odbc:client
                  jdbc:dbnet://www.valtech.fr/client
                  jdbc:odbc:wombat;CacheSize=20;ExtensionCase=LOWER
        Identification: user, password, or list of name/value pairs.


                                         Enterprise JavaBeans           2.0   292
Connection:
Types of JDBC Drivers (1)

   Level 1: JDBC-ODBC bridge
      Advantage: simple integration in an architecture using ODBC

      Disadvantage: poorer performance, non-portable, non applet-compliant

   Level 2: Java driver using native implementation for communication with the
    database
      Advantage: better performance

      Disadvantage : non-portable

   Level 3: Java driver communicating with an intermediary server transforming these
    calls into calls to the database.
      Advantage: portable, can be used in applets, RDBMS and http server can be 2 different
        machines for the applets
      Disadvantage: supplementary layer in the server

   Level 4 : 100% pure Java driver
      portable, can be used in applets




                                   Enterprise JavaBeans                       2.0        293
Connection:
Types of JDBC Drivers (2)

   JDBC-Net Driver
   JDBC-ODBC Bridge
   100% Pure Java Driver
   Part Java Driver using a proprietary native API.
   http://java.sun.com/products/jdbc/jdbc.drivers.html : list drivers
                                   JDBC
         Net Bridge    ODBC Bridge   Java Driver        Java+Native Driver
 JDBC                  ODBC Driver                          Native API
Protocol
         Net Server          API Direct or Proprietary Protocol


                                    RDBMS


                              Enterprise JavaBeans                 2.0       294
Connection:
Loading JDBC Drivers
                                                                          Advanced
                                                                           Concept
   Two solutions:
      To load the class explicitly

              Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        To add the property "jdbc.drivers" in System (file jdbc.properties)
              Properties System.getProperties()                          Demo
                                                                        Properties
              String System.getProperty(String)
              This property contains the list of JDBC Drivers.
              Example:
               jdbc.drivers=foo.bar.Driver:wombat.sql.Driver:bad.test.ourDriver;
   When a Driver is loaded, it invokes DriverManager.registerDriver
   For an Applet, the Driver has to come from the server containing the
    database.

                                   Enterprise JavaBeans                 2.0          295
Connection:
The class DatabaseMetaData
                                                                              Advanced
                                                                               Concept
   Obtained using Connection.getMetaData().
   Contains information on:
      The structure of the database: Tables, Columns, capabilities of the JDBC
       Driver and the RDBMS, stored procedures ... etc …
   Not supported by all databases and drivers
                                                                                   Demo
                                                                               DatabaseMeta
Connection cxt = DriverManager.getConnection(url, "tibo", "secret");
DatabaseMetaData dbmd = cxt.getMetaData();
System.out.println("Database : " + dbmd.getDatabaseProductName());
System.out.println("Database : " + dbmd.getDatabaseProductVersion());

ResultSet rs = dbmd.getTables("", "", "", null);   // May not be supported

while (rs.next()) {
          System.out.println("TABLE_NAME = "+ rs.getString("TABLE_NAME"));
          System.out.println("TABLE_TYPE = " + rs.getString("TABLE_TYPE"));
}

                                  Enterprise JavaBeans                       2.0      296
JDBC
SQL commands


   Relational databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   297
SQL commands
The classes                                                             2/4


     Connection                  Statement
createStatement()          executeQuery(String)
prepareStatement(String)   executeUpdate(String)
prepareCall(String)        execute(String)
getMetaData()              getMoreResults()
                           getResultSet()
                           getUpdateCount()
                                                         ResultSet
                                                    getInt(int)
                           PreparedStatement        getInt(String)
  DriverManager                                     getString(int)
                           executeQuery()
                                                    getString(String)
getConnection()            executeUpdate()
                           execute()
                           setInt(int, int)
                           setString(int, String)


                            CallableStatement
                           getInt(int)
                           getString(int)
                           Enterprise JavaBeans              2.0        298
SQL commands:
The different SQL commands

   Statement: simple SQL command
   PreparedStatement: pre-compiled SQL command
      With input parameters.


   CallableStatement: invokes a stored procedure
      With input and/or output parameters.




                            Enterprise JavaBeans    2.0   299
SQL commands:
The class Statement

   Interface.
   Instance created by Connection.createStatement();
   Can be executed by:
      executeQuery(String sql): returns a ResultSet (SELECT)

      executeUpdate(String sql): does not return a ResultSet (UPDATE ...)

      execute(String sql): can return several ResultSet’s (Stored Procedure)


   Must be closed after use by Statement.close()



    Statement stmt = cxt.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT invoiceId, amount FROM Invoice");



                                 Enterprise JavaBeans                    2.0     300
SQL commands:
The class PreparedStatement 1/2

   Sub-Interface of Statement.
   Instance created by Connection.prepareStatement(String sql);
   The SQL is pre-compiled by the RDBMS.
      More rapid in the case of repeated use of a same request.

      If the RDBMS does not support pre-compilation, the behavior will be
       identical to that of Statement.
   Must be closed after use by Statement.close()
   The SQL command can contain parameters that will be substituted by
    the value of Java variables.
       Input parameters.




                                                                             more


                              Enterprise JavaBeans                 2.0        301
SQL commands:
The class PreparedStatement 2/2

   PreparedStatement.setInt(int index, int value)
      index = Number of the parameter (starts at 1)

      value = Value of the parameter

      A function setXXX by Java basic type corresponding to an SQL type.


   Can be executed by:
      executeQuery(), executeUpdate(), execute() (without parameters).



    PreparedStatement stmt = cxt.prepareStatement(
             "SELECT invoiceId, amount FROM Invoice WHERE clientId = ?");

    // Set the value of the parameter ?1
    stmt.setString(1, clientId);

    ResultSet rs = stmt.executeQuery();
                                                                                 Demo
                                                                              PreparedStat

                                     Enterprise JavaBeans                   2.0       302
SQL commands:
The class CallableStatement
                                                                    Advanced
                                                                     Concept
   Sub interface of Statement/PreparedStatement.
   Execution of SQL procedures stored in the RDBMS.
   Instance created by Connection.prepareCall(String sql);
   Accepts input and/or output parameters
 CallableStatement cstmt = cxt.prepareCall(
        "{? = call TesterProcStoc2(?, ?)}");        // With a return value

 cstmt.setString(2, "Hello");                                 //   in
 cstmt.setInt(3, 10);                                         //   in-out
 cstmt.registerOutParameter(3, java.sql.Types.INTEGER);       //   in-out
 cstmt.registerOutParameter(1, java.sql.Types.INTEGER);       //   out

 cstmt.executeQuery();

 int x = cstmt.getInt(3);                                     // getXXX
 int retour = cstmt.getInt(1);                                // getXXX

                             Enterprise JavaBeans                  2.0       303
JDBC
Executing an SQL command


   Relational databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   304
Executing an SQL command
Classes                                                                 3/4


     Connection                 Statement
createStatement()          executeQuery(String)
prepareStatement(String)   executeUpdate(String)
prepareCall(String)        execute(String)
getMetaData()              getMoreResults()
                           getResultSet()
                           getUpdateCount()
                                                         ResultSet
                                                    getInt(int)
                           PreparedStatement        getInt(String)
  DriverManager                                     getString(int)
                           executeQuery()
                                                    getString(String)
getConnection()            executeUpdate()
                           execute()
                           setInt(int, int)
                           setString(int, String)


                            CallableStatement
                           getInt(int)
                           getString(int)
                           Enterprise JavaBeans              2.0        305
Executing an SQL command:
The operation Statement.executeQuery

   SQL command returning a ResultSet
   Used for SELECT SQL Command.
   The result is retrieved in a ResultSet
      The result of an SQL request is a matrix of values.

      Allows values to be retrieved for each resulting row.




    Statement stmt = cxt.createStatement();
    ResultSet rs = stmt.executeQuery(
           "SELECT invoiceId, amount FROM Invoice");

    while (rs.next()) {
           String factureId = rs.getString("invoiceId");
           float montantHT = rs.getFloat("amount");
    }


                               Enterprise JavaBeans            2.0   306
Executing an SQL command:
The operation Statement.executeUpdate

   SQL command returning no ResultSet.
   Returns the number of rows changed.
   Used for the following SQL commands:
      INSERT: adds rows to a table.

      UPDATE: modifies rows in a table.

      DELETE: deletes rows from a table.


   Takes an SQL command as parameter for Statement.
   No parameter for PreparedStatement or for CallableStatement.




                                                                    more


                            Enterprise JavaBeans              2.0    307
Executing an SQL command:
The operation Statement.executeUpdate
  String sql = "INSERT INTO Client (clientId, corporateName, " +
         "address, town, postcode) " + " VALUES (?,?,?,?,?)";

  PreparedStatement stmt = cxt.prepareStatement(sql);

  while(true) {
         String clientId, corporateName, address, town, postcode;

         // ...Read clientId, corporateName, address, town,
         // postcode on the keyboard...

         // Set the value of the parameter ?1
         stmt.setString(1, clientId);
         stmt.setString(2, corporateName);
         stmt.setString(3, address);
         stmt.setString(4, town);
         stmt.setString(5, postcode);

         int result = stmt.executeUpdate();
         System.out.println("result = " + result);      // returns 1
  }


                           Enterprise JavaBeans               2.0      308
Executing an SQL command:
The operation Statement.execute 1/3
                                                                Advanced
                                                                 Concept

   SQL command for which the return type is not known at the time of
    compilation.
      Example: Dynamic reading of an SQL command and execution.

      Returns a ResultSet or an integer.




   Stored procedure with several return values
      Returns one/several ResultSet and/or one/several integers.

      CallableStatement: can Execute a SELECT, an UPDATE and another
       SELECT. The result will be {ResultSet, integer, ResultSet}




                                                                        more

                            Enterprise JavaBeans              2.0        309
Executing an SQL command:
The operation Statement.execute 2/3
                                                              Advanced
                                                               Concept
String sql[] = new String[2];
sql[0] = "SELECT invoiceId, amount FROM Invoice";
sql[1] = "UPDATE Invoice SET amountVAT = amount * 1.206";

Statement stmt = cxt.createStatement();

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

    stmt.execute(sql[i]);
    System.out.print("The SQL request " + sql[i]);

    while(true) {
        // -1 if: no value or if it is a ResultSet
        int count = stmt.getUpdateCount();
        if(count > 0) {
            System.out.println(" has changed " + count + " rows");
            stmt.getMoreResults();
            continue;
    }
                                                                     more

                           Enterprise JavaBeans              2.0      310
Executing an SQL command:
The operation Statement.execute 3/3
                                                            Advanced
                                                             Concept

         if( count == 0 ) {
             System.out.println(" has changed no rows");
             stmt.getMoreResults();
             continue;
         }

         // null if no value or it is an integer
         ResultSet rs = stmt.getResultSet();

         if( rs != null ) {
             System.out.println(" returns a ResultSet");
             stmt.getMoreResults();
             continue;
         }
         break; // no more data to recover
     }
 }
                                                              Demo
                                                             Execute


                           Enterprise JavaBeans            2.0         311
Executing an SQL command:
Transaction

   Transaction: group of executed SQL commands,
   A transaction can be validated: Connection.commit()
   A transaction can be cancelled: Connection.rollback()
   Assures data integrity in multiple SQL commands.
   By default, JDBC uses the auto-commit mode
      It is necessary to deactivate this mode for Transactional access.

      Connection.setAutoCommit(boolean)


   The management of transactions is very variable depending on the
    RDBMS.
      Information on the level support provided by the Driver in
       DatabaseMetaData


                               Enterprise JavaBeans                  2.0   312
Executing an SQL command:
Level of isolation of a transaction

   What happens if an application SELECTs data that is being modified in
    a non-validated transaction ?
      If the RDBMS supports this functionality, it will be possible to read the
       value before it is validated (dirty read).
      cxt.setTransactionIsolation(TRANSACTION_ISOLATION_READ_UNCO
       MMITED)
   5 levels of isolation
      The weakest: non-supported transaction.

      The strongest: locking of data manipulated in the transaction


   The more important the level of isolation is, the slower access to data
    will be.
      Delay in the case of access to locked data.




                               Enterprise JavaBeans                    2.0    313
Executing an SQL command:
Example of Transaction



  cxt.setAutoCommit(false);

  try
  {
         stmt.executeUpdate("UPDATE ...");
         stmt.executeUpdate("UPDATE ...");
         stmt.executeUpdate("UPDATE ...");

         cxt.commit();
  }
  catch(Exception e)
  {
         cxt.rollback();
  }
                                                         Demo
                                                      Transaction




                              Enterprise JavaBeans   2.0       314
JDBC
Processing the results


   Relational databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   315
Processing the results
Classes                                                                 4/4


      Connection                 Statement
createStatement()          executeQuery(String)
prepareStatement(String)   executeUpdate(String)
prepareCall(String)        execute(String)
getMetaData()              getMoreResults()
                           getResultSet()
                           getUpdateCount()
                                                         ResultSet
                                                    getInt(int)
                           PreparedStatement        getInt(String)
   DriverManager                                    getString(int)
                           executeQuery()
                                                    getString(String)
 getConnection()           executeUpdate()
                           execute()
                           setInt(int, int)
                           setString(int, String)


                            CallableStatement
                           getInt(int)
                           getString(int)
                           Enterprise JavaBeans             2.0         316
Processing the results:
The class ResultSet

   Contains the result of an SQL command (SELECT)
      Contains a matrix of values.


   Possesses a current position on a row: the cursor.
      The cursor is moved by ResultSet.next().

      Returns true if there are still rows to be read, if not false.

      Can be named in some RDBMS allowing UPDATE/DELETE on the
       current line of the ResultSet.
   To retrieve the value of a column of the current row:
      Operations realizing the conversion of SQL/Java types.

      XXX getXXX(int pos) : pos = number of the column (starts at 1)

      XXX getXXX(String name) : name = name of the column


   wasNull(int) tests if the value of the column is null (SQL null)

                               Enterprise JavaBeans                2.0   317
Processing the results:
The class ResultSet MetaData

   You can access the structure of the columns of a ResultSet
   ResultSetMetaData ResultSet.getMetaData()
      Recovers the structure of a ResultSet.


   getColumnCount() returns the number of columns.
      String getColumnName(int): returns the name of the column.

      int getColumnType(int): returns the SQL type of a column.

      String getTableName(int): returns the name of the Table the column is in.




                               Enterprise JavaBeans                 2.0      318
Processing the results:
Example of use of a ResultSet


 Statement stmt = cxt.createStatement();
 ResultSet rs = stmt.executeQuery("SELECT * FROM Invoice");

 ResultSetMetaData rsmd = rs.getMetaData();
 int colCount = rsmd.getColumnCount();

 for(c = 1; c <= colCount; c++)
         System.out.print( rsmd.getColumnLabel() + " ");
 System.out.println();

 for(c = 1; c <= colCount; c++)
         System.out.print( rsmd.getColumnTypeName() + " ");
 System.out.println();

 while( rs.next() ) {
         for(c = 1; c <= colCount; c++)
                System.out.print(rs.getString(c) + " ");
        System.out.println();
 }


                           Enterprise JavaBeans               2.0   319
Processing the results:
The Binary Large Objects (BLOB) 1/2
                                                                   Advanced
                                                                    Concept
   Manipulation of large scale values (blob)
      Type SQL LONGVARBINARY or LONGVARCHAR

   Values manipulated like a Stream.
      getBinaryStream(), getAsciiStream(), getUnicodeStream().


 java.sql.Statement stmt = con.createStatement();
 ResultSet r = stmt.executeQuery("SELECT col FROM Test");
 // Read the BLOBs by packet of 4K
 byte buff = new byte[4096];
 while (r.next()) {
        Java.io.InputStream fin = r.getAsciiStream(1);
        for (;;) {
               int size = fin.read(buff);
               if (size == -1) break;     // end of stream
               output.write(buff, 0, size);
        }
 }                                                                       more

                              Enterprise JavaBeans                2.0     320
Processing the results:
The Binary Large Objects (BLOB) 2/2
                                                                     Advanced
                                                                      Concept
   Writing a BLOB
      To open the data source: an InputStream

      To associate the InputStream with the column in the instruction
       UPDATE.
      setBinaryStream(), setAsciiStream(), setUnicodeStream()



 File file = new File("/tmp/411PIT.gif");

 int lgr = file.length();

 InputStream = new FileInputStream(file);

 PreparedStatement pstmt = cxt.prepareStatement(
        "UPDATE Client SET image = ? WHERE clientId = '411PIT'");

 pstmt.setBinaryStream(1, fin, lgr);
 pstmt.executeUpdate();


                               Enterprise JavaBeans                 2.0     321
JDBC
Processing the exceptions


   Relational databases

   Introduction

   Connection

   SQL commands

   Executing an SQL command

   Processing the results

   Processing the exceptions


                             Enterprise JavaBeans   2.0   322
Processing the exceptions
The class SQLException

   The class SQLException describes access errors to a database.
   Contains:
      a string describing the problem, accessible across getMessage()

      a string of type "SQLstate" that respects the XOPEN convention.

      An integer corresponding to the error code, specific to the constructor of
       the database.
      A link to a supplementary exception, containing other information.




                                Enterprise JavaBeans                  2.0      323
Processing the exceptions
The class SQLWarning

   The class SQLWarning provides information of type "warning" when
    the database in accessed
       Contains:

          strings describing the problems, accessible across methods.


   The class DataTruncation (inherits from SQLWarning) provides
    warnings when the database has to "truncate" data.




                            Enterprise JavaBeans              2.0        324
            Advanced concepts
            Contents
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   325
 Developing Entity EJB using Bean-managed persistence
 Bean-managed Entity EJB

Represents persistent data or an entity of the information system or the
application - long-lived object.

Only Difference is that Persistence is managed completely by the Bean.

Same Home and Remote Interface as the Container Managed Bean

   Different implementation inside the Bean Class




                                   Enterprise JavaBeans         2.0        326
            Develop a container-managed Entity EJB
            Class diagram

                                <<Interface>>                                        <<Interface>>
                                   Remote                                             Serializable
                                (from rmi)
                                                                                  (from io)




             <<Interface>>                                  <<Interface>>                                 <<Interface>>     <<Interface>>
               EJBHome                                        EJBObject                                   EntityBean       EntityContext
             (from ejb)                                     (from ejb)                                   (from ejb)       (from ejb)




                            1                                             2                                           3
             <<Interface>>                                  <<Interface>>            AccountPK             AccountBean
             AccountHome                                        Account                                   (from sample)
            (from sample)                                   (from sample)




       AccountHomeObject                                AccountRemoteObject
      (from container)                                 (from container)
                                             creates                                                 Delegates


SpContent                                                                   Enterprise JavaBeans                          2.0               327
            Develop a Stateful Session EJB
            The Home Interface

               Must follow a naming convention

                public interface <BeanName>Home
                    extends javax.ejb.EJBHome
                {
                    public <BeanName> create (<rmiParams>)
                        throws [<businessException>,]...
                               javax.ejb.CreateException,
                               javax.rmi.RemoteException ;
                    //...
                }


               Must define, at least, one creation method
               The throws clause may include some Business Exception

SpContent                                 Enterprise JavaBeans          2.0   328
            Develop a container-managed Entity EJB
            The Remote Interface

               Must follow a naming convention
                public interface <BeanName>
                    extends javax.ejb.EJBObject
                {
                    public <rmiRV> <businessMethod> (<rmiParams>)
                        throws [<businessException>,]...
                                javax.rmi.RemoteException ;
                }
               Must extend the javax.ejb.EJBObject interface
               Must define the signature of all business methods
               All business methods must have the specified throws clause
                  May include business exceptions
                    Must include RemoteException
               Their signature must only use RMI-compliant parameter

SpContent                                Enterprise JavaBeans                2.0   329
            Developing Entity EJB using Bean-managed persistence
            The EJB class

               Must define creation methods for each create method of the Home
                interface
                public class <BeanName>Bean
                    implements javax.ejb.EntityBean
                {
                    public <PrimaryKey> ejbCreate (<rmiParams>)
                        throws [javax.ejb.CreateException,]
                               [javax.rmi.RemoteException]
                    { /* implementation */ }

                         // ...
                }


                       The return type must be the EJB primary key (Not Void)
            NEW

SpContent                                      Enterprise JavaBeans              2.0   330
            Developing Entity EJB using Bean-managed persistence
            The EJB class
      NEW
            Must define finder methods for the findByPrimaryKey method and each
             additional findXXX method of the Home interface
             public <PrimaryKey> ejbfindByPrimaryKey(<PrimaryKey>)
                     throws [javax.ejb.FinderException,]
                            [javax.rmi.RemoteException]
                 { /* implementation */ }

                  public Enumeration ejbfindXXX (<rmiParams>)
                      throws [javax.ejb.FinderException,]
                             [javax.rmi.RemoteException]
                  { /* implementation */ }


            finder methods must return a PrimaryKey or an Enumeration of PrimaryKey
             objects


SpContent                               Enterprise JavaBeans               2.0         331
         Developing Entity EJB using Bean-managed persistence
         The AccountBean class

          package beanManaged.server;

          public class AccountBean implements EntityBean {
            private EntityContext ctx;

            private Connection con = null;

            private             String        accountId;
            private             double        balance;


             static {
                        new weblogic.jdbc.jts.Driver () ;
             }

           private Connection getConnection() throws SQLException {
               return DriverManager.getConnection("jdbc:weblogic:jts:ejbPool");
           }


           //…


SpCode                                    Enterprise JavaBeans                    2.0   332
            Developing Entity EJB using Bean-managed persistence
            Create an Entity EJB
                    << Home Object>>                    << Remote Object>>       << Bean Instance>>
                : AccountHomeImpl                     : AccountImpl               : AccountBean               Transactional                   Persistent
   : Client
                                                                                                                   Service                    Store

                                                      UserTransaction.begin()
            create(args)
                                                          ejbCreate(args)
                                                                                                         Create an entity in the database
                                                                                                                            Register a resource
                                          Returns the primary key : pk
                                                                                                  The identity of the EJB
                                                new                                               Is complete
                                                           ejbPostCreate(args)
                               Association of
                               The EJB object
                               With its primary key




SpContent                                                             Enterprise JavaBeans                                           2.0            333
         Developing Entity EJB using Bean-managed persistence
         The AccountBean class ( Create )
          //…
           public AccountPK ejbCreate(String accountId, double initialBalance)
              throws CreateException
            {
              this.accountId = accountId;                      Obtain a transactional
              this.balance   = initialBalance;                      connection

              PreparedStatement ps = null;
              con = getConnection () ;
              ps = con.prepareStatement("insert into ejbAccounts (id, bal) values
                                       (?, ?)");
              ps.setString(1, accountId);
              ps.setDouble(2, balance);
              if (ps.executeUpdate() != 1) { // Create in Persistent Storage
                  throw new CreateException ("JDBC did not create any row");
              }

              AccountPK primaryKey = new AccountPK();
              primaryKey.accountId = accountId;
              return primaryKey;
          }

          public void ejbPostCreate(String accountId, double initialBalance) {}
          //… The Same As Container Managed


SpCode                                   Enterprise JavaBeans                     2.0   334
            Developing Entity EJB using Bean-managed persistence
            Find an entity EJB                                                 Any Available
                                                                                  Instance
                                                                               from the Pool
                   << Home Object>>       << Remote Object>>       << Bean Instance>>

                    : AccountHomeImpl                                : Account                  Persistence
 : Client                                      : AccountImpl
                                                                   (From the pool)              Storage

       find<METHOD>(args)
                                         ejbFind<METHOD>(args)
                                                                               Lookup the entity
                                                                               in the database

                                         Returns the primary key


                                        new
            Association of
            The EJB object
            with its primary
            key

SpContent                                      Enterprise JavaBeans                       2.0         335
         Developing Entity EJB using Bean-managed persistence
         The AccountBean class (Find)
          //…
          public AccountPK ejbFindByPrimaryKey(AccountPK pk) throws
                     FinderException,
                     RemoteException
                                                                       Obtain a transactional
           {                                                                  connection
              PreparedStatement ps = null;
              try {
                if ((pk == null) || (pk.accountId == null))
                    throw new FinderException ("primary key cannot be null");
                con = getConnection () ;
               ps = con.prepareStatement("select bal from ejbAccounts where id =   ?");
               ps.setString(1, pk.accountId);
               ps.executeQuery();
               ResultSet rs = ps.getResultSet();
               if (!rs.next())
                   throw new FinderException (pk.accountId + "not found");
             }catch (SQLException sqe) {
               throw new RemoteException (sqe.getMessage());
             }
             finally {
                 ps.close();
             }

            return pk ;
          }
          //…




SpCode                                      Enterprise JavaBeans                          2.0   336
         Developing Entity EJB using Bean-managed persistence
         The AccountBean class (Find groups)
          //…
           public Enumeration ejbFindBigAccounts(double balanceGreaterThan)
              throws FinderException, RemoteException
            {
              PreparedStatement ps = null;
                                                               Obtain a transactional
              ResultSet rs = null;                                  connection
              con = getConnection () ;
              ps = con.prepareStatement("select id, bal from ejbAccounts where
                                           bal > ?");
              ps.setDouble(1, balanceGreaterThan);
              ps.executeQuery();
              rs = ps.getResultSet();
              Vector v = new Vector();
              AccountPK pk;
              while (rs.next()) {
                  pk = new AccountPK();
                  pk.accountId = rs.getString(1);
                  v.addElement(pk);
              }
              rs.close();
              con.close () ;
              return v.elements();
              }
          }
          //…

SpCode                                   Enterprise JavaBeans                    2.0    337
Developing Entity EJB using Bean-managed persistence
State Synchronization

ejbLoad()

    Called when the contanier needs to synchronize the state in the
    Persistent store with the Bean Instance state.


ejbStore()

    Called when the contanier needs to synchronize the state in the
    Bean Instance state with the Persistent store.




                                  Enterprise JavaBeans        2.0     338
         Developing Entity EJB using Bean-managed persistence
         The AccountBean class ( Store )

         //…
          public void ejbStore() throws RemoteException
                                                               Obtain a transactional
           {
             PreparedStatement ps = null;
                                                                     connection
             try {    // Synchronize the state, to update with new values
               con = getConnection () ;     // recconnect for new TX
               ps = con.prepareStatement("update ejbAccounts set bal = ? where id
                                        = ?");
               ps.setDouble(1, balance);
               ps.setString(2, accountId);
               int i = ps.executeUpdate();

                if (i == 0) {
                  throw new RemoteException (accountId + " not updated");
                }
               }catch (SQLException sqe) {
                   throw new RemoteException (sqe.getMessage());
               }finally {
                  ps.close();
               }
           }
         //…

SpCode                                   Enterprise JavaBeans                   2.0     339
         Developing Entity EJB using Bean-managed persistence
         The AccountBean class ( Load )
           public void ejbLoad() throws RemoteException {
              AccountPK pk = (AccountPK) ctx.getPrimaryKey();        Obtain the primary key
              PreparedStatement ps = null;                             using the context
              try {
                con = getConnection () ;
                ps = con.prepareStatement("select bal from ejbAccounts where id = ?");
                ps.setString(1, pk.accountId);
                ps.executeQuery();
                ResultSet rs = ps.getResultSet();
                if (rs.next()) {
                  accountId = pk.accountId;
                  balance = rs.getDouble(1);
                }
                else {
                  throw new RemoteException (pk.accountId + "not found");
                }
              }catch (SQLException sqe) {
                throw new RemoteException (sqe.getMessage());
              }
              finally {
                  ps.close();
              }
          }
          //…


SpCode                                   Enterprise JavaBeans                     2.0         340
            Developing Entity EJB using Bean-managed persistence
            Deleting an Entity
                                    does not exist




                                       pooled


     If you only want to finish
     your client Session, just
                                              ejbRemove()
     release the reference
     on the EJB.                                     Not only put the instance
                                                     back in the pool,
                                                     but also delete the persistent
                                        ready        record of the Entity EJB
                                                     for all users

SpContent                            Enterprise JavaBeans               2.0      341
            Developing Entity EJB using Bean-managed persistence
            Deleting an Entity EJB

                  << Remote Object>>       << Bean Instance>>

                 : AccountBeanImpl               : AccountBean                            Persistent store
: Client


              remove()
                                   ejbRemove()
                                                         Delete any data related to this instance




                                                           Delete the persistent record
                                                           of the Entity before
                                                           putting it back in the pool




SpContent                                   Enterprise JavaBeans                           2.0        342
         Developing Entity EJB using Bean-managed persistence
         Remove persistent data manually
                                                                 Obtain a transactional
         //…
          public void ejbRemove() throws RemoteException {             connection
             PreparedStatement ps = null;
             try {
               AccountPK pk = (AccountPK) ctx.getPrimaryKey();
               con = getConnection () ;
               ps= con.prepareStatement("delete from ejbAccounts where id = ?");
               ps.setString(1, pk.accountId);
               int i = ps.executeUpdate(); // Remove data from store
               if (i == 0) {
                 throw new RemoteException (pk.accountId + "not found");
               }
             }
             catch (SQLException sqe) {
               throw new RemoteException (sqe.getMessage());
             }
             finally {
               try {
                 ps.close();
               }
               catch (Exception ignore) {}
             }
         //…



SpCode                                  Enterprise JavaBeans                   2.0        343
         Developing Entity EJB using Bean-managed persistence
         Which methods are involved with transactions?

                                                    transactional
                         Methods
                                                       context
                          ejbCreate                           Yes

                         ejbActivate                     Yes /No

                        ejbPassivate                     Yes / No

                        ejbPostCreate                         Yes
                         ejbRemove                            Yes
                          ejbLoad                             Yes
                          ejbStore                            Yes
                     ejbFind<METHOD>                          Yes
                      Business method                    Yes / No



SpCode                                 Enterprise JavaBeans         2.0   344
           Developing Entity EJB using Bean-managed persistence
           Bean-managed / Container-managed
               Bean-managed                                  Container-managed
   A lot of hand-written code for                     Not a single line of hand-written
   persistence management.                            code for persistence management.
   Persistence management cannot                      Flexible persistent storage
   be changed at deployment time                      Less control over SQL queries
   More control over SQL queries if                   (generated by the container).
   a relational DBMS is used for                      Performance issues
   persistence




              The choice will mostly depend on the performance of the container vendor tools
                                   concerning SQL code generation and
                          the ways to describe finder methods using these tools


SpVersus                                   Enterprise JavaBeans                    2.0         345
            Advanced concepts
            Contents
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   346
    Deploying Entity EJB using Bean-managed persistence
    Deployment Descriptor Information

    EJB meta-information
       EnterpriseBeanClassName

       RemoteInterfaceClassName

       HomeInterfaceClassName

       BeanHomeName : JNDI name for the Home object




    Entity information
       PrimaryKeyClassName

       ContainerManagedFields : Must be empty for Bean-Managed


                                                          New




                                      Enterprise JavaBeans        2.0   347
            Advanced concepts
            Contents
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   348
            Advanced concepts
            Session Bean using SessionSynchronization
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   349
            Developing Session Bean using SessionSynchronization
            Class diagram

                                <<Interface>>
                                   Remote
                                (from rmi)




                                                                                   New
             <<Interface>>                                  <<Interface>>        <<Interface>>           <<Interface>>     <<Interface>>
               EJBHome                                        EJBObject         SessionSynchronizaion    SessionBean      SessionContext
             (from ejb)                                     (from ejb)             (from ejb)           (from ejb)       (from ejb)




                            1                                             2                                          3
             <<Interface>>                                  <<Interface>>                                 TraderBean
             TraderHome                                         Trader                                   (from sample)
            (from sample)                                   (from sample)




       TraderHomeImpl                                   TraderRemoteImpl
      (from container)                                 (from container)
                                             creates                                                Delegates


SpContent                                                                   Enterprise JavaBeans                         2.0               350
                                                     Developing Session Bean using SessionSynchronization
                                                     Class description

                         <<Interface>>
                           Remote
                         (from rmi)
                                                                                                                                           The SessionSynchronization interface
                                                                                                                                              Allows a stateful EJB to synchronize its state buffer with
                                                                                                                                               a database during transactions.
     <<Interface>>                             <<Interface>>            <<Interface>>             <<Interface>>        <<Interface>>
      EJBHome                                   EJBObject           SessionSynchronization        SessionBean           EJBContext
     (from ejb)                                (from ejb)          (from ejb)                    (from ejb)            (from ejb)




                                                                                                                        <<Interface>>




                                                                                                                                              Its implementation by the EJB class is not mandatory
      <<Interface>>                            <<Interface>>                             TraderBean               -ctx SessionContext
      TraderHome                                  Trader                                (from server)
                                                                                                                     (from ejb)
     (from interfaces)                         (from interfaces)




 TraderBeanHomeImpl                         TraderBeanEOImpl
(from server)                    creates   (from server)                             delegates




         SpContent                                                                                                                                     Enterprise JavaBeans                  2.0       351
            Developing Session Bean using SessionSynchronization
            The SessionSynchronization interface

               During transactions, it is possible to manage a cache in memory for
                performance issues

               The cache will be used within business methods instead of direct calls
                to the database

               The cache will be read from the database at the beginning of each
                transaction and written to the database when the transaction is
                committed




SpContent                                Enterprise JavaBeans              2.0        352
            Developing Session Bean using SessionSynchronization
            The SessionSynchronization interface

               afterBegin() : called just after the beginning of a transaction. update
                your cache from the database


               beforeCompletion() : called just before a transaction is being
                committed write the values from the cache into the database


               afterCompletion(boolean) : called after the end of a transaction
                indicates if the transaction has been committed or rolled back.




SpContent                                 Enterprise JavaBeans                 2.0        353
            Developing Session Bean using SessionSynchronization
            The Home Interface

               Must follow a naming convention

                public interface <BeanName>Home
                    extends javax.ejb.EJBHome
                {
                    public <BeanName> create (<rmiParams>)
                        throws [<businessException>,]...
                               javax.ejb.CreateException,
                               javax.rmi.RemoteException ;
                    //...
                }


               Must define, at least, one creation method
               The throws clause may include some Business Exception

SpContent                                 Enterprise JavaBeans          2.0   354
            Developing Session Bean using SessionSynchronization
            The Remote Interface

               Must follow a naming convention
                public interface <BeanName>
                    extends javax.ejb.EJBObject
                {
                    public <rmiRV> <businessMethod> (<rmiParams>)
                        throws [<businessException>,]...
                                javax.rmi.RemoteException ;
                }
               Must extend the javax.ejb.EJBObject interface
               Must define the signature of all business methods
               All business methods must have the specified throws clause
                  May include business exceptions
                    Must include RemoteException
               Their signature must only use RMI-compliant parameter

SpContent                                Enterprise JavaBeans                2.0   355
            Developing Session Bean using SessionSynchronization
            The Bean Class                                       1/2

               Must implement the SessionSynchronization interface :

                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                    implements javax.ejb.SessionSynchronization
                {
                    public void afterBegin()
                    { /* implementation */ }

                    public void beforeCompletion()
                    { /* implementation */ }

                    public void afterCompletion(boolean committed)
                    { /* implementation */ }
                    // ...
                }


SpContent                                Enterprise JavaBeans           2.0   356
            Developing Session Bean using SessionSynchronization
            The Bean Class                                        2/2

               Must maintain a database buffer in memory during transactions :
                public class <BeanName>Bean
                    implements javax.ejb.SessionBean
                    implements javax.ejb.SessionSynchronization
                {
                    // the data cached during transactions
                    // the implementation is not mandatory
                    private Hashtable currentTranaction;
                    private Hashtable imageBeforeTransaction;

                    // a temporary copy of the conversational state
                    // used during transactions
                    private <type> tmpAttribut1;

                    // use these variables within afterBegin(), ...
                }



SpContent                                Enterprise JavaBeans              2.0    357
         Developing Session Bean using SessionSynchronization
         Database structure used by the Trader EJB
                 Client

                      clientID       LastName            FirstName

                     1234-2345           Sfez            Jean-Marc

                     1256-2347          Senhaji           Oussama

                 Portfolio
                      clientID      StockSymbol           Shares

                     1234-2345           INTL              2000

                     1256-2347          SUNW               10000


SpCode                            Enterprise JavaBeans               2.0   358
         Developing Session Bean using SessionSynchronization
         The TraderBean class (buffer definition)

          public class TraderBean implements SessionBean, SessionSynchronization {

            private SessionContext ctx     ;

            private Connection con         ;

            private double                tmpTradingBalance ;
            private Hashtable    currentTransaction         ;
            private Hashtable    imageBeforeTransaction     ;


            public   double          tradingBalance;
            public   String          traderName;
            public   String          clientId ;

             static {
                        new weblogic.jdbc.jts.Driver () ;
             }

            private Connection getConnection() throws SQLException {
               return DriverManager.getConnection("jdbc:weblogic:jts:ejbPool");
            }
          //…


SpCode                                    Enterprise JavaBeans                    2.0   359
            Developing Session Bean using SessionSynchronization
            Start a transaction

                                             does not exist




                                             method-ready                              passive

                              Tx-method


                              afterBegin()
                                                              non-tx method
                                                              or different tx method
                                             method-ready
                  tx method                     in TX         ERROR
SpContent                                    Enterprise JavaBeans                      2.0       360
           Developing Session Bean using SessionSynchronization
           Start a transaction
                  << Remote Object>>      << Bean Instance>>

               : TraderImpl                    : TraderBean                             transactional                      Persistent Store
: Client                                                                                   service

                                       UserTransaction.begin()

         Business method

                                                  If the instance is not active, the container must activate it


                                          Register the synchronization object
                                afterBegin()
                                                                                   Update the state using the database
                                                                                                    Register a resources

                              Business method

         Business method
                              Business method




SpCode                                                         Enterprise JavaBeans                                              2.0          361
         Developing Session Bean using SessionSynchronization
         The TraderBean class (afterBegin)
          //…
          public void afterBegin() {
             //The Session EJB is associated with a transactional context,
             //it may manipulate data in the database

               tmpTradingBalance = tradingBalance ;

               PreparedStatement ps = null    ;
               ResultSet rs = null            ;                    Obtain a transactional
               imageBeforeTransaction = new   Hashtable () ;
                                                                        connection
               currentTransaction     = new   Hashtable () ;
               con = getConnection () ;
               ps = con.prepareStatement("select * from Portfolio where ID = ?");
               ps.setString(1, id);
               ps.executeQuery();
               rs = ps.getResultSet();
               while (rs.next()) {

                    String stockSymbol = rs.getString (2)     ;
                    int shares          = rs.getInt (3) ;
                    imageBeforeTransaction.put (stockSymbol, new Integer (shares));

                }
          }
         //…
SpCode                                      Enterprise JavaBeans                      2.0   362
            Developing Session Bean using SessionSynchronization
            finish a transaction

                                          does not exist




                                          method-ready                            passive


                  commit                                        rollback

             1. beforeCompletion()
             2. afterCompletion(true/false)                 2. afterCompletion(false)
                                          method-ready
                                             in TX

SpContent                                     Enterprise JavaBeans                2.0       363
         Developing Session Bean using SessionSynchronization
         Commit a transaction
                       << Bean Instance>>

                                                                                   transactional
          : Client         : TraderBean                                                                        Persistent Store
                                                                                       service



                                            beforeCompletion()

                                                                            Update the database



                                                                                                   prepare()

                                                                                                   commit()

                                          afterCompletion(status)




                                                Update the conversational
                                                state depending on
                                                The database status



SpCode                                           Enterprise JavaBeans                                               2.0           364
         Developing Session Bean using SessionSynchronization
         Rollback a transaction
                        << Bean Instance>>

                          : TraderBean                                        transactional
           : Client
                                                                                  service

                              UserTransaction.rollback()

                                          afterCompletion(false)




                                                           Update the
                                                           Initial conversational
                                                           state




SpCode                                   Enterprise JavaBeans                             2.0   365
         Developing Session Bean using SessionSynchronization
         The TraderBean class (beforeCompletion)

          //…                                                        Update the database
          public void beforeCompletion() {
                                                                       using the buffer
           PreparedStatement ps = null ;
           try {
           for (Enumeration e = currentTransaction.keys() ; e.hasMoreElements() ;)
           {
               String stockSymbol = (String)e.nextElement() ;
               if (imageBeforeTransaction.get(stockSymbol) == null){
               // New Stock Symbol, insert it in the portfolio
               ps = con.prepareStatement("insert into Portfolio(ID, stockSymbol,
                                         shares) values (?, ?, ?)");
               ps.setString(1, id);
               ps.setString(2, stockSymbol) ;
               Integer s = (Integer)currentTransaction.get(stockSymbol) ;
               ps.setInt (3, s.intValue()) ;
               ps.executeUpdate() ;
               }else {
                 //…




SpCode                                   Enterprise JavaBeans                    2.0       366
         Developing Session Bean using SessionSynchronization
         The TraderBean class (before/afterCompletion)

              //Stock Symbol exists; update it in the Portfolio
              ps = con.prepareStatement("update Stocks SET Shares = ? WHERE ID = ?
                                        and StockSymbol = ?");
              Integer sCurrent = (Integer)currentTransaction.get(stockSymbol) ;
              Integer sBefore = (Integer)imageBeforeTransaction.get(stockSymbol) ;
              int sFinal = sCurrent.intValue() + sBefore.intValue () ;
              ps.setInt(1, sFinal ) ;
              ps.setString (2, id) ;
              ps.setString (3, stockSymbol ) ;
              ps.executeUpdate() ;                                  Possibility to oblige
                                                                       the current transaction
            }catch (Exception e) {                                     to be rollbacked
                 ctx.setRollbackOnly ();
            }
          }//end beforeCompletion

          public void afterCompletion(boolean status) {

              if (status == true ) tradingBalance = tmpTradingBalance ;
              else {
                imageBeforeTransaction = null ;
                currentTransaction     = null ;
              }
          }

SpCode                                      Enterprise JavaBeans                       2.0       367
         Developing Session Bean using SessionSynchronization
         Which methods are involved with transaction?
                                                     Transactional
                          Methods
                                                        context
                          afterBegin                           Yes

                       beforeCompletion                        Yes

                         newInstance                           No

                      setSessionContext                        No
                          ejbCreate                            No
                         ejbRemove                             No
                         ejbPassivate                          No
                          ejbActivate                          No

                       afterCompletion                         No

                       Business method                     Yes / No


SpCode                                  Enterprise JavaBeans          2.0   368
            Advanced concepts
            Deploying EJB using SessionSynchronization
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   369
            Advanced concepts
            Using EJB using SessionSynchronization
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   370
            Advanced concepts
            Advanced deployment : Security attributes
               Advanced EJB client : Handles
               Prerequisite : Distributed Transactions
               Advanced EJB client : Transaction management
               Advanced Deployment : Transaction attributes
               Prerequisite : Database access with JDBC
               Developing Entity EJB using Bean-managed persistence
               Deploying Entity EJB using Bean-managed persistence
               Using an Entity EJB using Bean-managed persistence
               Developing Session Bean using SessionSynchronization
               Deploying a Session Bean using SessionSynchronization
               Using a Session Bean using SessionSynchronization
               Advanced deployment : Security attributes




SpContent                                       Enterprise JavaBeans    2.0   371
Advanced deployment : Security attributes
EJB Security Model

   As for transaction management, the entire EJB or each method can be associated
    with a security management policy
   A security management policy is only defined by a list of Identities (users or roles)
    having access to the bean or to the specified method
      AllowedIdentities : a list of users or roles allowed to access the method or the bean

      deployment specialists assign security roles




                                      Enterprise JavaBeans                         2.0         372
Advanced deployment : Security attributes
EJB Security Model
                DeploymentDescriptor
        (from deployment)


           DeploymentDescriptor()
           getEnterpriseBeanClassName()
           setEnterpriseBeanClassName()
           getHomeInterfaceClassName()
           setHomeInterfaceClassName()
           getRemoteInterfaceClassName()
           setRemoteInterfaceClassName()
           getBeanHomeName()
           setBeanHomeName()
           getEnvironmentProperties()
                                                             AccessControlEntry
           setEnvironmentProperties()
                                                           (from deployment)
           getAccessControlEntries()
           setAccessControlEntries()
           getAccessControlEntries()                          AccessControlEntry()
                                                    0..*      AccessControlEntry()
           setAccessControlEntries()
           getControlDescriptors()                            AccessControlEntry()
           setControlDescriptors()                            getMethod()
           getControlDescriptors()                            setMethod()
           setControlDescriptors()                            getAllowedIdentities()
           isReentrant()                                      setAllowedIdentities()
           getReentrant()                                     getAllowedIdentities()
           setReentrant()                                     setAllowedIdentities()



                                       Enterprise JavaBeans                            2.0   373
Advanced deployment : Security attributes
EJB and Security

An EJB component or a method is associated with a list of allowed identities

   “AllowedIdentities” property specify this list of allowed identities




                                                              Direct
                                       Id = “client”
                                                              Debit
                         Client
                                           AllowedIdentities ={ “client” , “guest” , “admin”}




                                     Enterprise JavaBeans                             2.0       374
Advanced deployment : Security attributes
EJB and Security

An EJB component or a method can be associated with a specific security identity
  when it is running.
 RunAsMode specify if the method should run with
     the identity of the client (CLIENT_IDENTITY)

     a privileged system identity (SYSTEM_IDENTITY)

     an identity specified with RunAsIdentity (SPECIFIED_IDENTITY)

 RunAsIdentity specify an identity if SPECIFIED_IDENTITY is the value for
  RunAsMode




                                    Direct                             Account
                Id = “client”                  Id = “accountManager”
                                    Debit                               Bean
   Client
                                RUN_AS_MODE = SPECIFIED_IDENTITY
                                RUN_AS_IDENTITY = “AccountManager”

                                  Enterprise JavaBeans                    2.0      375
Advanced deployment : Security attributes
EJB security restrictions

   A stateful session EJB has its identity determined at instantiation.
       An EJB will run with the identity associated with the ejbCreate(…) method.

       All invoked method should not specify a conflicting identity

   A Stateless session EJB must process a complete transaction with the same
    identity
       all methods invoked on a bean instance within the same transaction must run with the
        same identity
   The container will throw a RemoteException if runtime identities are conflicting with
    these restrictions




                                      Enterprise JavaBeans                       2.0           376
            Advanced concepts
            Summary

               It is possible to demarcate transactions in a client
                application.


               Its possible to choose transactions and security
                management at deployment time.


               Entity Bean’s can have bean managed persistence
                (Written by the bean developer) .


               Session Beans can manage a buffer in memory using the
                SessionSynchronization interface.


SpContent                             Enterprise JavaBeans             2.0   377
Thank you for your participation!



             www.valtech.com




            Enterprise JavaBeans   2.0   378

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:40
posted:2/10/2012
language:English
pages:378