480 likes | 675 Views
EJB Development and Support Services. EJB Development and Support Services. Topics to be Covered: EJB Design Bean/Container Interaction Java Naming and Directory Interface (JNDI) Using Enterprise Beans Server Side Services. EJB Development and Support Services. EJB Design.
E N D
EJB Development and Support Services
EJB Development andSupport Services Topics to be Covered: • EJB Design • Bean/Container Interaction • Java Naming and Directory Interface (JNDI) • Using Enterprise Beans • Server Side Services
EJB Development andSupport Services EJB Design
Class and Interface Review • javax.ejb package • Core of the EJB API • Remote interface • Defines bean’s remote business methods • Local interface • Defines bean’s local business methods • Endpoint interface • Defines SOAP-accessible business methods • Message interface • Defines methods for asynchronous messages • Bean class • Implementation of business and lifecycle methods
Remote Interface • Defines business methods import javax.ejb.Remote; @Remote public interface CalculatorRemote { public int add(int x, int y); public int subtract(int x, int y); }
Bean Class • Actual implementation of business methods import javax.ejb.*; @Stateless public class CalculatorBean implements CalculatorRemote { public int add(int x, int y) { return x + y; } public int subtract(int x, int y) { return x – y; } }
Entity • Java Persistence API import javax.persistence.*; @Entity @Table(name=“CABIN”) public class Cabin { private int id; private String name; private int deckLevel;
Primary Key @Id @GeneratedValue @Column(name=“ID”) public int getId() { return id; } public void setId(int pk) { this.id = pk; }
Remaining Fields @Column(name=“NAME”) public String getName() { return name; } public void setName(String str) { this.name = str; } @Column(name=“DECK_LEVEL”) public int getDeckLevel() { return deckLevel; } public void setDeckLevel(int level) { this.deckLevel = level; } }
Primary Keys • Pointer that locates an enterprise bean • Defined by the bean developer • Must map to one of the following types: • Any Java primitive type (including wrappers) • java.lang.String • Primary-key class composed of primitives and/or Strings
Primary Key Class • Composed of primitives and/or strings • Must be serializable • Must have a public no-arg constructor • Must implement the equals() and hashCode() methods
Deployment Descriptors • Specifies how to apply primary services • security • transactions • naming • Specifies persistence unit and associated database • Describe runtime attributes of server-side component
EJB Packaging • JAR Files used for packaging • Applets • Applications • JavaBeans • Web Application • Enterprise JavaBeans • Bean classes • Component interfaces • Supporting Classes • Appropriate Deployment Descriptors
Example Deployment Descriptor <?xml version="1.0"?> <ejb-jar> <enterprise-beans> <session> <ejb-name>ProcPayBean</ejb-name> <remote>com.relaxalot.ProcPayRemote</remote> <local>com.relaxalot.ProcPayLocal</local> <ejb-class>com.relaxalot.ProcPayBean</ejb-class> <session-type>Stateless</session-type> </session> </enterprise-beans> </ejb-jar>
XML and/or Annotations • Defaults make XML deployment descriptors optional • Default transaction property REQUIRED • Default security semantics UNCHECKED • Annotations provide further information • Metadata placed directly in the bean class file • Deployment descriptors can override annotations
Example persistence.xml <persistence> <persistence-unit name=“titan”> <jta-data-source>java:/TitanDB</jta-data-source> </persistence-unit> </persistence>
EJB Development andSupport Services Bean/Container Interaction
EJB Container Implementation • Component interfaces allow external or co-located clients to interact with session bean class • Component interfaces interact with instances of the session bean class • Proxy Stub • Interacts with client, sends message to EJB Container • EJB Object • Implements remote interface • Wraps enterprise bean instance • Generated by the container
EJB Architecture Client EJB Container remote interface EJB object proxy remote interface EJB object bean
EJB Container • Intermediary between bean and server • Interaction defined by SessionBean interface, and JMS-MessageDrivenBean onMessage() method • javax.ejb.EJBContext interface implemented by the container. • Bean uses EJBContext interface to communicate with EJB environment • JNDI namespace
EJB Development andSupport Services Java Naming and Directory Interface (JNDI)
Naming and Directory Services • Naming Service • Associates names with Objects • Provides facility to find an object based on a name • Examples: DNS, File System • Directory Object • Contains attributes • Like a record in a database • Directory Service • Provides directory object operations for manipulating attributes
JNDI Architecture JNDI Application Filesystem Service Provider LDAP Service Provider RMI Service Provider Filesystem LDAP Directory RMI Registry
JNDI API Benefits • Standard Java Extension • javax.naming • javax.naming.directory • Unified system for resource access • Insulates application from naming and directory service protocols • Extensible • Composite or federated namespaces
Naming Concepts • Binding • Association of a name with an object • Context • Set of bindings • Subcontext • Binding one context within another usr Context Subcontext bin tom Binding
Context & InitialContext • javax.naming.Context interface • Collection of bindings • Operations apply only to bindings, not to Context itself • javax.naming.InitialContext class • Implements the Context interface • Starting point for exploring a namespace • Requires an initial context factory com.sun.jndi.fscontext.RefFSContextFactory
InitialContext Properties • InitialContext constructor takes a set of properties Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, “com.sun.jndi.fscontext.RefFSContextFactory”); props.put(Context.PROVIDER_URL,”file:///”); Context initialContext = new InitialContext(props);
Looking Up Objects • lookup() method • Specify the name of the child • Type of returned object determined by service provider • Container with children should implement javax.naming.Context Object obj = initialContext.lookup(name);
Listing Objects • list() method • Returns a list of names of an object’s children as an instance of javax.naming.NamingEnumeration • NamingEnumeration contains a collection of javax.naming.NameClassPair objects • Browsing is a combination of list() and lookup() calls NamingEnumberation kids = initialContext.list(name);
Binding Objects • bind() method • Creates a Binding object • Use rebind() if name already exists • Use unbind() to remove a binding File newfile = File(“c:\temp\newfile”); tempContext.bind(“newfile”, newfile);
JNDI and JDBC • JDBC 2.0 DataSource • Provides Database connections • Information to create connections are stored as properties • Registered with a directory service Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup(“jdbc/EmployeeDB”); Connection con = ds.getConnection(); con.close();
JNDI and EJB • JNDI used to locate a specific EJB Home Context ctx = new InitialContext(); Object ref = ctx.lookup(“TravelAgntBean”); TravelAgntRemote dao = (TravelAgntRemote) PortableRemoteObject.narrow(ref, TravelAgntRemote.class); dao.makeReservation();
JNDI Environment Naming Context • Part of Bean-Container Contract • Common naming context • java:comp/env • Declare resources using XML deployment descriptor or Annotation • EJBs • JDBC DataSource • Java Message Service • Environment Properties Context ctx = new InitialContext();
ENC Example (Deployment Descriptor) – Describing the Resource <resource-ref> <description>DataSource for Relaxalot Database</description> <res-ref-name>theDataSource</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> <mapped-name>java:/DefaultDS</mapped-name> <injection-target> <injection-target-class> edu.weber.ProcessPaymentBean </injection-target-class> <injection-target-name>dataSource </injection-target-name> <injection-target> </resource-ref>
ENC Example (Annotation) – Describing the Resource public class ProcessPaymentBean implements ProcessPaymentRemote { ... @Resource(mappedName=“java:/DefaultDS”) DataSource dataSource
ENC Example – Use the Resource public class ProcessPaymentBean implements ProcessPayment Remote { ... private boolean process() { Connection con = dataSource.getConnection(); ... con.close(); }
EJB Development andSupport Services Using Enterpise Beans
Entities • Model data and behavior • Provide interface to data • Business rules that directly affect data • Relationships with other entities // Use javax.persistence.PersistenceContext // annotation to get access to entities // using an EntityManager service that // references a persistence unit @PersistenceContext(unitName=“titan”) private EntityManager manager; ... public void createCabin(Cabin cabin) { manager.persist(cabin); }
Session Beans • Model processes and tasks • Functions of the business • Inappropriate for client application or entity beans • Provide business logic • Control workflow // Lookup session bean TravelAgent tAgent = (TravelAgent)... // Create a reservation tAgent.setCustomer(customer); tAgent.setRoomID(roomID); tAgent.setHotelID(hotelID); Ticket ticket = tAgent.bookReserve(creditCard, price);
Session Beans • Stateful • Maintain conversational state • State kept in memory • Dedicated to a single client • Stateless • No conversational state • Method calls are independent • Provide higher performance • A few stateless beans can service many clients
EJB Development andSupport Services Server Side Services
Resource Management • Instance Pooling • Clients do not directly access EJB’s • Number of instances can be efficiently managed and minimized • Reuse existing beans for different client requests • Activation Mechanism • Used for stateful session beans • Passivation • Serialize bean’s state to storage • Activation • Restore a stateful bean instance’s state
Concurrency • Multiple clients accessing the same bean at the same time • Not supported by session beans • Entities represent shared data • Java Persistence spec: persistence container protects shared data by making a copy of the entity bean on a per-transaction basis • Defense against stale reads or simultaneous updates is vendor specific • EJB prohibits synchronized keyword • EJB prohibits beans from creating threads
Transactions • Set of tasks executed together • Atomic • Reservation and Payment must both be successful • Manage automatically • Declare transactional attribute • Manage explicitly • Use javax.transaction.UserTransaction object
Persistence • Applies to Entities • Java Persistence specification • Plain Old Java objects (POJO) • Can be created outside the scope of the EJB container • Attached/Detached • Entity Manager • Object-to-relational persistence • Map entity state to relational database tables and columns
Distributed Object Interoperability • Location Transparency • CORBA IIOP • Support mandated in EJB 3.0 • RMI/IIOP • SOAP via JAX-RPC API • Programming model used by Java EJB Client • Other protocols and clients can be supported by servers • CORBA clients written in C++, Smalltalk, Ada using EJB-to-CORBA mapping • SOAP clients written in Visual Basic.NET, C#, Perl using EJB-to-SOAP mapping
Asynchronous Enterprise Messaging • Message-driven Beans (MDBs) • Route messages from JMS clients to JMS-MDB • Reliable delivery • Attempt redelivery on failure • Persisted messages • Transactional • EJBs can send messages
EJB Development andSupport Services Topics to be Covered: • EJB Design • Bean/Container Interaction • Java Naming and Directory Interface (JNDI) • Using Enterprise Beans • Server Side Services