1 / 80

COMS W4156: Advanced Software Engineering

COMS W4156: Advanced Software Engineering. Prof. Gail Kaiser Kaiser+4156@cs.columbia.edu http://york.cs.columbia.edu/classes/cs4156/. Java EE 3-Tier Architecture. EJB Specification.

Download Presentation

COMS W4156: Advanced Software Engineering

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMS W4156: Advanced Software Engineering Prof. Gail Kaiser Kaiser+4156@cs.columbia.edu http://york.cs.columbia.edu/classes/cs4156/ Kaiser: COMS W4156 Fall 2007

  2. Java EE 3-Tier Architecture Kaiser: COMS W4156 Fall 2007

  3. EJB Specification • EJB is an open specification - any vendor can develop a runtime environment that complies with the specification • EJB specs have been evolving: • Originated with IBM 1997 • Later adopted by Sun (1.0 1998, 1.1 1999) • Enhanced under Java community process (2.0 2001, 2.1 2003, 3.0 2006) • EJB 3.0 is a major departure from earlier versions, but backwards compatible (old code works with 3.0 but not vice versa) • [Last week < 3.0, today = 3.0] Kaiser: COMS W4156 Fall 2007

  4. Enterprise Beans • Encapsulate the business logic of an application • Now just session and message-driven beans; entity beans are persistence entities that use the Java Persistence API • Still deployed in an EJB Container (application server) responsible for transaction management, security authorization, etc. Kaiser: COMS W4156 Fall 2007

  5. Enterprise Bean Class • Now applies to session beans and message-driven beans but not entities • Bean type must be specified using metadata annotations (or old XML deployment descriptors) @Stateful public class ShoppingCartBean implements ShoppingCart { private float total; private Vector productCodes; public int someShoppingMethod(){...}; ... Kaiser: COMS W4156 Fall 2007

  6. Business Interfaces • A business interface is required for both session and message-driven beans, but is now a plain Java interface • The business interface of a message-driven bean is defined by the messaging type used (typically MessageListener), not by the developer Kaiser: COMS W4156 Fall 2007

  7. Multiple Interfaces • If a bean class implements only a single interface (not counting standard interfaces such as java.io.Serializable or any of the javax.ejb interfaces), that is deemed the business interface and is by default a local interface unless designated by a @Remote annotation • A bean class may have multiple interfaces, but one or more must be designated as a business interface by either a @Local or @Remote annotation (not both) Kaiser: COMS W4156 Fall 2007

  8. Example @Stateless @Remote public class CalculatorBean implements Calculator { public float add (int a, int b) { return a + b; } public float subtract (int a, int b) { return a - b; } } public interface Calculator { public float add (int a, int b); public float subtract (int a, int b); } Kaiser: COMS W4156 Fall 2007

  9. Session Bean • Still represents a single client (not shared) inside the Application Server • Client still invokes the session bean’s methods to execute business tasks • Still not persistent (its data is not saved to a database) • When the client terminates, the session bean still appears to have terminated and is no longer associated with the client Kaiser: COMS W4156 Fall 2007

  10. Stateful Session Beans • The instance variables still represent the conversational state of a unique client-bean session • This state is still retained for the duration of the session across multiple method invocations • The state still disappears when the client removes the bean or terminates Kaiser: COMS W4156 Fall 2007

  11. Stateless Session Beans • Still does not maintain a conversational state • The bean’s instance variables may still contain a state specific to the client during a single method invocation, but still not retained when the method is finished • Pooled stateless beans may retain state between invocations, but that state must apply across all clients since all instances of a stateless session bean are still equivalent Kaiser: COMS W4156 Fall 2007

  12. Session Bean Interfaces • A client can access a session bean only through the methods in the bean’s business interface • Can have more than one business interface • A business interface can be either local or remote (or web service) • No longer a separate home interface - now not required to implement any lifecycle methods, but may optionally do so and annotate as such Kaiser: COMS W4156 Fall 2007

  13. Lifecycle Methods • The actual methods can now have any names • @PostConstruct: The container immediately calls the annotated method after a bean instance is instantiated • @PreDestroy: Called before the container destroys an unused or expired bean instance from its object pool • @PrePassivate: Called before the container passivates a stateful bean instance • @PostActivate: Called when a re-activated stateful bean instance is ready • @Init: Designates initialization methods for a stateful session bean; the @PostConstruct method, if any, is called afterwards • @Remove: Informs the container to remove the bean instance from the object pool after the method executes (not actually a callback) Kaiser: COMS W4156 Fall 2007

  14. Lifecycle of a Stateful Session Bean • Client initiates the lifecycle by obtaining a reference • Container performs any dependency injection (resolves annotations) and invokes the @PostConstruct method, if any • Now bean ready for client to invoke business methods Kaiser: COMS W4156 Fall 2007

  15. Lifecycle of a Stateful Session Bean • While in ready state, container may passivate and invoke the @PrePassivate method, if any • If a client then invokes a business method, the container invokes the @PostActivate method, if any, and it returns to ready stage Kaiser: COMS W4156 Fall 2007

  16. Lifecycle of a Stateful Session Bean • At the end of the life cycle, the client invokes a method annotated @Remove • The container calls the @PreDestroy method, if any Kaiser: COMS W4156 Fall 2007

  17. Lifecycle of a Stateless Session Bean • A client initiates the life cycle by obtaining a reference • The container performs any dependency injection and then invokes the @PostConstruct method, if any • The bean is now ready to have its business methods invoked by clients Kaiser: COMS W4156 Fall 2007

  18. Lifecycle of a Stateless Session Bean • Because a stateless session bean is never passivated, its life cycle has only two stages: nonexistent and ready for the invocation of business methods. • At the end of the life cycle, the container calls the @PreDestroy method, if any Kaiser: COMS W4156 Fall 2007

  19. Remote Interfaces • Support remote clients running on a different JVM or machine, to which is the bean’s location is transparent • To allow remote access, must decorate the business interface with the @Remote annotation @Remote public interface InterfaceName { ... } • OR decorate the bean class with @Remote, specifying the business interface(s) @Remote(InterfaceName.class) public class BeanName implements InterfaceName { ... } Kaiser: COMS W4156 Fall 2007

  20. Local Interfaces • Client must run in the same JVM as the bean, the location of the bean is not transparent • Now the default: if the bean’s business interface is not decorated with @Local or @Remote, and the bean class does not specify the interface using @Local or @Remote, the business interface is by default a local interface Kaiser: COMS W4156 Fall 2007

  21. Local Interfaces • To build an enterprise bean that allows only local access, optionally annotate the business interface of the enterprise bean as @Local @Local public interface InterfaceName { ... } • OR specify the interface by decorating the bean class with @Local and specify the interface name @Local(InterfaceName.class) public class BeanName implements InterfaceName { ... } Kaiser: COMS W4156 Fall 2007

  22. Method Parameters and Return Values • The parameters of remote calls are more isolated than those of local calls - the client and bean operate on different copies of a parameter object • If the client changes the value of the object, the value of the copy in the bean does not change • In a local call, both the client and the bean can modify the same parameter object – but should not rely on this side effect of local calls • Because remote calls are likely to be slower than local calls, the parameters in remote methods should be relatively coarse-grained Kaiser: COMS W4156 Fall 2007

  23. Deciding on Local vs. Remote: Coupling • Tightly coupled beans depend on one another • For example, if a session bean that processes sales orders calls a session bean that emails a confirmation message to the customer, these beans are tightly coupled • Tightly coupled beans are good candidates for local access • Because they fit together as a logical unit, they typically call each other often and would benefit from the increased performance that is possible with local access Kaiser: COMS W4156 Fall 2007

  24. Deciding on Local vs. Remote: Type of Client • If an enterprise bean is accessed by application clients, then it should allow remote access • In a production environment, these clients almost always run on different machines than the Application Server • If an enterprise bean’s clients are web components or other enterprise beans, then the type of access depends on how you want to distribute your components Kaiser: COMS W4156 Fall 2007

  25. Deciding on Local vs. Remote: Component Distribution • Java EE applications are scalable because their server-side components can be distributed across multiple machines • In a distributed application, the web components may run on a different server than do the enterprise beans they access • Then the enterprise beans should allow remote access Kaiser: COMS W4156 Fall 2007

  26. Deciding on Local vs. Remote: Performance • Due to factors such as network latency, remote calls may be slower than local calls. • On the other hand, if you distribute components among different servers, you may improve the application’s overall performance • Actual performance can vary in different operational environments Kaiser: COMS W4156 Fall 2007

  27. Deciding on Local vs. Remote • If you aren’t sure which type of access an enterprise bean should have, choose remote access, which gives more flexibility • In the future you can distribute your components to accommodate the growing demands on your application • Although it is uncommon, it is possible for an enterprise bean to allow both remote and local access through different interfaces (the same business interface cannot be both a local and remote business interface) Kaiser: COMS W4156 Fall 2007

  28. Example Stateless Session Bean: Business Interface … @Remote public interface Converter { public BigDecimal dollarToYen(BigDecimal dollars); public BigDecimal yenToEuro(BigDecimal yen); } Kaiser: COMS W4156 Fall 2007

  29. Example Stateless Session Bean: Enterprise Bean Class … @Stateless public class ConverterBean implements Converter { private BigDecimal yenRate = new BigDecimal("115.3100"); private BigDecimal euroRate = new BigDecimal("0.0071"); public BigDecimal dollarToYen(BigDecimal dollars) { BigDecimal result = dollars.multiply(yenRate); return result.setScale(2, BigDecimal.ROUND_UP); } public BigDecimal yenToEuro(BigDecimal yen) { BigDecimal result = yen.multiply(euroRate); return result.setScale(2, BigDecimal.ROUND_UP); } } Kaiser: COMS W4156 Fall 2007

  30. Example Stateless Session Bean: Application Client … public class ConverterClient { @EJB private static Converter converter; public ConverterClient(String[] args) { } public static void main(String[] args) { ConverterClient client = new ConverterClient(args); client.doConversion(); } Kaiser: COMS W4156 Fall 2007

  31. Example Stateless Session Bean: Application Client public void doConversion() { try { BigDecimal param = new BigDecimal("100.00"); BigDecimal yenAmount = converter.dollarToYen(param); System.out.println("$" + param + " is " + yenAmount + " Yen."); BigDecimal euroAmount = converter.yenToEuro(yenAmount); System.out.println(yenAmount + " Yen is " + euroAmount + " Euro."); System.exit(0); } catch (Exception ex) { System.err.println("Caught an unexpected exception!"); ex.printStackTrace(); } } } Kaiser: COMS W4156 Fall 2007

  32. Example Stateful Session Bean: Business Interface … @Remote public interface Cart { public void initialize(String person) throws BookException; public void initialize(String person, String id) throws BookException; public void addBook(String title); public void removeBook(String title) throws BookException; public List<String> getContents(); public void remove(); } Kaiser: COMS W4156 Fall 2007

  33. Example Stateful Session Bean: Enterprise Bean Class … @Stateful public class CartBean implements Cart { String customerName; String customerId; List<String> contents; public void initialize(String person) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; } customerId = "0"; contents = new ArrayList<String>(); } Kaiser: COMS W4156 Fall 2007

  34. Example Stateful Session Bean: Enterprise Bean Class public void initialize(String person, String id) throws BookException { if (person == null) { throw new BookException("Null person not allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new BookException("Invalid id: " + id); } contents = new ArrayList<String>(); } Kaiser: COMS W4156 Fall 2007

  35. Example Stateful Session Bean: Enterprise Bean Class public void addBook(String title) { contents.add(title); } public void removeBook(String title) throws BookException { boolean result = contents.remove(title); if (result == false) { throw new BookException(title + " not in cart."); } } public List<String> getContents() { return contents; } @Remove public void remove() { contents = null; } } Kaiser: COMS W4156 Fall 2007

  36. Message-Driven Beans • Allows Java EE applications to process messages asynchronously (session beans can receive synchronous messages) • Acts as a JMS (Java Message Service) message listener • Messages can be sent by an application client, another enterprise bean, a web component, or a JMS system that does not use Java EE technology Kaiser: COMS W4156 Fall 2007

  37. What is Messaging? • A method of communication between software components or applications • A messaging client can send messages to, and receive messages from, any other client • Each client connects to a messaging agent that provides facilities for creating, sending, receiving and reading messages Kaiser: COMS W4156 Fall 2007

  38. What is Messaging? • Messaging enables distributed communication that is loosely coupled • A component sends a message to a destination, and the recipient retrieves the message from the destination • However, the sender and the receiver do not have to be available at the same time • The sender does not need to know anything about the receiver, nor vice versa • Both only need to know which message format and which destination to use • Differs from tightly coupled technologies, such as Remote Method Invocation (RMI), which require an application to know a remote application’s methods Kaiser: COMS W4156 Fall 2007

  39. JMS API • Common set of interfaces and associated semantics that allow programs written in Java to communicate with other messaging implementations • The JMS API can ensure that a message is delivered once and only once (PERSISTENT) • Lower reliability, at most once (NON_PERSISTENT), is available for applications that can afford to miss messages Kaiser: COMS W4156 Fall 2007

  40. JMS API Architecture • A JMS provider is a messaging system that implements the JMS interfaces and provides administrative and control features (included in Java EE) • JMS clients are the programs or components that produce and consume messages • Messages are the objects that communicate information between JMS clients • Administered objects are preconfigured JMS objects (destinations and connection factories) created by an administrator for the use of clients Kaiser: COMS W4156 Fall 2007

  41. JMS API Architecture Kaiser: COMS W4156 Fall 2007

  42. Messaging Domains • Either point-to-point or publish/subscribe • JMS API provides common interfaces not specific to either domain Kaiser: COMS W4156 Fall 2007

  43. Point-to-Point • Built on the concept of message queues, senders and receivers • Each message is addressed to a specific queue, and receiving clients extract messages from the queues established to hold their messages • Queues retain all messages sent to them until the messages are consumed or until the messages expire Kaiser: COMS W4156 Fall 2007

  44. Point-to-Point • Each message has only one consumer • A sender and a receiver of a message have no timing dependencies - the receiver can fetch the message whether or not it was running when the client sent the message • The receiver acknowledges the successful processing of a message Kaiser: COMS W4156 Fall 2007

  45. Publish/Subscribe • Clients address messages to a topic • Each message can have multiple consumers. • Publishers and subscribers are anonymous and can dynamically publish or subscribe to the content hierarchy • The system distributes the messages arriving from a topic’s multiple publishers to its multiple subscribers • Topics retain messages only as long as it takes to distribute them to current subscribers. Kaiser: COMS W4156 Fall 2007

  46. Publish/Subscribe • Publishers and subscribers have a timing dependency – a client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages • JMS relaxes this timing dependency by allowing durable subscriptions, which receive messages sent while the subscribers are not active Kaiser: COMS W4156 Fall 2007

  47. Message Consumption • Synchronous: A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method - the receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit • Asynchronous: A client can register a message listener with a consumer - Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage method, which acts on the contents of the message Kaiser: COMS W4156 Fall 2007

  48. Programming Model Kaiser: COMS W4156 Fall 2007

  49. Connection Factory • The object a client uses to create a connection to a provider • Encapsulates a set of configuration parameters defined by an administrator • At the beginning of a JMS client program, you inject a connection factory resource into a ConnectionFactory object @Resource(mappedName="jms/ConnectionFactory") private static ConnectionFactory connectionFactory; Kaiser: COMS W4156 Fall 2007

  50. Destination • The object a client uses to specify the target of messages it produces and the source of messages it consumes • In PTP, destinations are called queues • In pub/sub, destinations are called topics • To create a destination using the Application Server, create a JMS destination resource that specifies a JNDI name for the destination @Resource(mappedName="jms/Queue") private static Queue queue; @Resource(mappedName="jms/Topic") private static Topic topic; Kaiser: COMS W4156 Fall 2007

More Related