Presentation is loading. Please wait.

Presentation is loading. Please wait.

95-702 Organizational Communication Technologies 1 Enterprise Java Beans Detail.

Similar presentations


Presentation on theme: "95-702 Organizational Communication Technologies 1 Enterprise Java Beans Detail."— Presentation transcript:

1 95-702 Organizational Communication Technologies 1 Enterprise Java Beans Detail

2 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

3 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

4 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

5 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)

6 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.

7 95-702 Organizational Communication Technologies 7 Entity Bean Life Cycle (From Sun) Does not exist Pool of available instances -- Ready to have business methods called -- Has an identity setEntityContext unsetEntityContext ejbActivate ejbPassivate Client calls create and container calls ejbCreate and ejbPostCreate Client calls remove and container calls ejbRemove Client initiates Container initiates

8 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

9 95-702 Organizational Communication Technologies 9 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; }

10 95-702 Organizational Communication Technologies 10 A Component Interface import javax.ejb.*; // From Eckel import 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; }

11 95-702 Organizational Communication Technologies 11 The Container Implements the component interface (From Eckel)

12 95-702 Organizational Communication Technologies 12 import javax.ejb.CreateException; // From Eckel import 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; }

13 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

14 95-702 Organizational Communication Technologies 14 Deployment Descriptor // From Eckel Movie javatheater.ejb.MovieHome javatheater.ejb.Movie javatheater.ejb.implementation.MovieBean Container java.lang.Integer False 2.x Movie id - title - id

15 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);

16 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(); }

17 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

18 95-702 Organizational Communication Technologies 18 Life Cycle of Stateful Session Bean Does not exist Ready for business methods to be called Passive From Sun Client calls create. Container calls setSessionContext and then calls ejbCreate Container calls ejbPassivate before passivating After activation the container calls ejbActivate Client calls remove, container calls ejbRemove

19 95-702 Organizational Communication Technologies 19 Life Cycle of a Stateless Session Bean (from Sun) Does not exist Ready setSessionContext ejbCreate ejbRemove

20 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

21 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; }

22 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; }

23 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); }

24 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) {} }

25 95-702 Organizational Communication Technologies 25 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);

26 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(); }

27 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)

28 95-702 Organizational Communication Technologies 28 From Sun

29 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");

30 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); }

31 95-702 Organizational Communication Technologies 31 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.

32 95-702 Organizational Communication Technologies 32 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.

33 95-702 Organizational Communication Technologies 33 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(); } }

34 95-702 Organizational Communication Technologies 34 The Web Service as an EJB

35 95-702 Organizational Communication Technologies 35 From The J2EE Tutorial

36 95-702 Organizational Communication Technologies 36 From The J2EE Tutorial

37 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.

38 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

39 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 cannot see that it’s interacting with an EJB

40 95-702 Organizational Communication Technologies 40 The Web Service Session Bean package 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 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. WSDL can be generated and all of the previous clients will work.


Download ppt "95-702 Organizational Communication Technologies 1 Enterprise Java Beans Detail."

Similar presentations


Ads by Google