95-702 Organizational Communication Technologies 1 Enterprise Java Beans Detail.
-
date post
22-Dec-2015 -
Category
Documents
-
view
228 -
download
0
Transcript of 95-702 Organizational Communication Technologies 1 Enterprise Java Beans Detail.
95-702 Organizational Communication Technologies
2
Notes from:
“Advanced Java 2 Platform How to Program” Deitel Deitel Santry
“Thinking in Enterprise Java” Bruce Eckel et. Al.
Sun documentation and J2EE Tutorial http://java.sun.com
95-702 Organizational Communication Technologies
3
Benefits of Enterprise Beans
• Simplify development of large, distributed applications
• The developer can concentrate on business problems
• The EJB container handles transaction management and security authorization
• Portable – may be moved to other J2EE containers
95-702 Organizational Communication Technologies
4
Benefits of Enterprise Beans(2)
• Scalable – the components may be distributed across many machines
• Location Transparency – the client should not be concerned with the location of the bean
• Transaction management - ensures data integrity (over concurrent access of shared resources)
• Promotes thin clients and web services
95-702 Organizational Communication Technologies
5
Entity Bean
• Each entity bean has a unique identifier called its primary key
• The primary key can be used by the client to locate the bean
• Each bean represents a row in its table• Rows may have columns that reference other
entity beans (students take courses)• These relationships may be managed by the
bean or by the container (container managed relationships)
95-702 Organizational Communication Technologies
6
Relationships OrderEJB CusomerEJB 1 Many 1
Many
LineItemEJB ProductEJB
Many 1
A relationship field is like a foreign key in a database.If a b then a “knows about” or “holds a pointer to” b.
95-702 Organizational Communication Technologies
7
Entity Bean Life Cycle (From Sun)
Does not exist
Pool of available instances
-- Ready to havebusiness methods called
-- Has an identity
setEntityContext unsetEntityContext
ejbActivate ejbPassivateClient callscreate and container calls ejbCreateand ejbPostCreate
Client callsremove andcontainer callsejbRemove
Client initiates
Containerinitiates
95-702 Organizational Communication Technologies
8
A Typical Entity Bean Needs
• A Home interface defining the create and finder methods
• A Component interface defining the business methods a client may call
• An implementation of the Component interface
• Deployment descriptors
95-702 Organizational Communication Technologies
9
A Home Interface
import javax.ejb.*; // From Eckelimport java.util.Collection;import java.rmi.RemoteException; public interface MovieHome extends EJBHome { public Movie create(Integer id, String title) throws RemoteException, CreateException; public Movie findByPrimaryKey(Integer id) throws RemoteException, FinderException;}
95-702 Organizational Communication Technologies
10
A Component Interfaceimport javax.ejb.*; // From Eckelimport java.rmi.RemoteException; /** * A movie, with id and title. * * Note that there is no setId() method in the * interface, to prevent clients from arbitrarily * changing a movie's primary key. */public interface Movie extends EJBObject { public Integer getId() throws RemoteException; public String getTitle() throws RemoteException; public void setTitle(String title) throws RemoteException;}
95-702 Organizational Communication Technologies
11
The Container Implements the component interface (From Eckel)
95-702 Organizational Communication Technologies
12
import javax.ejb.CreateException; // From Eckelimport javax.ejb.EntityBean;import javax.ejb.EntityContext; public abstract class MovieBean implements EntityBean { // Container notifications methods public Integer ejbCreate(Integer id, String title) throws CreateException { if (id == null) throw new CreateException("Primary key cannot be null"); if (id.intValue() == 0) throw new CreateException("Primary key cannot be zero"); setId(id); setTitle(title); return null; }
95-702 Organizational Communication Technologies
13
public void ejbPostCreate(Integer id, String title) {} // Called by public void ejbLoad() {} // container public void ejbStore() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setEntityContext(EntityContext ctx) {} public void unsetEntityContext() {} // Business methods provided by container public abstract void setId(Integer id); public abstract String getTitle(); public abstract void setTitle(String title); public abstract Integer getId();}
// From Eckel
95-702 Organizational Communication Technologies
14
Deployment Descriptor<ejb-jar> // From Eckel <enterprise-beans> <entity> <ejb-name>Movie</ejb-name> <home>javatheater.ejb.MovieHome</home> <remote>javatheater.ejb.Movie</remote> <ejb-class> javatheater.ejb.implementation.MovieBean </ejb-class> <persistence-type>Container</persistence-type> <prim-key-class>java.lang.Integer</prim-key-class> <reentrant>False</reentrant> <cmp-version>2.x</cmp-version> <abstract-schema-name>Movie</abstract-schema-name> <cmp-field><field-name>id</field-name>-</cmp-field> <cmp-field><field-name>title</field-name>-</cmp-field> <primkey-field>id</primkey-field> </entity> </enterprise-beans></ejb-jar>
95-702 Organizational Communication Technologies
15
Client (From Eckel)import javax.naming.*;import javatheater.ejb.*; public class MovieClient { public static void main(String[] args) throws Exception { javax.naming.Context initial = new javax.naming.InitialContext(); Object objRef = initial.lookup("javatheater/Movie"); MovieHome movieHome = (MovieHome) javax.rmi.PortableRemoteObject.narrow( objRef, MovieHome.class);
95-702 Organizational Communication Technologies
16
// Generate a primary key value int pkValue = (int) System.currentTimeMillis() % Integer.MAX_VALUE; // Create a new Movie entity Movie movie = movieHome.create( new Integer(pkValue), "A Bug’s Life" ); // As a test, locate the newly created entity movie = movieHome.findByPrimaryKey(new Integer(pkValue)); // Access the bean properties System.out.println(movie.getId()); System.out.println(movie.getTitle()); // Remove the entity movie.remove(); }}
95-702 Organizational Communication Technologies
17
Session Bean
• Represents a single client inside the J2EE server
• Is not persistent• May be stateful (holding the
conversational state of one client)• May be stateless (the container may
assign any bean to any client)• Is the only bean that may implement a
web service
95-702 Organizational Communication Technologies
18
Life Cycle of Stateful Session Bean
Does not exist
Ready for businessmethods to be called
Passive
From Sun
Client calls create.Container calls setSessionContextand then callsejbCreate
Container calls ejbPassivate beforepassivating
After activation the container callsejbActivate
Client calls remove, container calls ejbRemove
95-702 Organizational Communication Technologies
19
Life Cycle of a Stateless Session Bean (from Sun)
Does not exist
Ready
setSessionContextejbCreate
ejbRemove
95-702 Organizational Communication Technologies
20
A Typical Session Bean Has
• A Remote Interface defining the business methods a client will call
• A Home Interface for lifecycle management
• An enterprise bean class
95-702 Organizational Communication Technologies
21
Session Bean Remote Interface(From Sun)
import javax.ejb.EJBObject;import java.rmi.RemoteException;import java.math.*;public interface Converter extends EJBObject { public BigDecimal dollarToYen(BigDecimal dollars) throws RemoteException; public BigDecimal yenToEuro(BigDecimal yen) throws RemoteException; }
95-702 Organizational Communication Technologies
22
The Home Interface
import java.io.Serializable;import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;public interface ConverterHome extends
EJBHome { Converter create() throws RemoteException, CreateException;}
95-702 Organizational Communication Technologies
23
The Session Bean Class
import java.rmi.RemoteException;import javax.ejb.SessionBean;import javax.ejb.SessionContext;import java.math.*;public class ConverterBean implements SessionBean { BigDecimal yenRate = new BigDecimal("121.6000"); BigDecimal euroRate = new BigDecimal("0.0077");
public BigDecimal dollarToYen(BigDecimal dollars) { BigDecimal result = dollars.multiply(yenRate); return result.setScale(2,BigDecimal.ROUND_UP); }
95-702 Organizational Communication Technologies
24
public BigDecimal yenToEuro(BigDecimal yen) { BigDecimal result = yen.multiply(euroRate); return result.setScale(2,BigDecimal.ROUND_UP);}public ConverterBean() {}public void ejbCreate() {}public void ejbRemove() {}public void ejbActivate() {}public void ejbPassivate() {}public void setSessionContext(SessionContext sc) {}}
95-702 Organizational Communication Technologies
25
The Session Bean Clientimport javax.naming.Context;import javax.naming.InitialContext;import javax.rmi.PortableRemoteObject;import java.math.BigDecimal;public class ConverterClient {public static void main(String[] args) {try { Context initial = new InitialContext(); Object objref = initial.lookup ("java:comp/env/ejb/SimpleConverter"); ConverterHome home = (ConverterHome)PortableRemoteObject.narrow(objref, ConverterHome.class);
95-702 Organizational Communication Technologies
26
Converter currencyConverter = home.create(); BigDecimal param = new BigDecimal ("100.00"); BigDecimal amount = currencyConverter.dollarToYen(param); System.out.println(amount); amount = currencyConverter.yenToEuro(param); System.out.println(amount); System.exit(0); } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); } }}
95-702 Organizational Communication Technologies
27
Message Driven Bean
• Handles asynchronous messages• Normally acts as a JMS message listener• The message may have originated from an
application client, another enterprise bean, a web component or a non-Java application that can generate messages
• Like a stateless session bean but with no interfaces
• All operations within onMessage may be in a transaction context (the message is redelivered on rollback)
95-702 Organizational Communication Technologies
29
On The Client
// locate the connection factory and queue
connectionFactory =
(ConnectionFactory) jndiContext.lookup
("java:comp/env/jms/MyConnectionFactory");
destination =
(Queue) jndiContext.lookup("java:comp/env/jms/QueueName");
95-702 Organizational Communication Technologies
30
// Next, the client creates the queue connection, session, and sender:
connection = connectionFactory.createConnection();session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
messageProducer = session.createProducer(destination);
// Finally, the client sends several messages to the queue:
message = session.createTextMessage(); for (int i = 0; i < NUM_MSGS; i++) { message.setText("This is message " + (i + 1)); System.out.println("Sending message: " + message.getText()); messageProducer.send(message); }
95-702 Organizational Communication Technologies
31
JMS Message TypesJMS Message TypesMessage Type Body Contains
TextMessageA java.lang.String object (for example, an XML document).
MapMessageA set of name/value pairs, with names as String objects and values asprimitive types in the Java programming language. The entries can beaccessed sequentially by enumerator or randomly by name. The orderof the entries is undefined.
95-702 Organizational Communication Technologies
32
BytesMessageA stream of uninterpreted bytes. This message type is for literallyencoding a body to match an existing message format.
StreamMessageA stream of primitive values in the Java programming language, filledand read sequentially.
ObjectMessage A Serializable object in the Java programming language.
95-702 Organizational Communication Technologies
33
On the serverpublic void onMessage(Message inMessage) { TextMessage msg = null; try { if (inMessage instanceof TextMessage) { msg = (TextMessage) inMessage; System.out.println("MESSAGE BEAN: Message received: " +msg.getText()); } else { System.out.println("Message of wrong type: " + inMessage.getClass().getName()); } } catch (JMSException e) { e.printStackTrace(); mdc.setRollbackOnly(); } catch (Throwable te) { te.printStackTrace(); } }
95-702 Organizational Communication Technologies
37
The Web Service as an EJB
• A Web service client can access J2EE applications in two ways.
• First, the client can access a Web service created with JAX-RPC. Behind the scenes, JAX-RPC uses a servlet to implement the Web service.
• Second, a Web service client can access a stateless session bean through the service endpoint interface of the bean. Other types of enterprise beans cannot be accessed by Web service clients.
95-702 Organizational Communication Technologies
38
A Stateless Session Bean as a Web Service
• The client need not know that its interacting with a Java EJB
• It calls the bean like it calls any other web service
95-702 Organizational Communication Technologies
39
The Web Service Endpoint Interface
package helloservice;
import java.rmi.RemoteException;
import java.rmi.Remote;
public interface HelloIF extends Remote {
public String sayHello(String name)
throws RemoteException;
}
The client cannotsee that it’s interactingwith an EJB
95-702 Organizational Communication Technologies
40
The Web Service Session Beanpackage helloservice;import java.rmi.RemoteException; import javax.ejb.SessionBean;import javax.ejb.SessionContext;
public class HelloServiceBean implements SessionBean {
public String sayHello(String name) {
return "Hello " + name + "from HelloServiceEJB"; } public HelloServiceBean() {} public void ejbCreate() {} public void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}}
If we added remote and homeInterfaces then this bean couldalso be called using in the traditionalmanner – with remote references. No change to the bean would be necessary.
WSDL can be generated and allof the previous clients will work.