CMP 436 - PowerPoint PPT Presentation

1 / 113
About This Presentation
Title:

CMP 436

Description:

Sun Site Article about EJB 3.0. http://java.sun.com ... Sun's definition: ... pre-release EJB 3.0 specifications are in part available from JBoss and Oracle. ... – PowerPoint PPT presentation

Number of Views:119
Avg rating:3.0/5.0
Slides: 114
Provided by: GJu
Category:
Tags: cmp

less

Transcript and Presenter's Notes

Title: CMP 436


1
CMP 436
  • Introduction to
  • Enterprise JavaBeans (EJBs)
  • --Reading Materials
  • Fall 06
  • Department of Mathematics
  • and Computer Science
  • Lehman College, CUNY

2
Introduction to EJB
3
Key References
  • Bill Burke Richard Monson-Haefel, Enterprise
    JavaBeans 3.0, 5th Edition O'Reilly Associates,
    2006. ISBN 0-596-00978-x
  • Sun Site Article about EJB 3.0
  • http//java.sun.com/developer/technicalArticl
    es/ebeans/ejbease/
  • JBOSS site
  • http//labs.jboss.org/portal/jbossejb3
  • Ant Build tool
  • http//ant.apache.org/

4
Enterprise Computing Environments
  • The term enterprise stands for the entire
    business activity of an organization.
  • perhaps distributed over a number of sites and
    structured as a number of units, with varying
    amounts of dependence between the units.
  • Large organizations in general have specific
    goals for their enterprise information systems,
    including
  • Time-to-market
  • Portability
  • Diverse Environments
  • Interoperability, Assembly, and Integration
  • Lower cost
  • Three key evolutions of the enterprise IS
    architecture
  • Single-tier traditional mainframe architecture.
  • Two tier client-server model.
  • Three-tier or N-tier distribute software
    components over a set of machines all of which
    comprise a part of the application.

5
Three-Tier Architecture (Socket, RPC-based)
  • Thinner client business data model separated
    from presentation
  • Business logic and data access logic reside in
    middle tier server while client handles
    presentation.
  • Middle tier server is now required to handle
    system services
  • Concurrency control, threading, transaction,
    security, persistence, multiplexing, performance,
    etc.
  • Pros
  • Business logic can change more flexibly than
    2-tier model.
  • Most business logic components reside in the
    middle-tier server.
  • Cons
  • Complexity is introduced in the middle-tier
    server.
  • Client and middle-tier server is more tightly
    coupled (than the three-tier object based model).
  • Difficult to reuse code (compared to object model
    based)

6
Three-Tier Architecture (Remote Object based)
  • Business logic and data model are objects
  • Business logic and data model are now described
    in abstraction (interface language).
  • Object models used CORBA, RMI, DCOM
  • Interface language in CORBA is IDL
  • Interface language in RMI is Java interface
  • See WebService part1 lecture note about CORBA,
    RMI, DCOM
  • Pros
  • More loosely coupled than RPC model
  • Code could be more reusable
  • Cons
  • Complexity in the middle-tier still need to be
    addressed.

7
Three-Tier Architecture (Web Server based)
  • Browser handles presentation logic
  • Browser talks to Web server via HTTP protocol
  • Business logic and data model are handled by web
    components (CGI, Servlet/JSP, ASP).
  • Web components generate dynamic contents.
  • Pro
  • Ubiquitous and almost universal client types
  • Zero client management
  • Support various client devices
  • (E.g., J2ME-enabled cell-phones)
  • Cons
  • Complexity in the middle-tier still need to be
    addressed.

8
Business Components In the Middle Tier
  • Business components that perform enterprise-wide
    business are residing and operating in the middle
    tier.
  • Managing business components in the middle-tier
    need services for handling
  • Lots of requests gt lifecycle management
  • Access information services gt persistence,
    transaction management
  • Many and varied operations gt security management
  • Potential remote access gt distributed objects
  • Three evolutionary streams are merged in the
    enterprise computing environment.
  • Server-side business application environments
  • Mainframes, databases, TP monitors
  • Design and development paradigms
  • OOP, UML, OO languages, component principles
  • Distributed application elements
  • RPC, remote objects (RMI, CORBA)
  • Need to have middle tier that can manage
    enterprise-wide distributed business components
    with quality services outlined above.

9
Services Required by the Middle-tier Server (in
Java Environments)
  • Lifecycle services
  • For flexible, extensible, scalable component
    management
  • Container manages instances, based on deployment
    and component callbacks
  • Transaction services
  • Based on the Java Transaction API (JTA) which is
    based on and supports the X/Open XA model
  • The X/Open XA interface is a specification that
    describes the protocol for transaction
    coordination, commitment, and recovery between a
    transaction manager and one or more resource
    managers.
  • Persistence services
  • Needs to handle the data persistence. Ideally
    business components developers do not need to
    handle the database access logic. Instead, it
    will be dealt with by the middle-tier server.
  • Security services
  • J2EE Declarative and programmatic security
  • Distributed access services
  • RMI or CORBA IIOP

10
Enterprise JavaBeans (EJBs)
  • EJBs are server components designed to
    encapsulate business logic, and to keep
    developers from having to provide system-level
    services.
  • The EJB Specification defines an architecture for
    managing transactional, distributed business
    objects in an n-tier architecture.
  • Provides a set of contracts between the server
    container and the component developer.
  • Server vendors focus on system-level services.
  • Developers focus on business logic.
  • EJBs are J2EE components.
  • Deployment model, general application assembly
    model applies
  • Basic elements are Java stuff
  • EJBs are managed components.
  • A collection of related objects that operate in
    an environment with well-specified services and
    contracts
  • JavaBean remote object (local, remote)
    runtime services
  • Services are accessed through the container.
  • Contracts exist between the component, its
    container, and its clients.
  • Contracts maintain the integrity of the services.
  • EJBs are business components.

11
Component-based Software System
  • A software component is
  • A software element that confirms to a component
    model and can be independently deployed and
    composed without modification according to a
    composition standard.
  • Advance Features of Software Components
  • Component model conformity
  • Interoperability
  • Customizability and packaging
  • Deploy-ability
  • Component-based software system
  • Is an assembly of software components, which
    follows an engineering process that conforms to
    component based software engineering principles.
  • Heterogeneity
  • Source code availability
  • Evolvability
  • Distribution
  • Reusability

12
Component-based SS (contd)
  • A component model is the backbone of a
    component-based system. It provides critical
    support for component development, composition,
    communication, deployment, evolvement and etc
  • Commercial Component Model
  • J2EE (JavaBean, EJB, Web Service)
  • NET (OLE, ActiveX, COM/DCOM/COM, Web Service)
  • CORBA
  • Comparison between J2EE and .Net
  • Portability/interoperability
  • Reliability, scalability
  • Development environment
  • Ownership
  • Training

13
J2EE versus .NET
14
J2EE versus .NET (contd)
15
Traditional SW Engineering Process
16
Component-based SW Engineering
17
Issues
  • How to design a CBS? Design Pattern?
  • How to select, customize components?
  • What are the issues during the component
    composition?
  • How to test CBS?
  • How to maintain CBS?

18
EJB Definition
  • Suns definition
  • The Enterprise JavaBeans architecture is a
    component architecture for the development and
    deployment of component-based distributed
    business applications. Applications written using
    the Enterpirse JaveBeans architecture are
    scalable, transactional and multi-user secure.
  • EJB
  • Enterprise JavaBeans is a standard server-side
    component model for distributed business
    applications.

19
Evolving EJB Standards
  • EJB 1.0
  • Session beans only, entity beans optional
  • No deployment descriptor format defined
  • EJB 1.1
  • Session and entity beans required
  • XML-based deployment descriptors
  • Contracts tightened up, a few API changes
  • EJB 2.0
  • New message-driven beans
  • New container-managed persistence scheme (EJB-QL)
  • Local client interfaces
  • EJB 2.1
  • Support for exposing EJBs as SOAP web services
  • Timer services added to container for time-based
    business logic (e.g., run a query in five minute,
    etc).

20
Why EJB 3.0?
  • Engineering principle "Everything should be made
    as simple as possible." The same can be said for
    enterprise software development.
  • EJB 2.1 Framework is overly too complex
  • EJB 3.0 is the revision of the Enterprise Java
    Beans specification. One of the most significant
    changes in EJB 3.0 is the introduction of a
    standard Object/Relational mapping (ORM)
    specification and the move to POJO (Plain Old
    Java Object) based persistence.
  • The EJB 3.0 framework is a standard framework
    defined by the Java Community Process (JCP) and
    supported by all major J2EE vendors. EJB 3.0
    makes heavy use of Java annotations
    (java.lang.annotation)
  • Enables declarative programming to greater extent
  • Imperative (how) vs. declarative (what)

21
JDO versus Hibernate (EJB 3.0)
  • Two competing ORM technologies (for data
    persistence)
  • JDO vs Hibernate
  • What was wrong with JDO (Java Data Objects based
    on XML-based metadata)? Still open debates
  • JDO is not a very appropriate model for ORM
  • The JDO specification is just absurdly
    over-complex
  • There are some problems right at the heart of the
    JDO specification that are simply not easy to fix
    (still same in JDO2.0)
  • EJB 3 expert group's decision to develop their
    own POJO persistence solution (based on Hibernate
    http//www.hibernate.org/) rather than adopting
    JDO.
  • Hibernate is a powerful and high performance
    object/relational persistence mapping and query
    service for Java.
  • Hibernate supports the EJB 3.0/JSR-220
    persistence standardization effort.

22
EJB 3.0 Features
  • EJB 3.0
  • The EJB 3.0 Specification defines a variety of
    annotation types such as those that specify a
    bean's type (_at_Stateless, _at_Stateful,
    _at_MessageDriven, _at_Entity)
  • A bean is remotely or locally accessible
    (_at_Remote, _at_Local), transaction attributes
    (_at_TransactionAttribute), and security and method
    permissions (_at_MethodPermissions, _at_Unchecked,
    _at_SecurityRoles).
  • There are many more annotations defined in the
    specification than these.
  • Annotations for the EJB 3.0 annotation types
    generate interfaces required by the class as well
    as references to objects in the environment.
  • Based on so called POJO (Plain Old Java Objects)
    and POJI (Plain Old Java Interfaces).
  • JNDI is no longer required to get references to
    resources and other objects in an enterprise
    bean's context (it can still be used if desired).
  • A developer can use resource and environment
    reference annotations in the bean class.
  • Open source and commercial implementations of
    pre-release EJB 3.0 specifications are in part
    available from JBoss and Oracle.
  • JBOSS 4.0.3 or higher to conduct limited
    experiment with EJB 3.0.

23
Spring vs. EJB 3.0
  • http//www.springframework.org/
  • The Spring framework is a popular but
    non-standard open source framework. It is
    primarily developed by and controlled by
    Interface21 Inc.
  • The architecture of the Spring framework is based
    upon the Dependency Injection (DI) design
    pattern.
  • A class may have dependencies on other classes to
    perform useful tasks. The class can create its
    own dependencies, or the dependencies can be
    injected into the class instance.  Removing the
    responsibility for creating dependencies from a
    class is called Dependency Injection (or
    Inversion of Control.)
  • The dependencies can be attached by either
    setting properties or using a constructor
    function to setup all dependencies at
    instantiation.
  • Spring can work standalone or with existing
    application servers and makes heavy use of XML
    configuration files.
  • The EJB 3.0 framework is a standard framework
    defined by the Java Community Process (JCP) and
    supported by all major J2EE vendors.
  • EJB 3.0 makes heavy use of Java annotations
    (java.lang.annotation)
  • Enables declarative programming to greater extent
  • Imperative (how) vs. declarative (what)

24
EJB Framework
25
Enterprise JavaBeans (EJBs) Redefined
  • Enterprise JavaBeans is a framework for
    distributed component based processing.
  • Typically EJBs are secure, transactional elements
    of business processing that can be shared across
    different applications running in different
    computing environments.

26
(No Transcript)
27
The EJB RMI-IIOP
  • Common Object Request Broker Architecture (CORBA)
  • Specifications governed by the Object Management
    Group (OMG)
  • CORBA is language neutral, using interfaces
    written in Interface Definition Language (IDL).
  • CORBA uses Object Request Brokers (ORBs) for
    networking and data marshalling.
  • EJBs borrow heavily from this technology and from
    RMI
  • RMI-IIOP
  • CORBA services incorporated into EJBs
  • Naming, Lifecycle management, Security
  • Persistence, Distributed structures

28
Three Major Components of EJB Technology
  • Server, Container, Business Components (EJBs)

29
EJB Server
  • The EJB server provides transparent services
    available to all EJBs.
  • The servers job is to hide the complexity of
    these services from the applications that require
    them.
  • The EJB specification outlines eight services
    that must be provided by all EJB servers.

30
EJB Container
  • The EJB container integrates with the EJB server
    and acts as an abstraction layer between the
    server and the business components running under
    the control of the server.
  • This is the only mechanism by which the various
    business components can access the services
    provided by the server.
  • With the servers transparent service
    infrastructures, the container
  • Servicing multiple concurrent clients (business
    object life cycle management and pooling)
  • Managing transactions on shared data
  • Automatic database updates with no SQL (Container
    Managed Persistence)
  • Controlling access to the application (security)
  • Providing remote access to the application (RMI,
    CORBA IIOP)
  • Scaling the application to run on multiple
    servers (clustering)

31
EJB Roles
  • The EJB specification outlines six logical roles
    required for EJB development
  • Bean provider, application assembler, deployer,
    server provider, container provider, system
    administrator
  • An individual might play one or more of these
    roles on a project involving EJB development.
  • The bean provider is a developer.
  • Responsible for translating business requirements
    into physical code within an EJB.
  • The final product of the bean provider is an JAR
    file containing the appropriate classes as well
    as the structural content of the deployment
    descriptor.
  • The application assembler is often a team leader
    or senior developer.
  • Responsible for packaging all of the JAR files
    generated by the bean providers into a complete
    application.
  • Their final product is an enterprise archive
    (EAR) file containing the appropriate JAR files.

32
EJB Roles (contd)
  • The deployer is usually a senior developer or
    architect.
  • Responsible for installing the application into
    the target runtime environment.
  • Must be familiar with all aspects of the
    environment including security and transaction
    support.
  • The server provider is usually an external
    vendor.
  • The job of the server provider is to produce an
    EJB server thats compliant with the EJB
    specifications.
  • The container provider is usually an external
    vendor and is often the same as the server
    vendor.
  • The container provider produces an EJB container
    thats compliant with the EJB specifications.
  • The system administrator is generally a member of
    the organization into which an application is
    being installed.
  • Ensures that the runtime environment is
    configured in such a way that the application can
    function correctly and integrate with all of the
    required external components

33
Remote and Local Interfaces
  • The component and home interfaces are client
    views on the EJB.
  • Remote
  • Used for accessing beans outside the JVM managing
    the bean class
  • Restricts access to pass by value, and parameters
    must be Serializable
  • Local
  • Used by clients that share a JVM with the bean
  • Do not involve networking
  • Use pass by reference semantics
  • Allow association with other EJBs (in the local
    JVM, thus reduce communication overheads)

34
EJB Types
  • Bean Types
  • Session Beans
  • Entity Beans
  • Message Driven Beans

35
Session Beans
  • Session Beans
  • Task-oriented
  • Model non-persistence state
  • May access data directly or through entity beans
  • Stateless vs. stateful session beans.
  • Usage model business process being performed by
    a client.

36
Entity Beans
  • Entity Beans
  • Model persistent data structures.
  • EJB 2.x (Heavyweight) vs. EJB 3.0(ORM)
  • Usage Represent data in the database or states
    across all client interactions.

37
Message-Driven Beans
  • Message-Driven Beans
  • Introduced in EJB 2.0
  • Asynchronously invoked to handle the processing
    of incoming JMS messages.
  • Similar to Stateless session beans.
  • Usage Model businesses involved with
    asynchronous messages.

38
Concerns to EJB Architecture
  • Performance
  • Communication overhead
  • Number of remote invocations
  • Amount of data that is transferred
  • Marshalling cost of parameters/results
  • Database/Entity Bean overhead
  • Mapping
  • Transaction
  • Deadlock
  • Complicated transactions
  • Added complexity and increased development time
  • Continual specification revisions

39
When to Use EJB?
  • Rules for choosing EJB
  • Scalability
  • Transaction
  • Comprehensive security model
  • Rules for not choosing EJB
  • Dirty, fast solution
  • Not scale, no transaction and comprehensive
    security
  • Expensive to train or hire qualified people
  • No platform independent
  • Thread control

40
Develop Your First EJB
  • A simplest EJB contains
  • A remote/local interface
  • A bean implementation class
  • Developing the Remote Interface
  • Remote interface defines what business methods
    the bean is to expose to the client.
  • Clients needs to make a reference to the remote
    interface to carry on some business processing.
  • Remote
  • Used for accessing beans outside the JVM managing
    the bean class
  • Restricts access to pass by value, and parameters
    must be Serializable
  • Local
  • Used by clients that share a JVM with the bean
  • Do not involve networking
  • Use pass by reference semantics
  • Allow association with other EJBs (in the local
    JVM, thus reduce communication overheads)

41
Developing Bean Implementation Class
  • The implementation class contains all the actual
    implementation details of the business logic. In
    addition, some EJB-specific call backs are
    required.
  • The type of bean determines what interface our
    implementation class will implement.

42
Application Deployment in JBoss
  • You can deploy applications in the following
    form
  • JAR (Java application archive
  • EJB JAR (Java application archive)
  • WAR (Web application archive)
  • EAR (Enterprise application archive)
  • To deploy, copy the file to
  • JBOSS HOME/server/default/deploy directory
  • Te redeploy, overwrite the file with a more
    recent version (hot deployment)
  • To un-deploy, remove the file from the directory
  • JAR and WAR files are platform and server
    independent, EAR files are not
  • Assembling an EAR file is usually done through a
    deployment wizard.

43
Hypersonic DBMS
  • Hypersonic is an open-source relational database
    that ships with JBoss.
  • For our EJB studies, well use Hypersonic as a
    DBMS running under control of JBoss.
  • Easier and better to concentrate on the EJB
    technologies.
  • The Hypersonic database service must be activated
    within Boss.
  • Open the file hsqldb-ds.xml in the JBOSS
    HOME/server/default/deploy directory.
  • Make sure the following line is uncommented.
  • ltconnection-urlgt.lt/connection-
    urlgt
  • Once you master the EJB in JBoss, try to develop
    your applications with a different DBMS.
  • http//www.onjava.com/pub/a/onjava/2004/02/25/jbos
    sjdbc.html
  • Oracle Database Configuration
  • MySQL Database Configuration
  • Sybase Database Configuration
  • DB2 Database Configuration
  • Informix Database Configuration

44
Client Implementation
  • Obtain a reference to a JNDI server
  • Obtain a reference to a remote object.
  • Invoke a business method on the bean.
  • public static Context getInitialContext() throws
  • javax.naming.NamingException
  • Properties p new Properties()
  • p.put(Context.INITIAL_CONTEXT_FACTORY,
  • "org.jnp.interfaces.NamingContextFactory")
  • p.put(Context.URL_PKG_PREFIXES,
  • "org.jboss.namingorg.jnp.interfaces")
  • p.put(Context.PROVIDER_URL, "jnp//localhost1099
    ")
  • return new InitialContext(properties)

45
Client Implementation
  • Context jndiContext getInitialContext()
  • Object ref jndiContext.lookup("HelloWorld/remote
    ")
  • HelloRemote dao
  • (HelloRemote)PortableRemoteObject.narrow(ref,
  • HelloRemote.class)
  • System.out.println(dao.HelloWorld("test"))

46
TravelAgentRemote
  • package com.titan.travelagent
  • import javax.ejb.Remote
  • import com.titan.domain.Cabin
  • _at_Remote
  • public interface TravelAgentRemote
  • public void createCabin(Cabin cabin)
  • public Cabin findCabin(int pKey)

47
TravelAgentBean
  • package com.titan.travelagent
  • import javax.ejb.Stateless
  • import javax.persistence.EntityManager
  • import javax.persistence.PersistenceContext
  • import com.titan.domain.Cabin
  • _at_Stateless
  • public class TravelAgentBean implements
    TravelAgentRemote
  • _at_PersistenceContext(unitName"titan") private
    EntityManager manager
  • public void createCabin(Cabin cabin)
  • manager.persist(cabin)
  • public Cabin findCabin(int pKey)

48
Entity Bean Example Cabin
  • package com.titan.domain
  • import javax.persistence.Entity
  • import javax.persistence.Table
  • import javax.persistence.Column
  • import javax.persistence.Id
  • _at_Entity
  • _at_Table(name"CABIN")
  • public class Cabin implements java.io.Serializable
  • private int id
  • private String name
  • private int deckLevel
  • private int shipId
  • private int bedCount
  • _at_Id
  • _at_Column(name"ID")

49
Entity Bean Example Cabin (contd)
  • _at_Column(name"NAME")
  • public String getName()
  • return name
  • public void setName(String str)
  • name str
  • _at_Column(name"DECK_LEVEL")
  • public int getDeckLevel()
  • return deckLevel
  • public void setDeckLevel(int level)
  • deckLevel level

_at_Column(name"SHIP_ID") public int
getShipId() return shipId
public void setShipId(int sid) shipId
sid _at_Column(name"BED_COUNT")
public int getBedCount() return
bedCount public void setBedCount(int
bed) bedCount bed
50
Client Program
  • dao.createCabin(cabin_1)
  • Cabin cabin_2 dao.findCabin(1)
  • System.out.println(cabin_2.getName())
  • System.out.println(cabin_2.getDeckLeve
    l())
  • System.out.println(cabin_2.getShipId()
    )
  • System.out.println(cabin_2.getBedCount
    ())
  • catch (javax.naming.NamingException ne)
  • ne.printStackTrace()
  • public static Context getInitialContext()
  • throws javax.naming.NamingException
  • return new javax.naming.InitialContext()
  • package com.titan.clients
  • import com.titan.travelagent.TravelAgentRemote
  • import com.titan.domain.Cabin
  • import javax.naming.InitialContext
  • import javax.naming.Context
  • import javax.naming.NamingException
  • import javax.rmi.PortableRemoteObject
  • public class Client
  • public static void main(String args)
  • try
  • Context jndiContext
    getInitialContext()
  • Object ref jndiContext.lookup("Trave
    lAgentBean/remote")

51
To Access an EJB, use JNDI
  • To access an EJB, a client starts using JNDI to
    obtain a directory connection to a beans
    container.
  • JNDI is an implementation-independent API for
    directory and naming systems.
  • Every EJB vendor must provide a directory service
    that is JNDI-compliant.
  • The getInitialContext() method uses JNDI to
    obtain a network connection to the EJB server.
  • Once a JNDI connection is established and a
    context is obtained from the getInitialContext()
    method, the context can be used to lookup the
    remote interface of the TravelAgent EJB
  • Object ref jndiContext.lookup("TravelAgentBean/r
    emote")
  • The actual name you use to do a lookup is
    vender-dependent

52
To Access an EJB, use JNDI (contd)
  • If you are using a standard Java EE component
    (Servlet, JSP, EJB or Java EE Application
    Client), you will not need to set the properties
    explicitly when creating a JNDI InitialContext,
    no matter which EJB vendor you are using.
  • Thats because the JNDI properties can be
    configured at deployment time and are applied
    automatically.
  • public static Context getInitialContext()
  • throws javax.naming.NamingException
  • return new javax.naming.InitialContex
    t()
  • From a servlet
  • Object ref jndiContext.lookup(javacomp/env/ejb
    /TravelAgentRemote)

53
build.xml
  • lt?xml version"1.0"?gt
  • ltproject name"JBoss" default"ejbjar"
    basedir"."gt
  • ltproperty environment"env"/gt
  • ltproperty name"src.dir" value"basedir/src/m
    ain"/gt
  • ltproperty name"src.resources"
    value"basedir/src/resources"/gt
  • ltproperty name"jboss.home" value"env.JBOSS_H
    OME"/gt
  • ltproperty name"build.dir" value"basedir/bui
    ld"/gt
  • ltproperty name"build.classes.dir"
    value"build.dir/classes"/gt
  • lt!-- Build classpath --gt
  • ltpath id"classpath"gt
  • ltfileset dir"jboss.home/server/default
    /lib"gt
  • ltinclude name".jar"/gt
  • lt/filesetgt
  • ltfileset dir"jboss.home/server/default
    /deploy/ejb3.deployer"gt
  • ltinclude name".jar"/gt
  • lt/filesetgt

54
build.xml
  • ltproperty name"build.classpath"
    refid"classpath"/gt
  • lt!--
    --gt
  • lt!-- Prepares the build directory
    --gt
  • lt!--
    --gt
  • lttarget name"prepare" gt
  • ltmkdir dir"build.dir"/gt
  • ltmkdir dir"build.classes.dir"/gt
  • lt/targetgt
  • lt!--
    --gt
  • lt!-- Compiles the source code
    --gt
  • lt!--
    --gt
  • lttarget name"compile" depends"prepare"gt
  • ltjavac srcdir"src.dir"
  • destdir"build.classes.dir"
  • debug"on"
  • deprecation"on"
  • optimize"off"

55
build.xml (contd)
  • lttarget name"ejbjar" depends"compile"gt
  • ltjar jarfile"build/titan.jar"gt
  • ltfileset dir"build.classes.dir"gt
  • ltinclude name"com/titan/domain/.class"/
    gt
  • ltinclude name"com/titan/travelagent/.cl
    ass"/gt
  • lt/filesetgt
  • ltfileset dir"src.resources/"gt
  • ltinclude name"META-INF/persistence.xml"
    /gt
  • lt/filesetgt
  • lt/jargt
  • ltcopy file"build/titan.jar"
    todir"jboss.home/server/default/deploy"/gt
  • lt/targetgt

56
build.xml (contd)
  • lttarget name"run.client" depends"ejbjar"gt
  • ltjava classname"com.titan.clients.Client"
    fork"yes" dir"."gt
  • ltclasspath refid"classpath"/gt
  • lt/javagt
  • lt/targetgt
  • lt!--
    --gt
  • lt!-- Cleans up generated stuff
    --gt
  • lt!--
    --gt
  • lttarget name"clean.db"gt
  • ltdelete dir"jboss.home/server/default/data
    /hypersonic"/gt
  • lt/targetgt
  • lttarget name"clean"gt
  • ltdelete dir"build.dir"/gt
  • ltdelete file"jboss.home/server/default/dep
    loy/titan.jar"/gt
  • lt/targetgt

57
\resources\META-INF\persistence.xml
  • Java Persistence specification requires a simple
    XML persistence.xml file,
  • which configures basic things like the name of
    the EntityManager service that will be managing
    the set of entities deployed in a particular
    deployment package.
  • It also defines what database the EntityManager
    service will be communicating with and may also
    specify additional, vendor specific properties.
  • lt?xml version"1.0" encoding"UTF-8" ?gt
  • ltpersistencegt
  • ltpersistence-unit name"titan"gt
  •   ltjta-data-sourcegtjava/DefaultDSlt/jta-data-sour
    cegt
  • ltpropertiesgt
  •   ltproperty name"hibernate.hbm2ddl.auto"
    value"create-drop" /gt
  •   lt/propertiesgt
  •   lt/persistence-unitgt
  • lt/persistencegt

58
\client-config\jndi.properties
  • java.naming.factory.initialorg.jnp.interfaces.Nam
    ingContextFactory
  • java.naming.factory.url.pkgsorg.jboss.namingorg.
    jnp.interfaces
  • java.naming.provider.urllocalhost

59
Session EJBs
  • Service Implementations

60
Session EJBs
  • Session EJBs are often called session beans
  • Session beans implement services
  • They provide some useful behaviour to the
    application
  • Session bean methods (behaviours) are often
    invoked by JSPs or Servlets
  • Session beans are invoked synchronously
  • A client sends a method invocation request to a
    session bean, and blocks
  • The method executes and completes
  • The client now regains control and resumes
    execution
  • This is similar to how methods are called in Java

61
Session Bean Types
  • There are two types of session bean
  • Stateless
  • The session bean does not maintain any
    conversational state
  • Thus, execution of a method does not affect any
    future invocations
  • Stateless session beans are more efficient
  • They can be easily pooled
  • Each instance of a given session bean is
    identical
  • Stateful
  • The session bean stores conversational state
  • This often includes shopping carts, login data,
    etc.
  • Stateful session beans are less efficient, but
    are often a requirement for certain services
  • The conversational state must be identical to
    that at the time of the previous executions
    return

62
Stateless vs. Stateful
  • Consider the following client using a stateful
    session bean
  • bean.setAccountID(accountID)
  • bean.deposit(100.0f)
  • Now consider the client below using a equivalent
    stateless session bean
  • bean.depositIntoAccount(accountID, 100.0f)

63
Stateless Session Beans
  • Stateless session beans should be used whenever
    possible, due to their pooling efficiency
  • They are typically used when one method call can
    complete the behaviour required
  • Examples
  • Currency conversion
  • Bank transaction (e.g. deposit)
  • Search

64
Stateless Session Beans
  • The following describes the lifecycle of a
    stateless session bean

Created
Service method invoked
Non-existent
Pooled
Destroyed
65
SLSB The Interface
  • import javax.ejb.Remote
  • import com.titan.domain.Cabin
  • _at_Remote
  • public interface TravelAgentRemote
  • public void createCabin(Cabin cabin)
  • public Cabin findCabin(int pKey)
  • The _at_Remote line is an annotation
  • It can occur on the previous line, or you can use
    it like a modifier (e.g. _at_Remote public )
  • Annotations specify meta-data
  • In this case, _at_Remote says that the interface can
    be used remotely
  • Alternatively, a local interface could be used
    when clients and EJBs are co-located.
  • Sun claims that this interface is a plain old
    Java interface (POJI)
  • It is, however, bound to the annotation _at_Remote,
    which is part of the EJB package
  • However, it is possible for this interface to be
    used outside of a container

66
SLSB The Bean
  • import javax.ejb.Stateless
  • import javax.persistence.EntityManager
  • import javax.persistence.PersistenceContext
  • import com.titan.domain.Cabin
  • _at_Stateless
  • public class TravelAgentBean implements
    TravelAgentRemote
  • _at_PersistenceContext(unitName"titan") private
    EntityManager manager
  • public void createCabin(Cabin cabin)
  • manager.persist(cabin)
  • public Cabin findCabin(int pKey)
  • return manager.find(Cabin.class, pKey)

67
SLSB The Client
  • public static void main(String args)
  • try
  • Context jndiContext
    getInitialContext()
  • Object ref jndiContext.lookup("Trave
    lAgentBean/remote")
  • TravelAgentRemote dao
    (TravelAgentRemote)ref
  • Cabin cabin_1 new Cabin()
  • cabin_1.setId(1)
  • cabin_1.setName("Master Suite")
  • cabin_1.setDeckLevel(1)
  • cabin_1.setShipId(1)
  • cabin_1.setBedCount(3)
  • The client uses the Java Naming and Directory
    Interface (JNDI) to obtain (and create) an
    instance of the bean

68
SLSB The Client (Alternative)
  • import javax.ejb.EJB
  • public class Client2
  • _at_EJB CurrencyConverter converter
  • public void convertTest()
  • float newVal converter.convert(USD, CAD,
    100f)
  • code omitted
  • The _at_EJB annotation marks the converter field as
    a dependency injected field
  • Dependency injection is a technical term that
    basically means that dependencies (such as an EJB
    to its client) are made externally
  • In EJB 3.0, you can declare which EJBs should be
    used by a particular when you deploy that client

69
Stateful Session Beans
  • While stateless session beans can be pooled more
    efficiently, some behaviours require
    conversational state
  • e.g. A shopping cart
  • The conversational state for stateful session
    beans is client-specific it is not shared with
    all clients of that bean type
  • This type of behaviour requires multiple method
    calls to complete
  • For example
  • bean.addToShoppingCart(item1)
  • bean.addToShoppingCart(item2)
  • items bean.getShoppingCartItems()
  • bean.removeFromShoppingCart(items1)
  • bean.checkout()

70
Stateful Session Beans
  • The following describes the lifecycle of a
    stateful session bean

Created
Service method invoked
Non-existent
Ready
Destroyed (by client)
Passivated
Activated
Destroyed (by container)
Passive
71
SFSB The Interface
  • import javax.ejb.Remote
  • _at_Remote
  • public interface Shopper
  • public void setCustomerID(int customerID)
  • public void addToShoppingCart(CartItem item)
  • public void removeFromShoppingCart(CartItem
    item)
  • public ArrayListltCartItemgt getShoppingCartItems()
  • public void checkout()
  • The _at_Remote annotation (as before) declares this
    interface as a remote interface
  • Similarly, the _at_Local annotation would declare it
    as a local interface, which can only be accessed
    from the same machine
  • Often, session beans (of both types) are accessed
    remotely, for example, from Java Server Pages or
    standalone clients

72
SFSB The Bean
  • import javax.ejb.Stateful
  • _at_Stateful
  • _at_Remote(Shopper.class)
  • public class ShopperImpl implements Shopper
  • public void setCustomerID(int customerID)
  • public void addToShoppingCart(CartItem item)
  • public void removeFromShoppingCart(CartItem
    item)
  • public ArrayListltCartItemgt getShoppingCartItems()
  • public void checkout()
  • The _at_Stateful annotation marks the bean as a
    stateful session bean
  • The _at_Remote annotation marks the Shopper
    interface as its remote interface

73
SFSB The Client
  • import javax.ejb.EJB
  • public class SFSBClient
  • _at_EJB Shopper shopper
  • public void cartTest()
  • CartItem item1 new CartItem(Briefcase 14x8,
    1)
  • CartItem item2 new CartItem(Ball Point Pen,
    12)
  • shopper.addToShoppingCart(item1)
  • shopper.addToShoppingCart(item2)
  • code omitted
  • You can use the dependency injection method of
    obtaining a session bean instance
  • This is the preferred method, since
  • It involves less code in the client
  • It saves the client from dealing with JNDI
    directly

74
Example SFSB
  • Exercise 11.4

75
Lifecycle Callbacks
  • For both types of session bean, weve examined
    the lifecycle of the beans
  • It is possible to receive notification when
    certain lifecycle changes occur
  • After creation of the bean (PostConstruct)
  • Before passivation of the bean (PrePassivate)
  • After activation of the bean (PostActivate)
  • Before destruction of the bean (PreDestroy)
  • Typically, these lifecycle events will trigger
    the acquisition or release of resources
  • e.g. network or database connections, open files,
    etc.

76
Lifecycle Callbacks
  • Lifecycle callbacks can be received
  • In the bean itself
  • _at_PrePassivate
  • public void passivateHandler()
  • // free up resources before going into passive
    mode
  • Or, in an external object (a callback
    interceptor)
  • _at_PostActivate
  • public void activateHandler(InvocationContext
    context)
  • // re-acquire resources

77
SFSB The Bean (with Interceptor)
  • import javax.ejb.Stateful
  • _at_Stateful
  • _at_Remote(Shopper.class)
  • _at_Interceptor(ShopperCallbackHandler.class)
  • public class ShopperImpl implements Shopper
  • public void setCustomerID(int customerID)
  • public void addToShoppingCart(CartItem item)
  • public void removeFromShoppingCart(CartItem
    item)
  • public ArrayListltCartItemgt getShoppingCartItems()
  • public void checkout()
  • The _at_Interceptor annotation will allow the class
    ShopperCallbackHandler class to receive lifecycle
    callbacks

78
SFSB The Interceptor
  • public class ShopperCallbackHandler
  • _at_PostConstruct
  • public void postConstruct(InvocationContext
    context)
  • System.out.println(postConstruct())
  • _at_PrePassivate
  • public void prePassivate(InvocationContext
    context)
  • System.out.println(prePassivate())
  • _at_PostActivate
  • public void postActivate(InvocationContext
    context)
  • System.out.println(postActivate())
  • _at_PreDestroy
  • public void preDestroy(InvocationContext
    context)
  • System.out.println(preDestroy())
  • The methods above can have any name, but

79
The _at_Remove Annotation
  • The _at_Remove annotation declares a method to
    represent the deletion of the bean
  • The method itself does not implement the deletion
    of the bean
  • The method is called first, then the container
    deletes the bean
  • This annotation is available to both types of
    session bean, as well as message-driven beans
  • public ShopperImpl implements Shopper
  • other methods omitted
  • _at_Remove
  • public void remove()
  • System.out.println(Removing Shopper)

80
Pooling Stateful Session Beans
  • When a stateful session bean becomes passive, it
    goes into an available pool
  • The state is serialized and stored to disk
  • When the beans client invokes one of the beans
    methods, the bean is activated again
  • However, if the bean remains unused for too long,
    it may be deleted
  • In these cases, the container may create a new
    instance, and load the state into the new bean
    for the client

81
Message-Driven Beans
  • Asynchronous Service Implementations

82
Message-Driven Beans
  • Message-driven EJBs are often called
    message-driven beans (or MDBs)
  • MDBs implement services
  • They provide some useful behaviour to the
    application
  • MDB methods (behaviours) can be invoked by JSPs,
    Servlets, the container, the database, Java
    objects, or even other applications
  • MDBs are invoked asynchronously
  • A client sends a message to an MDB
  • The client can immediately resume execution
  • Concurrently, the MDB handles the message
  • Although event-handling in Java uses method
    invocation, many other languages use asynchronous
    messaging to handle events

83
Message-Driven Beans (contd)
  • The advantages provided by MDBs include
  • Asynchronous message processing
  • Messaging occurs through middleware
  • Offline messaging is possible
  • Multiplexed messaging is possible

84
Message-Driven Beans (contd)
  • The advantages provided by MDBs include
  • Asynchronous message processing
  • Clients send messages to MDBs, but resume
    execution immediately, not waiting for the MDB to
    complete its operation
  • If the operation is expected to take a long time
    (file/database access or sending E-Mail), the
    client is saved from experiencing this delay
  • Messaging occurs through middleware
  • Offline messaging is possible
  • Multiplexed messaging is possible

85
Message-Driven Beans (contd)
  • The advantages provided by MDBs include
  • Asynchronous message processing
  • Messaging occurs through middleware
  • Middleware can decouple the sender of a message
    from its receiver (location transparent)
  • Moving a sender has no effect on the system
  • Moving a receiver involves re-routing the message
    to a new location in the middleware
  • Non-MDB clients can also send messages to MDBs
  • Offline messaging is possible
  • Multiplexed messaging is possible

86
Message-Driven Beans (contd)
  • The advantages provided by MDBs include
  • Asynchronous message processing
  • Messaging occurs through middleware
  • Offline messaging is possible
  • The messaging middleware could store messages to
    be sent then the receiver is available
  • Multiplexed messaging is possible

87
Message-Driven Beans (contd)
  • The advantages provided by MDBs include
  • Asynchronous message processing
  • Messaging occurs through middleware
  • Offline messaging is possible
  • Multiplexed messaging is possible
  • A message can be broadcast or multicast to
    multiple receivers
  • In method invocation this is not possible

88
Java Message Service (JMS)
  • JMS is a generic Java API for messaging
  • The service theoretically can access any
    message-oriented middleware (MOM)
  • IBM WebSphere MQ (formerly MQ Series)
  • BEA Tuxedo/Q
  • Microsoft MSMQ
  • SonicMQ
  • Asynchronous SOAP
  • Tibco Rendezvous
  • These MOMs support guaranteed message delivery
    (using acknowledgements)
  • JMS is used (indirectly) by MDBs to receive
    messages

89
Types of Messaging
  • There are two types of messaging
  • Publish/subscribe
  • Messages are broadcast to a public or private
    repository, to be downloaded by any number of
    receivers
  • Point-to-point
  • Messages are sent to a specific receiver
  • Both types of messages can have multiple senders
    adding messages to the queue
  • However, only publish/subscribe messaging can
    have multiple receivers for each message

90
MDB Example
  • Exercise 12.1

91
MDB The Bean
  • import javax.ejb.
  • import javax.jms.
  • _at_MessageDriven(activationConfig
  • _at_ActivationConfigProperty(propertyNamedestinati
    onType, propertyValuejavax.jms.Topic)
  • )
  • public class NewsletterMailer implements
    MessageListener
  • // This method is declared in MessageListener (a
    JMS interface)
  • public void onMessage(Message msg)
  • try
  • if (msg instance of ObjectMessage)
  • ObjectMessage objMessage
    (ObjectMessage)msg
  • NewsLetter newsletter (NewsLetter)msg.getO
    bject()
  • String content newsletter.getContent()
  • // send content via E-Mail to the
    newsletters subscribers
  • catch (Exception e)
  • e.printStackTrace()

92
MDB The Client (JMS)
  • import javax.jms.
  • public class NewsletterClient
  • _at_Resource(mappedName"jms/NewMessageFactory")
    private ConnectionFactory connectionFactory
  • _at_Resource(mappedName"jms/NewMessage") private
    Queue queue
  • public void sendNewsLetter(String content)
  • NewsLetter newsletter new
    NewsLetter(content)
  • try
  • Connection connection connectionFactory.cr
    eateConnection()
  • Session session connection.createSession(f
    alse, Session.AUTO_ACKNOWLEDGE)
  • MessageProducer messageProducer
    session.createProducer(queue)
  • ObjectMessage objMessage
    session.createObjectMessage()
  • objMessage.setObject(newsletter)
  • messageProducer.send(objMessage)
  • messageProducer.close()
  • catch (Exception e)
  • e.printStackTrace()

93
Service-Oriented Architecture (SOA)
  • SOA is a way to structure an application so that
    its services are loosely coupled with their users
    and each other
  • In some sense, dependency injection in a session
    bean is a way to loosely couple an EJB with its
    client
  • However, SOA takes this idea much further
  • A service bus is used for communication between
    services
  • On the service bus, protocols and network
    locations are transparent

94
SOA vs. SOAP
  • SOA should not be confused with SOAP
  • Simple Object Access Protocol The protocol used
    for web services
  • While you certainly can implement SOA with web
    services, it is not necessary
  • However, it is very common for SOA to be
    implemented using SOAP (and related technologies
    WSDL, UDDI, ebXML, BPEL)

95
Web Services and SOAP
  • Web services use SOAP (Simple Object Access
    Protocol) to communicate
  • A client sends a SOAP request
  • The web service sends back a SOAP response

96
Web Services and SOAP
  • Web services use SOAP (Simple Object Access
    Protocol) to communicate
  • A client sends a SOAP request
  • lt?xml version"1.0" encoding"UTF-8" ?gt
  • ltSOAP-ENVEnvelope references omitted gt
  • ltSOAP-ENVBodygt
  • ltns1someMethod xmlnsns1"urnMySoapService
    s"gt
  • ltsomeParam xsitype"xsdstring"gtabcdelt/s
    omeParamgt
  • lt/ns1someMethodgt
  • lt/SOAP-ENVBodygt
  • lt/SOAP-ENVEnvelopegt
  • The web service sends back a SOAP response

97
Web Services and SOAP
  • Web services use SOAP (Simple Object Access
    Protocol) to communicate
  • A client sends a SOAP request
  • The web service sends back a SOAP response
  • lt?xml version"1.0" encoding"UTF-8" ?gt
  • ltSOAP-ENVEnvelope some references omitted gt
  • ltSOAP-ENVBodygt
  • ltns1someMethodResponse xmlnsns1"urnMySoa
    pServices" SOAP-ENVencodingStyle"http//schemas.
    xmlsoap.org/soap/encoding/"gt
  • ltreturn xsitype"xsdint"gt12345lt/returngt
  • lt/ns1someMethodResponsegt
  • lt/SOAP-ENVBodygt
  • lt/SOAP-ENVEnvelopegt

98
Web Services and SOAP
  • Web service developers do not generally need to
    know SOAP
  • The middleware handles the generation of stubs
    and ties to handle client and server side SOAP,
    respectively
  • In Java EE, JAX-WS is the specification for the
    middleware which provides SOAP implementations
  • It can come in handy to know the basics of the
    protocol during debugging, however

99
Web Service The Service
  • import javax.jws.WebService
  • import javax.jws.WebMethod
  • _at_WebService(serviceNameCurrencyConvert,
    portNameCurrencyConvertPort)
  • public class CurrencyConvertImpl implements
    CurrencyConvert
  • _at_WebMethod
  • public float convert(String from, String to,
  • float amount)
  • The _at_WebService annotation marks this class as a
    web service with the name CurrencyConvert and
    port name CurrencyConvertPort
  • The _at_WebMethod annotation marks the convert()
    method as accessible web service protocols (SOAP)

100
Web Service The Client
  • String url http//www.mysite.org8000/CurrencyC
    onverter
  • String namespace http//www.mysite.org
  • URL wsdlURL new URL(url /CurrencyConverterImp
    l?WSDL)
  • QName serviceName new QName(namespace, url)
  • Service service Service.create(wsdlURL,
    serviceName)
  • CurrencyConverter converter service.getPort(Curr
    encyConverter.class)
  • float amount converter.convert(USD, CAD,
    100f)
  • This code accesses the web service to call the
    remote method
  • The web service has an added advantage that
    non-Java clients can call its methods

101
Web Service/EJB The Service
  • import javax.ejb.Stateless
  • import javax.jws.WebService
  • import javax.jws.WebMethod
  • _at_Stateless
  • _at_Remote(CurrencyConvert.class)
  • _at_WebService(serviceNameCurrencyConvert,
    portNameCurrencyConvertPort)
  • public class CurrencyConvertImpl implements
Write a Comment
User Comments (0)
About PowerShow.com