Download Enterprise Java Beans

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Enterprise Java Beans
Detail
95-702 Organizational
Communication Technologies
1
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
2
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
3
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
4
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
5
Relationships
OrderEJB
1
CusomerEJB
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
6
Entity Bean Life Cycle (From Sun)
Client initiates
Container
initiates
Does not exist
setEntityContext
unsetEntityContext
Pool of available
instances
Client calls
ejbPassivate
ejbActivate
create and
container calls
-- Ready to have
ejbCreate
business methods called
and ejbPostCreate
-- Has an identity
95-702 Organizational
Communication Technologies
Client calls
remove and
container calls
ejbRemove
7
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
8
A Home Interface
import javax.ejb.*;
// From Eckel
import 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
9
A Component Interface
import javax.ejb.*;
import java.rmi.RemoteException;
// From Eckel
/**
* 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
10
The Container Implements the
component interface (From Eckel)
95-702 Organizational
Communication Technologies
11
import javax.ejb.CreateException;
import javax.ejb.EntityBean;
import javax.ejb.EntityContext;
// From Eckel
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
12
// From Eckel
public void ejbPostCreate(Integer id, String title) {}
public void ejbLoad() {}
public void ejbStore() {}
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setEntityContext(EntityContext ctx) {}
public void unsetEntityContext() {}
// Called by
// container
// 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();
}
95-702 Organizational
Communication Technologies
13
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>
95-702 Organizational
</enterprise-beans>
Communication Technologies
</ejb-jar>
14
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
15
// 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
16
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
17
Life Cycle of Stateful Session Bean
From Sun
Does not exist
Client calls remove, container calls ejbRemove
Client calls create.
Container calls
setSessionContext
Container calls ejbPassivate before
and then calls
passivating
ejbCreate
Ready for business
Passive
methods to be called
After activation the container calls
ejbActivate
95-702 Organizational
Communication Technologies
18
Life Cycle of a Stateless Session
Bean (from Sun)
Does not exist
ejbRemove
setSessionContext
ejbCreate
Ready
95-702 Organizational
Communication Technologies
19
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
20
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
21
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
22
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
23
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
24
The Session Bean Client
import 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
25
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
26
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
27
From Sun
95-702 Organizational
Communication Technologies
28
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
29
// 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
30
JMS Message Types
JMS Message Types
Message Type Body Contains
TextMessage
A java.lang.String object (for example, an XML document).
MapMessage
A set of name/value pairs, with names as String objects and values as
primitive types in the Java programming language. The entries can be
accessed sequentially by enumerator or randomly by name. The order
of the entries is undefined.
95-702 Organizational
Communication Technologies
31
BytesMessage
A stream of uninterpreted bytes. This message type is for literally
encoding a body to match an existing message format.
StreamMessage
A stream of primitive values in the Java programming language, filled
and read sequentially.
ObjectMessage A Serializable object in the Java programming
language.
95-702 Organizational
Communication Technologies
32
On the server
public 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
33
Communication Technologies
}}
The Web Service as an EJB
95-702 Organizational
Communication Technologies
34
From The J2EE Tutorial
95-702 Organizational
Communication Technologies
35
From The J2EE Tutorial
95-702 Organizational
Communication Technologies
36
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, JAXRPC 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
37
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
38
The Web Service Endpoint
Interface
The client cannot
see that it’s interacting
with an EJB
package helloservice;
import java.rmi.RemoteException;
import java.rmi.Remote;
public interface HelloIF extends Remote {
public String sayHello(String name)
throws RemoteException;
}
95-702 Organizational
Communication Technologies
39
The Web Service Session Bean
package helloservice;
import java.rmi.RemoteException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
If we added remote and home
Interfaces then this bean could
also be called using in the traditional
manner – with remote references.
No change to the bean would be
necessary.
public class HelloServiceBean implements SessionBean {
public String sayHello(String name) {
return "Hello " + name + "from HelloServiceEJB";
}
public HelloServiceBean() {}
WSDL can be generated and all
public void ejbCreate() {}
of the previous clients will work.
public void ejbRemove() {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void setSessionContext(SessionContext sc) {}
}
95-702 Organizational
Communication Technologies
40