September 29, 2009COMS W41561 COMS W4156: Advanced Software Engineering Prof. Gail Kaiser
September 29, 2009COMS W41562 Topics covered in this lecture.NET: includes new improved COM+ as EnterpriseServices EJB = Enterprise Java Beans
September 29, 2009COMS W41563.NET
September 29, 2009COMS W41564 What is.NET?.NET An object-oriented software development platform, with –peer to peer multi-language interoperability –common intermediate language (CIL) –common language runtime (CLR) –common data representation based on XML The C# language is the most comfortable for.NET, but not the only one and not mandatory
September 29, 2009COMS W41565 Why do they call it “.NET”? “I don't know what they were thinking. They certainly weren't thinking of people using search tools. It's meaningless marketing nonsense.” [Andy McMullan]Andy McMullan
September 29, 2009COMS W41566 How Does Multi-Language Support Work? A compiler from any supported language compiles an application into CIL (also referred to as MS IL – Microsoft Intermediate Language) The compiler also generates metadata in XML – information on the types and named entities (classes, methods, fields, etc.) defined and used in the applicationXML At runtime, the CIL code is Just-in-Time (JIT) compiled into the target platform’s native code The CLR uses the metadata to perform runtime checks for type-safety and security (“managed code”)
September 29, 2009COMS W41567 Attributes Metadata attributes attach some data to a class or method, which can be accessed via reflection, e.g., [serializable] Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post- processed
September 29, 2009COMS W41568 Common Language Runtime Execution Model CLR VB Source code Compiler C++C# Assembly Operating System Services MSIL Common Language Runtime JIT Compiler Compiler Native code Managed Code Managed Code Managed Code Unmanaged Code CLR Services Ngen
September 29, 2009COMS W41569 What does “managed” mean? Managed code:.NET provides several core run-time services to the programs that run within it, e.g., exception handling and security - for these services to work, the code must provide a minimum level of information to the runtime Managed data: Data that is allocated and freed by the CLR’s garbage collector Managed classes: A C++ class can be marked with the __ gc keyword - then memory for instances of the class are managed by the garbage collector and the class can interoperate with classes written in other CLR languages, e.g., inherit from a VB class (also restrictions, e.g., a managed class can only inherit from one base class)
September 29, 2009COMS W What is an “assembly”? A logical.exe or.dll, can be an application (with a main entry point) or a library Consists of one or more files (dlls, exes, html files, etc.), and represents a group of resources, type definitions, implementations of those types, and references to other assemblies These resources, types and references are described in a block of data called a manifest - part of the assembly, making it self-describing Assemblies often referred to as “components”: CLR in a sense replaces COM
September 29, 2009COMS W Private vs. Shared Assemblies A private assembly is normally used by a single application, and is stored in the application's directory A shared assembly is intended to be used by multiple applications, and is normally stored in the global assembly cache (GAC) but can be stored elsewhere Assemblies find each other (outside the GAC) by searching directory paths
September 29, 2009COMS W Remoting When a client creates an instance of the remote type, the.NET infrastructure creates a proxy object that looks exactly like the remote type to the client. The client calls a method on that proxy, and the remoting system receives the call, routes it to the server process, invokes the server object, and returns the return value to the client proxy - which returns the result to the client.
September 29, 2009COMS W Remoting Send messages along channels, e.g., TCP or HTTP Multiple serialization formats, e.g., SOAP (for HTTP) or binary (for TCP, replacing DCOM) Distributed garbage collection of objects is managed by “leased based lifetime” – when that time expires the object is disconnected from the.NET runtime remoting infrastructure unless in the interim renewed by a successful call from the client to the object (or explicit renewal by client)
September 29, 2009COMS W Remote Invocations SingleCall: Each incoming request from a client is serviced by a new object Singleton: All incoming requests from clients are processed by a single server object Client-activated object: The client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it
September 29, 2009COMS W So Where’s the Component Services?
September 29, 2009COMS W NET Serviced Components Classes in the System.EnterpriseServices namespace wrap COM+ and make it much easier to build COM components COM+ services can be used by.NET components derived from the ServicedComponent class using the System.EnterpriseServices namespace Must be registered with the COM+ catalog Can also use COM+ services outside components
September 29, 2009COMS W Example
September 29, 2009COMS W NET vs. COM+ No IDL (Interface Definition Language) files, the compiler generates the assembly metadata and dependencies are captured during compilation (in manifests) Doesn’t rely on registry, reduces DLL Hell
September 29, 2009COMS W Enterprise Java Beans (EJB)
September 29, 2009COMS W EJBEJB Goals Standard component architecture for building distributed business applications in Java (concerned with server- side, not UI) Interoperability between enterprise beans and other Java Platform Enterprise Edition components, as well as non- Java applications Compatible with other Java APIs and with CORBA protocols Follow the Write Once, Run Anywhere philosophy of Java - an enterprise bean can be developed once and then deployed on multiple platforms without recompilation or source code modification Define the “contracts” that enable tools from multiple vendors to develop and deploy components that can interoperate at runtime
September 29, 2009COMS W Reprise: 3-tiered architecture Client Database Component middleware Application logic components Back-end tier Middle tier Front-end tier LDAPDatabase Client Database Component middleware Application logic components Back-end tier Middle tier Front-end tier LDAPDatabase
September 29, 2009COMS W EJB 3-tiered architecture Client Database Component middleware Application logic components Back-end tier Middle tier Front-end tier LDAPDatabase Application server EJBs
September 29, 2009COMS W Java EE 3-Tier Architecture
September 29, 2009COMS W EJBs as components Enterprise Java Beans are components that provide middle-tier business logic … … and interact heavily with the data layer of the application EJB framework conforms to and at the same time induces a 3-tier architecture for distributed applications
September 29, 2009COMS W EJB as Component Model Framework Programming model Standardized interfaces Runtime environment Built-in component services (persistence, transactions, security, etc.) Meta-data Deployment facilities
September 29, 2009COMS W EJB Specification EJB is an open specification - any vendor can develop a runtime environment that complies with the specification EJB code intended to be portable across brands (assuming uses only services defined by the spec, not additional vendor facilities) EJB specs have been evolving:EJB specs –Originated with IBM 1997 –Later adopted by Sun ( , ) –Enhanced under Java community process ( , , ) EJB 3.0 is a major departure from earlier versions, but backwards compatible (old code works with 3.0 but not vice versa)
September 29, 2009COMS W Enterprise Beans Body of code with fields and methods Encapsulates the business logic or business data of an application Instances are created and managed at runtime by a Container (application server) Client access is mediated by the bean instance’s Container - isolates the bean from direct access by client applications (and other beans)
September 29, 2009COMS W EJB Container Manages every aspect of an enterprise bean at runtime, including access to the bean, and implements component services When a client application invokes a method on an enterprise bean, the container first intercepts the invocation to ensure persistence, transactions and access control are applied properly to every operation a client performs on the bean An enterprise bean cannot function outside of an EJB container
September 29, 2009COMS W EJB Container
September 29, 2009COMS W Resource Management Containers manage many beans simultaneously To reduce memory consumption and processing, containers pool resources When a bean is not being used, a container may place it in a pool to be reused by another client Or evict it from memory (passivate) and only bring it back (activate) when its needed While its reference on the client remains intact When the client invokes a method on the reference, the container re-incarnates the bean to service the request
September 29, 2009COMS W Implementing Enterprise Beans To create an EJB server-side component, an enterprise bean developer provides business interfaces plus the actual bean implementation class The implementation class (bean class) is instantiated at runtime and becomes a distributed object
September 29, 2009COMS W Enterprise Beans as Distributed Objects The business interfaces are types of Java RMI Remote interfaces The java.rmi.Remote interface is used by distributed objects to represent the bean in a different address space (process or machine) An enterprise bean class is instantiated and lives in its container but can be accessed by client applications that live in other address spaces, using skeletons and stubs implemented by the container –When you call an entity bean's method, your program's thread stops executing and control passes over to the server –When the method returns from the server, the local thread resumes executing
September 29, 2009COMS W Stubs and Skeletons
September 29, 2009COMS W Business Data and Methods Entity beans (aka persistence entities) represent persistent business data stored in one row of a database table, and may add behavior specific to that data - but the methods are often just getters, setters and finders Session beans implement business processes and interact with clients Message-driven beans combine features of a session bean and a message listener, allowing a business component to receive messages (and event notifications) asynchronously
September 29, 2009COMS W Business Interfaces A “business interface” is required for both session and message-driven beans (and for entities prior to EJB 3.0) The business interface of a message-driven bean is defined by the messaging type used (typically MessageListener ), not by the developer
September 29, 2009COMS W 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), it is deemed the “business interface” and is by default a local interface unless designated by annotation A bean class may have multiple interfaces, but one or more must be designated as a business interface by either annotation (not both)
September 29, 2009COMS 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); }
September 29, 2009COMS W Remote Interfaces Support remote clients running on a different JVM or machine, to which the bean’s location is transparent To allow remote access, must decorate the business interface with public interface InterfaceName {... } OR decorate the bean class specifying the business public class BeanName implements InterfaceName {... }
September 29, 2009COMS W Local Interfaces To build an enterprise bean that allows only local access, optionally annotate the business interface of the enterprise public interface InterfaceName {... } OR specify the interface by decorating the bean class and specify the interface public class BeanName implements InterfaceName {... }
September 29, 2009COMS W Local Interfaces Client must run in the same JVM as the bean, the location of the bean is not transparent The default: if the bean’s business interface is not decorated and the bean class does not specify the interface the business interface is by default a local interface (prior to EJB 3.0, all enterprise beans were required to implement remote interfaces)
September 29, 2009COMS W 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 s 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
September 29, 2009COMS W 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
September 29, 2009COMS W 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
September 29, 2009COMS W 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
September 29, 2009COMS W 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 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)
September 29, 2009COMS W Session Beans
September 29, 2009COMS W Session Bean Represents a single client (at a time) inside the Application Server Mediates between client and other components of the application Client invokes the session bean’s methods to execute business tasks When the client terminates, the session bean appears to have terminated and is no longer associated with the client
September 29, 2009COMS W Stateful vs. Stateless There are two basic kinds of session bean: Stateless and Stateful Stateful session beans encapsulate business logic and state specific to a client Stateful beans are called "stateful" because they maintain conversational state between method invocations The state is held in instance variables (in memory) and is not persistent across executions The state disappears when the client removes the bean or terminates
September 29, 2009COMS W Stateful Session Beans To conserve resources, stateful session beans may be passivated when not in use by the client Passivation means the bean's conversational-state is written to secondary storage (disk) and the instance is removed from memory If the client removes the bean or terminates, the session ends and the state disappears The client's reference to the bean is not affected by passivation: it remains alive and usable while the bean is passivated When the client invokes a method on a bean that is passivated, the container will activate the bean by instantiating a new instance and populating its conversational- state with the state written to secondary storage
September 29, 2009COMS W Stateless vs. Stateful Stateless session beans are made up of business methods that behave like functions: they operate only on the arguments passed to them when they are invoked (but can lookup state in a database or file) Stateless beans are called "stateless" because they are transient - they do not maintain a conversational state between method invocations The bean’s instance variables may contain a state specific to the client during a single method invocation, but not retained when the method is finished
September 29, 2009COMS W Stateless Session Beans Each invocation of a stateless business method is independent from previous invocations Because stateless session beans are "stateless" they tend to process requests faster and use less resources All instances are equivalent – the EJB container can assign a pooled stateless bean instance to any client, improving scalability
September 29, 2009COMS W 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) Not required to implement any lifecycle methods, but may optionally do so and annotate as such (prior to EJB 3.0, all enterprise beans had to implement a “home” interface with lifecycle methods)
September 29, 2009COMS W Lifecycle Methods The actual methods can have any : The container immediately calls the annotated method after a bean instance is : Designates initialization methods for a stateful session : Called before the container passivates a stateful bean : Called when a re-activated stateful bean instance is : Informs the container to remove the bean instance from the object pool after the method executes (not actually a : Called before the container destroys an unused or expired bean instance from its object pool
September 29, 2009COMS W Lifecycle of a Stateful Session Bean Client initiates the lifecycle by obtaining a reference Container invokes methods, if any Now bean ready for client to invoke business methods
September 29, 2009COMS W Lifecycle of a Stateful Session Bean While in ready state, container may passivate and invoke method, if any If a client then invokes a business method, the container invokes method, if any, and it returns to ready stage
September 29, 2009COMS W Lifecycle of a Stateful Session Bean At the end of the life cycle, the client invokes a method The container calls method, if any
September 29, 2009COMS W Lifecycle of a Stateless Session Bean A client initiates the life cycle by obtaining a reference The container invokes method, if any The bean is now ready to have its business methods invoked by clients
September 29, 2009COMS W 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 method, if any
September 29, 2009COMS W Message-Driven Beans
September 29, 2009COMS W Message-Driven Beans Allows Java EE applications to process messages asynchronously (session beans can only receive synchronous messages) Acts as a JMS (Java Message Service) message listenerJava Message Service 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
September 29, 2009COMS W 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
September 29, 2009COMS W 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
September 29, 2009COMS W 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
September 29, 2009COMS W 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 via Java Naming and Directory Interface (JNDI)Java Naming and Directory Interface
September 29, 2009COMS W JMS API Architecture
September 29, 2009COMS W Messaging Domains Either point-to-point or publish/subscribe JMS API provides common interfaces not specific to either model
September 29, 2009COMS W 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
September 29, 2009COMS W 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
September 29, 2009COMS W 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.
September 29, 2009COMS W 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 normally 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
September 29, 2009COMS W 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
September 29, 2009COMS W Programming Model
September 29, 2009COMS W How are Message-Driven Beans Different from Session Beans? Developer does not define any interfaces, only a bean class that implements the MessageListener interface Otherwise resembles a stateless session bean: –Retains no data or conversational state for a specific client –All instances equivalent, allowing EJB container to assign a message to any bean instance in a pool –Can process messages from multiple clients (one at a time) –Client-independent state can be retained across messages (e.g., JMS API connection, open database connection, object reference to an enterprise bean)
September 29, 2009COMS W Lifecycle of a Message-Driven Bean The container usually creates a pool of message- driven bean instances For each, the container calls method, if any
September 29, 2009COMS W Lifecycle of a Message-Driven Bean A message-driven bean is never passivated, and it has only two states: nonexistent and ready to receive messages At the end of the life cycle, the container calls method, if any
September 29, 2009COMS W Entity Beans
September 29, 2009COMS W Entity Beans Called entity beans = EJB 3.0 Uses the Java Persistence APIJava Persistence API Annotated An entity class represents a table in a relational database An entity instance represents a row in that table
September 29, 2009COMS W Instance Variables Persistent instance variables can only be accessed through the entity class’ methods Must only be serializable types (so they can be stored in a database) Object/relational mapping must be defined An entity may include non-persistent instance variables, annotated
September 29, 2009COMS W Primary Keys Each entity must have a unique object identifier, which may be either simple or composite Simple primary keys Composite primary keys defined by a primary key class, The simple primary key, or each field of a composite primary key, must be a Java primitive type, string or date EntityManager.find method used to look up entities by primary key
September 29, 2009COMS W Queries Other finder methods defined using SQL-like queries in Java Persistence Query LanguageJava Persistence Query Language EntityManager.createQuery method used to create dynamic queries defined within business logic public List findWithName(String name) { return em.createQuery( "SELECT c FROM Customer c WHERE c.name LIKE :custName").setParameter("custName", name).setMaxResults(10).getResultList(); }
September 29, 2009COMS W Queries EntityManager.createNamedQuery method used to create static queries defined in annotation name="findAllCustomersWithName", query="SELECT c FROM Customer c WHERE c.name LIKE :custName" ) customers = em.createNamedQuery("findAllCustomersWithName").setParameter("custName", "Smith").getResultList();
September 29, 2009COMS W Managing Entities Entity Manager represented by javax.persistence.EntityManager instances Associated with a persistence context corresponding to a particular data public EntityManager em; Both Container-Managed Entity Managers (automatic) and Application-Managed Entity Managers
September 29, 2009COMS W Transactions State of persistent entities automatically synchronized to the database when the associated transaction commits But business logic for transactions resides in session or message-driven beans Either container-managed or bean-managed transactions
September 29, 2009COMS W Container-Managed Transactions Container sets the boundaries of transactions, cannot use operations like commit or rollback within code Container begins transaction immediately before enterprise bean method starts and commits just before method exits Decorate entire enterprise bean class or individual business method Transaction types: Required, RequiresNew, Mandatory, NotSupported, Supports, Never
September 29, 2009COMS W Bean-Managed Transactions The code in the session or message-driven bean explicitly marks the boundaries of the transaction Useful for implementing multiple transactions within a single method or transactions than span multiple methods Can use either Java Database Connectivity (JDBC) or the Java Transaction API (JTA)Java Database Connectivity Java Transaction API A JTA transaction can span updates to multiple databases from different vendors managed by the Java Transaction Service, but cannot support nested transactions JTA supplies begin, commit and rollback methods
September 29, 2009COMS W Using Transactions in Session Beans A stateless session bean with bean-managed transactions must commit or rollback before returning A stateful session bean using JTA transactions retains its association with a transaction across multiple client calls, even if the database connection is opened and closed A stateful session bean using JDBC transactions loses its transaction association if the connection is closed
September 29, 2009COMS W Saving a Session Bean’s State in a Database Transactions normally concerned with synchronizing the state of persistent entities to databases Optional for a stateful session bean to receive transaction synchronization notifications to also store its own data in a database Then must implement the SessionSynchronization interface, supplying afterBegin, beforeCompletion and afterCompletion methods
September 29, 2009COMS W Final Notes
September 29, 2009COMS W Next Assignment First Iteration Plan due October 13 thFirst Iteration Plan
September 29, 2009COMS W Upcoming Deadlines Project concept feedback by October 6 th First iteration begins October 6 th First Iteration Plan due October 13 thFirst Iteration Plan First Iteration First Progress Report due October 20 thFirst Progress Report
September 29, 2009COMS W COMS W4156: Advanced Software Engineering Prof. Gail Kaiser