J2EE: Introduction, Practice and Software Architecture. Dr. Gerald Loeffler Java Architect Sun Client Solutions, Sun Microsystems

Size: px
Start display at page:

Download "J2EE: Introduction, Practice and Software Architecture. Dr. Gerald Loeffler Java Architect Sun Client Solutions, Sun Microsystems"

Transcription

1 J2EE: Introduction, Practice and Software Architecture Dr. Gerald Loeffler Java Architect Sun Client Solutions, Sun

2 About this course 1/2 Course material this presentation the Task Tracker example application (!) all software needed by the Task Tracker application (and more) selected J2EE specifications After this course you should understand the "mindset" of J2EE recognise all J2EE concepts fully understand the central concepts of J2EE understand the most important software architectural decisions in building J2EE applications know how to do simple O/R mapping with Hibernate 2

3 About this course be able to develop web/ejb/database applications using a simplified development process understand the basics of inversion of control/dependency injection and Spring s implementation thereof understand how Spring can help in separating and configuring the layers of your software and performing common J2EE tasks 3

4 Table of contents Software architecture and design fundamentals Introduction Inversion of control and dependency injection, Spring Web development with J2EE Enterprise JavaBeans J2EE applications JMS and message-driven beans J2EE component environment and references Transactions Persistence in J2EE applications Epilogue 4

5 Benotung Die Ermittlung der Note für die KV erfolgt auf Basis einer schriftlichen multiple-choice Prüfung: Do. 19. Mai 2005, 13:45-15:15, HS10 oder HS16 Geprüft wird das Verständnis der Konzepte von J2EE und ihrer Zusammenhänge, und nicht ein enzyklopädisches Wissen über Programmierdetails! Sie müssen J2EE-Konzepte benennen und erklären können. Sie müssen nicht die exakten Namen von Java Packages, Classes, Interfaces und Methods von J2EE kennen, aber es ist sehr wohl nötig, über die prinzipielle Existenz und den Nutzen jener Java-Konstrukte Bescheid zu wissen, die in dieser KV eine prominente Rolle einnehmen. 5

6 Das Softwareentwicklungsprojekt 1/3 Ist optional und wird nicht benotet ist aber ein wesentlicher Bestandteil der KV und sollte von allen Teilnehmern durchgeführt werden! Sie können sich hierzu zu Gruppen (optimaler Weise zu 2 Personen) zusammenschließen. Zu entwickeln ist: Asynchroner J2EE Job Scheduler Architektur: Web frontend, EJB layer, DB access mit Hibernate, DB creation scripts (table creation und sample data creation), access control zu web frontend und EJBs Database schema / persistent classes ungefähr wie folgt: JobClass: pk, priority (integer, 1-3), name (low/medium/high) Job: pk, JobClass (foreign key auf JobClass.pk), username, description, input (integer), result (integer) 6

7 Das Softwareentwicklungsprojekt 2/3 Use cases: Submit job: Im web frontend auswählen der JobClass und Eingabe von description und input des Jobs. Aufruf einer session bean durch den Front Controller, die den username des neuen Job auf den momentan eingelogten User setzt und dann den Job via JMS an eine Queue sendet. Message-driven bean horcht an Queue und "arbeitet" Jobs ab, indem sie den Job aus der Message extrahiert, die result-property (mit einem dummy- Wert) füllt, und den resultierenden Job via Hibernate in die Datenbank schreibt. Erfolgs- oder Misserfolgsmeldung im web frontend List processed jobs: Im web frontend wählt man die "List processed jobs"-funktion aus. Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. Anzeige der Jobs und ihrer JobClass im web frontend. 7

8 Das Softwareentwicklungsprojekt 3/3 Deliverables: Use case diagram (auch auf Papier möglich) Domain object model (auch auf Papier möglich) Source code (incl. aller deployment descriptors) J2EE application module (ear-file) Methode des build/package/deploy ist frei und deshalb sind buildscripts (z.b. Ant-scripts) nicht Teil der deliverables 8

9 Literature and References 1/2 Selected J2EE specifications in the course material Java2 Platform Enterprise Edition Specification, v1.4, Sun Java Servlet Specification, Version 2.4, Sun JavaServer Pages Specification, Version2.0, Sun Enterprise JavaBeans Specification, Version 2.1, Sun The J2EE 1.4 Tutorial, Eric Armstrong et al., Sun in the course material Core J2EE Patterns, Deepak Alur et al. EJB Design Patterns, Floyd Marinescu Patterns of Enterprise Application Architecture, Martin Fowler 9

10 Literature and References 2/2 Enterprise JMS Programming, Shaun Terry Hibernate Hibernate in Action, Christian Bauer and Gavin King Hibernate2 Reference Documentation, Version included in the Hibernate distribution, which is in the course material Presentation "Object/Relational Mapping with Hibernate" by Gavin King Spring Spring - java/j2ee Application Framework, Rod Johnson et al. included in the Spring distribution, which is in the course material J2EE without EJB, Rod Johnson with Juergen Hoeller 10

11 Software architecture and design fundamentals 11

12 Layering (in software design) Layering is a means of reducing the complexity (of software) By reducing the dependencies of (software) artefacts Layers are arranged in a stack Each layer depends only on the services offered by the next lower layer(s)...and not on the services offered by layers further down in the stack Every layer is ignorant of all higher layers Layer is a logical concept Tier goes further and includes physical separation

13 Layering in J2EE applications 1/4 Typically, J2EE applications use three layers: Presentation layer (GUI layer) Handles user interaction Rich-client GUI, web-based user interface (Web-UI) Often structured according to MVC (model-view-controller) Business logic layer (domain layer) The heart of the system Business rules, domain logic, validation, computation, workflow decisions Data access layer (DAOs, persistence layer, data source layer, EIS (enterprise information system) access layer) Handles access to and communication with back-end systems such as relational databases (RDBMSs) Object-oriented databases (OODBMSs) Message-oriented middleware (messaging systems) Enterprise resource planning (ERP) systems such as SAP Typically, these back-end systems reside in a separate tier 13

14 Layering in J2EE applications 2/4 The principles of layering imply: The business logic layer and data access layer are independent of the presentation layer The data access layer is independent of the business logic layer Often not strictly the case Typically, classes belonging to different layers reside in different Java packages Here we advocate a software architecture with the following additional characteristics: Business logic layer is sub-divided into Service layer: offers exactly the services needed by the presentation layer and the use cases it implements, often in a procedural way. Only (!) the service layer manages (demarcates) transactions! Domain objects (business objects, domain model), i.e. an objectoriented implementation of domain concepts and their behaviour. Often the domain objects are persistent. 14

15 Layering in J2EE applications 3/4 All layers make use of the business objects, i.e., all layers depend on the business objects. Presentation layer and service layer are strongly correlated (but the service layer is independent of the presentation layer!) and designed around the use cases of the application Often, there is more than one pair of presentation and service layer, because there is more than one category of use cases (actors!) for the interaction with the application: Normal users and the use cases they execute through the normal GUI of the application Admin users and a separate admin GUI for their use cases Monitoring systems and a distinct set of use cases (and technology (JMX)) for the interaction between monitoring systems and the application 15

16 Layering in J2EE applications 4/4 normal user admin user monitoring system presentation layer service layer data/eis access layer domain objects DB SAP Exercise: think of sensible assignments of these layers to tiers! For different types of application: web app, standalone app 16

17 Other basic software design building blocks 1/2 The classical GOF (Gamma et al.) design patterns Singleton: Ensures a class only has one instance, and provide a global point of access to it (Abstract) Factory: Provides an interface for creating families of related objects without specifying their concrete classes Prototype: Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype Facade: Provides a unified interface to a set of interfaces in a subsystem. Defines a higher-level interface that makes the subsystem easier to use. Proxy: Provide a surrogate or placeholder for another object to control access to it... 17

18 Other basic software design building blocks 2/2 Model-View-Controller (MVC) as a general design principle for user interfaces Distributed computing/j2ee/ejb patterns Data Transfer Object: (Plain Java) classes which contain and encapsulate bulk data in one network transportable bundle Domain Data Transfer Object vs. Custom Data Transfer Object Session Facade: Clients should have access only to session beans (and not to entity beans) EJBHomeFactory, BusinessDelegate, Business Interface: see later Very basic OO design principles Encapsulation Separation of concerns... 18

19 Introduction 19

20 Examples of J2EE applications 1/3 Portfolio Management System intranet clients on bank-controlled PCs, globally; Swing frontend one application server per continent IIOP as protocol between clients and servers database (data warehouse) to store portfolio information in mainframes as back-end systems to handle trading (connected via message-oriented middleware (MOM) 20

21 Examples of J2EE applications 2/3 MMS processing system MMS-capable phones as clients mobile network infrastructure translates requests into HTTP load-balanced application servers handle HTTP requests MMS after processing passed on to delivery system 21

22 Examples of J2EE applications 3/3 Mobile work management system PDAs in factory setting as clients, receive work-units and confirm cmpletion; AWT-frontend occasional HTTP-based connection to application server web-application as control station to distribute work to clients SAP back-end defines work-units and is notified of completion database to "buffer" data between application core and SAP 22

23 Levels of J2EE knowledge Don't lose the perspective - differentiate between mastering important concepts and "tool wrestling"! J2EE tool mechanics J2EE software development artifacts J2EE concepts and terminology General (distributed) computing concepts 23

24 J2EE is Java2 Enterprise Edition... a collection of Java technologies to build distributed applications (incl. web applications)... a set of specifications to write applications against (that will run in an application server)... a set of specifications to define the behaviour of application servers and hence to write application servers against... a component technology... an umbrella Java Specification Request (JSR) (for J2EE) and numerous JSRs (for each of the constituing technologies)... very complex if considered in it's entire breadth and depth... not a software product (IDE, server, whatever)... targeted at the same application space as Microsoft's.Net, which uses some of the same architectural concepts 24

25 J2EE 1.4 APIs 1/4 J2SE 1.4 APIs JDBC 3.0 (Java Database Connectivity) for accessing relational (SQL) databases (RDBMSs) Java IDL ((Corba) Interface Definition Language) to implement clients of Corba objects RMI-IIOP ((Java) Remote Method Invocation over (Corba) Internet Inter-Orb Protocol) to implement clients of Corba objects using the RMI API include ubiquitous javax.rmi.portableremoteobject.narrow() method JNDI (Java Naming and Directory Interface) to retrieve "administered objects" from the app server: EJBHome, UserTransaction, JDBC DataSource, JMS ConnectionFactory, JMS Destination, JavaMail Session, URL, "connection" ConnectionFactory, ORB, component environment entries,... 25

26 J2EE 1.4 APIs 2/4 JAXP 1.2 (Java API for XML Processing) for parsing, creating and transforming XML documents includes at least one DOM2 parser, SAX2 parser and XSLT engine JAAS (Java Authentication and Authorization Service) for programmatic extensions of security aspects EJB 2.1 (Enterprise JavaBeans) Servlet 2.4 JSP 2.0 (Java Server Pages) JMS 1.1 (Java Messaging Service) JTA 1.0 (Java Transaction API) to demarcate transaction using UserTransaction object defines interfaces app server - transaction manager - resource manager 26

27 J2EE 1.4 APIs 3/4 JavaMail 1.3 for sending (SMTP) and accessing (POP, IMAP) messages JAF 1.0 used by JavaMail Connector 1.5 (J2EE Connector Architecture) for integrating external enterprise systems and app servers to write clients to external enterprise systems Web Services 1.1 to deploy web service (SOAP) endpoints (servers) JAX-RPC 1.1 (Java API for XML Remote Procedure Calls) to implement web service (SOAP) clients and endpoints (servers) SAAJ 1.2 (SOAP with Attachments API for Java) to manipulate SOAP messages (used by JAX-RPC) 27

28 J2EE 1.4 APIs 4/4 JAXR 1.0 (Java API for XML Registries) to implement clients to UDDI and ebxml registries J2EE Management 1.0 for management tools to interact with app server JMX 1.2 (Java Management Extensions) used by J2EE Management API J2EE Deployment 1.1 for app server providers to implement standardized plugins into deployment tools (IDEs) JACC 1.0 (Java Authorization Service Provider Contract for Containers) defines interface between app server and authorization policy provider 28

29 J2EE component overview Servlet JSP EJB Java class that consumes HTTP request and produces HTTP response front controller in web apps, Gateway to HTTP-based protocols (SOAP) "markup (HTML) file with Java code", compiled to Servlet view in web apps application ("business") logic and/or data Resource adapter ("connector") link between app server and enterprise information system (EIS) (SAP, Siebel, Message Oriented Middleware (MOM), Host,...) Applet, application 29

30 Application server Runtime environment for J2EE components (Logically) made up of containers: web container (hosts Servlets/JSPs) EJB container (hosts EJBs) Provides services to (and encapsulates) components: thread pooling state management security authentication, authorization, access control, encryption transactions...is a web server, Corba server, includes a transaction manager,... -> demo J2EE 1.4 SDK app server admin console 30

31 Software products used in this course Application server: Sun Java System Application Server Platform Edition 8.1 alternatives: BEA WebLogic IBM WebSphere JBoss Writing deployment descriptors, packaging and deployment: text-editor, XML-editor, J2EE 1.4 deploytool, Ant scripts alternatives: Integrated Development Environments (IDEs) such as Sun Java Studio Eclipse Borland JBuilder Writing and compiling Java code: Eclipse, J2SE, Ant alternatives: other IDEs, text-editor 31

32 Examples of J2EE architectures 1/3 Simple web-centric application 32

33 Examples of J2EE architectures 2/3 Web application using EJBs ("3.5 tier"), e.g. Task Tracker 33

34 Examples of J2EE architectures 3/3 Mixed-client (web service, Corba and DB) distributed application 34

35 Interception by the application server / container Request over any protocol Application Server / Container Client Component Response 35

36 J2EE component interplay 36

37 Components, containers, protocols 37

38 Protocols 38

39 Task Tracker the example application Web frontend generated by Servlet, JSPs Business logic encapsulated behind session EJBs Persistent data in PointBase RDBMS (comes with app server) Database access through Hibernate Complete source (and everything else) provided Demo: TaskTracker web GUI 39

40 Task Tracker use cases 40

41 Task Tracker domain object model 41

42 Task Tracker database schema 42

43 Components, modules, deployment descriptors 1/3 43

44 Components, modules, deployment descriptors 2/3 Compononents are collections of Java classes/interfaces: web: Servlet, JSP,... EJB: session bean, message driven bean, entity bean... Modules are jar-files that bundle components and follow a specific layout: EJB module = ejb-jar file (xyz-ejb.jar) DD: ejb-jar.xml (J2EE standard), sun-ejb-jar.xml (app server specific) web app module = war (Web Archive) file (xyz.war)... DD: web.xml (J2EE standard), sun-web.xml (app server specific) J2EE application (= ear (Enterprise Archive) file) is a jar-file that bundles other modules and follows a specific layout DD: application.xml (J2EE standard), sun-application.xml (app server specific) 44

45 Components, modules, deployment descriptors 3/3 Example: Task Tracker modules (war, ejb-jar and ear) and deployment descriptors for each module J2EE SDK deploytool J2EE SDK admin console 45

46 Inversion of control and dependency injection, Spring 46

47 Motivation 1/4 Suppose class A depends on a service S public class A { private S s; public void m() { s.do(); } } public interface S { void do(); } 47

48 Motivation 2/4 Class A might create (instantiate) an implementation of service S itself public class A { private S s = new SImpl(); // } Disadvantage: creates explicit dependency of class A on service implementation SImpl 48

49 Motivation 3/4 Or Class A might delegate the creation of the implementation of service S to a factory public class A { private S s = SFactory.getInstance(); // } Disadvantage: creates explicit dependency of class A on factory SFactory 49

50 Motivation 4/4 Or Class A might expose it s dependency on service S to the outside world and rely on dependency injection to satisfy this dependency public class A { private S s; public A(S s) { this.s = s; } // } This is called (constructor-based) dependency injection or inversion of control (IoC) (because who/what controls the creation of the service implementation is inverted compared to our original example) Disadvantage: requires the existence of an IoC container to satisfy the dependencies But neither A nor C nor CImpl have an explicit dependency on the IoC container! 50

51 Setter base dependency injection With constructor-based dependency injection, constructor arguments might get confusing Setter-based dependency injection uses one JavaBean setter method to inject each dependency: public class A { private S s; public void sets(s s) { this.s = s; } // } 51

52 IoC and J2EE The basic IoC mechanism can be used to great advantage in the J2EE world: Moving JNDI lookups to the IoC container Linking a DataSource to a data access object (DAO) Linking a DAO to a service object Linking a service object to an EJB facade Linking an EJB client to the EJB Examples for each of these points are given in the TaskTracker application and in the rest of this presentation. 52

53 Spring bean factory Provides the basic services of an IoC container (objects are called beans in this context): Bean creation Bean configuration Bean wiring, i.e. setting bean references to create an object graph Bean lookup <bean id= s class= com.xyz.simpl /> <bean id= a class= com.xyz.a > <property name= s > <ref bean= s /> </property> </bean> f = new XmlBeanFactory(new ClassPathResource( xml )); A a = (A) f.getbean( a ); 53

54 Spring and layering in J2EE applications 1/2 Use Spring to define and configure the objects that form the interface of each layer in a J2EE application, using e.g. a separate Spring bean definition file per layer: The DAOs of the data access layer The service objects of the service layer Depend on DAOs, e.g. bean definition file for service layer could import DAO bean definition file The session beans of a session facade layer Depend on service objects, e.g. session facade layer could access beans form bean factory using the service layer bean definition file The actions of the presentation layer Depend on service objects Either, bean definition file for presentation layer defines EJB proxies to access session facade layer Or, bean definition file for presentation layer could import service layer bean definition file (if access is to POJOs of service layer directly) 54

55 Spring and layering in J2EE applications 2/2 controller actions presentation layer session beans session façade layer service objects service layer DAOs data access layer 55

56 Web development with J2EE 56

57 HTTP basics RFC 1945 (HTTP/1.0), RFC 2616 (HTTP/1.1) Request - Response cycle HTTP Request Method: GET, HEAD, POST, PUT, DELETE, OPTIONS, TRACE Request URL Header, body HTTP Response Result code: 404 (not available), 500 (server error) Header, body 57

58 HTTP GET request GET /articles/news/today.asp HTTP/1.1 Accept: */* Accept-Language: en-us Connection: Keep-Alive Host: localhost Referer: User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0) Accept-Encoding: gzip, deflate 58

59 HTTP response HTTP/ OK Date: Wed, 13 Jan :19:42 GMT Server: Apache/1.3.1 (Unix) Connection: close Cache-control: private Content-Type: text/html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> </HTML> 59

60 HTML forms HTTP GET <form action=" method="get"> name=<input type="text" name="name"> age=<input type="text" name="age"> <input type="submit" VALUE="Submit via GET!"> </form> -> 60

61 HTML forms HTTP POST <form action=" method="post"> name=<input type="text" name="name"> age=<input type="text" name="age"> <input type="submit" VALUE="Submit via GET!"> </form> -> 61

62 HttpServlet 1/2 A Java class Managed by servlet container Triggered by HTTP requests arriving at container, produces HTTP response service() dispatches to doget(), dopost(),... HTTP request encapsulated as Java object of type HttpServletRequest headers, parameters (strings), attributes (objects) request URL (see later) output is Java object of type HttpServletResponse that encapsulates the HTTP response content-type, content I.e.: servlets (and JSPs) fully expose the request-response nature of HTTP 62

63 HttpServlet 2/2 A servlet instance's methods may be called from any number of threads simultaneously - be careful (avoid) instance variables. How to use: don't produce (significant) markup from servlet - use JSPs for that servlet acts as Front Controller in web apps: cf. MVC (Model-View-Controller) all HTTP requests arrive at Front Controller decode actions call business logic (i.e. interact with Model) pass model to JSP (the View), via forward/include which produces markup 63

64 Servlet request URL Available from HttpServletRequest Protocol: http Host: Request path: /superapp/buy/confirm Context path: /superapp Servlet path: /buy Path info: /confirm Query string: value=ok 64

65 Servlet (web) sessions Session ties together HTTP requests from one client HttpServletRequest.getSession() of all requests (within a session) returns the same session object call before getting Writer/OutputStream so that a cookie can be set Session identity maintained between requests via cookies (stored on client and sent with requests) via URL rewriting ( must be done explicitly through HttpServlerResponse.encodeURL() Sessions timeout and/or call to invalidate() Objects can be stored in session as named attributes HttpSession.setAttribute(String, Object) and getattribute(string) all attributes should be serilizable! 65

66 Web archive (WAR) 1/2 Packaging and deployment unit of web apps Contains web components (servlets, JSPs) server-side Java classes static web content (HTML, images, ) client-side Java classes (applets, support classes) standard and app-server-specific deployment descriptor (web.xml and sun-web.xml) Packaged as jar with extension war jar cvf example.war. 66

67 Web archive (WAR) 2/2 67

68 Java Server Pages (JSP) basics 1/2 JSPs are "inside-out servlets", which are translated to "real" servlets at runtime or deployment time JSP body becomes service() methods Directives page import="java.util.*, com.sun.*" %> Scriptlets <% for (int i = 0; i < 10; i++) { } %> Expressions <%= book.gettitle() %> JSP elements/tags <jsp:usebean>, <jsp:include> Arbitrary taglib elements/tags (e.g. JSTL) <c:redirect url="/begin.jsp"/> 68

69 Java Server Pages (JSP) basics 2/2 Implicitly available objects: application: javax.servlet.servletcontext (Web Context) config: javax.servlet.servletconfig exception: Throwable (within error pages) out: javax.servlet.jsp.jspwriter request: javax.servlet.servletrequest response: javax.servlet.servletresponse session: javax.servlet.http.httpsession 69

70 Java Standard Tag Library (JSTL) Available from JSP 2.0 (J2EE 1.4) Introduced Expression Language (EL) into JSP Core tags basics, flow control, URL management XML tags Core, flow control, transformation I18N tags Locale, message formatting, number and date formatting Database tags DataSource support, SQL 70

71 Task Tracker web frontend TTFrontController servlet view JSPs web.xml tasktracker.war deploying war to app server via admin console deploytool autodeploy 71

72 Struts Open source, quasi-standard framework for MVC web apps Supports MVC implementation but still exposes HTTP's requestresponse nature very similar in nature to TaskTracker example but ready-to-use implementation of controller (ActionServlet) and a lot of general MVC support struts-config.xml ActionServlet Client ActionMappings Action Model view.jsp 72

73 Security terminology 1/3 Principal the authenticated subject, e.g. a user has name Authentication data e.g. password Authentication the process of proving the identity of a principal matching principal and authentication data against a "store" e.g., entering username/password which is validated Credential encodes to the app server what the user is allowed to do result of (successful) authentication 73

74 Security terminology 2/3 (Security) role a logical concept that is used by a (J2EE) application to group permissions an application's security roles are mapped to users (principals) and groups from the operating environment e.g. tt-admin, tt-user, tt-vip-user Authorization, Access control the process of providing/restricting a principal's access to resources based on the principal's roles Security (policy) domain, realm scope of one security policy Security context used by app server to hold credentials, etc. 74

75 Security terminology 3/3 Group1 User1 User2 Group2 User3 Operating Environment Role1 Permission1 Application Permission2 Role2 75

76 Declarative security for web components 1/2 An application's roles and access controls are declared in the deployment descriptor Protectable resource: URLs Web authentication mechanisms: HTTP basic authentication username/password (base64-encoded) handled by web browser HTTP form-based authentication username/password, but app provides HTML form HTTPS client authentication user needs Public Key Certificate 76

77 Declarative security for web components 2/2 Transport guarantee is the means of specifying encrypted communication (i.e. HTTPS) Security roles are identified in the deployment descriptor (web.xml) and mapped to users/groups from the operating environment in the app-server-specific deployment descriptor (sun-web.xml or sun-application.xml) Example: TaskTracker web.xml, sun-web.xml, sun-application.xml, admin console 77

78 Programmatic security for web components Encoding authorisation requirements in code To be used (only) if declarative security is not enough (too static) API HttpServletRequest getremoteuser(): the login name of the user making the request (if (!) sent with the request) isuserinrole(string rolename) getuserprincipal(): the name of the currently authenticated user (wrapped in a Principal object); null means not logged in Role names used in code are logical role names that can be linked to "real" role names in the deployment descriptor (security-role-ref). 78

79 Enterprise JavaBeans 79

80 Enterprise Java Bean (EJB) principles 1/3 Managed by EJB container in app server (container callbacks!) Clients can be remote (most usual), local or (remote) web service clients Home interface defined by developer to include factory methods (create), a remove-method, finders, etc. methods act on EJBs of one type ("substitute for static methods") remote home interface or local home interface lookup via JNDI (i.e. by name) Component interface defined by developer to include business methods methods act on EJB instance (although, in the case of SLSBs, instances indistinguishable) remote interface or local interface 80

81 Enterprise Java Bean (EJB) principles 2/3 Security and transaction support declarative or programmatic Packaged in ejb-jar file (includes deployment descriptors) Session bean: a component that implements some business logic running on the server stateful ("objects") or stateless ("scoped procedures") remote clients or local clients stateless session beans may also have web service clients executes for one (stateful) or all (stateless) client(s), short-lived 81

82 Enterprise Java Bean (EJB) principles 3/3 Entity bean: a component that represents an object-oriented view of some entities stored in persistent storage (database) remote clients or local clients an object view of persistent data ("one instance represents one record from a table") has primary key shared access from multiple clients, long-lived Message driven bean: a component that implements some asynchronous business logic running on the server asynchronously (!) executes logic on server triggered by arrival of JMS messages no clients (either local, remote or web service) no home and component interface stateless, no identity (similar to SLSB), short-lived 82

83 Remote access to an EJB 83

84 A bit of perspective on EJBs 1/2 It is not complex to write EJBs, but it is definitely more effort than to write plain old Java objects (POJOs) 1 class vs. 1 class + home interface(s) + (business interface(s)) + component interface(s) + deployment descriptors The most common decision to be made is for a web application whether to package business logic in session beans or POJOs EJBs (session beans, in this case) offer over POJOs (when used from the web container): declarative security and transactions (can be changed without touching the code) remote access (important if there is also a non-web client; provides possibility for further load-balancing between web end ejb tiers) formal interface definition and encapsulation it is usually little effort to provide a session facade that hides POJOs which implement the application logic 84

85 A bit of perspective on EJBs 2/2 if there is very little application logic (just database access, as in the TaskTracker application) then database access (properly encapsulated in a database access layer!) could also be done directly from within the action-objects of the web user interface You do not have to use EJBs! 85

86 EJB remote client view and remote clients Applies to session and entity beans but don't use for entity beans for performance reasons Location independence API and semantics of using remote client view is the same whether EJB runs in same JVM as client or in remote JVM Java RMI-based (i.e. (also) Corba/IIOP-based) pass-by-value semantics for arguments and return values (serialization) EJB remote client view defined through: remote home interface remote (component) interface Clients can be non-java (if they speak Corba) but web services are a more widely supported choice as an interface to non-java clients 86

87 EJB local client view and local clients Applies to session and entity beans Client and EJB execute in same JVM no location independence pass-by-reference semantics for arguments and return-values (normal Java method call semantics) avoids overhead of remote call! methods can be more fine-grained than with remote view EJB local client view defined through: local home interface local (component) interface Clients "must" be Java 87

88 EJB web service client view and web service clients Applies only to stateless session beans Exposes the EJB as a web service calls via SOAP over HTTP(S) (replaces IIOP in "normal" remote client view) provides location independence (SOAP calls are remote calls) EJB web service client view defined through: WSDL document (replaces remote (component) interface) Clients can be non-java quickly becoming the best supported cross-platform distributed computing technology Java clients use JAX-RPC to access (any) web service 88

89 Know what you do when using a remote view Applies to remote client view and web service client view Martin Fowler's first law of distributed objects: "Don't distribute your objects" Location independence is beautiful and provides flexibility in deployment but remote calls have high latency (network, network stack, marhsalling/unmarshalling ("copying") of parameters and return values) must therefore be coarse-grained: few remote calls, transporting as much data as is sensible and possible may fail due to network problems, unavailable server, etc. Local EJBs offer mainly "only" (declarative) security and transaction support over normal Java objects The developer decides between remote and/or local client view 89

90 Passivation and activation Applies to stateful session beans and entity beans The app server (ejb container) actively manages memory by serializing/deserializing bean instances to/from disk when required: passivation/activation all fields in an EJB must be serializable, "part of the EJB spec" (or null at the moment of passivation) don't use transient fields ejbpassivate() and ejbactivate() methods called by container immediately before passivation and after activation, respectively ejbpassivate() close any open resources (e.g. DB connections) set all fields to null that are not serializable or "part of the EJB spec" ejbactivate() re-open any resources (e.g. DB connections) re-initialize any null-fields 90

91 Writing a session bean (local/remote client view) 1/4 Decide between stateful vs. stateless stateless session beans may not contain any conversational state in instance variables between method calls (best to avoid any instance variables) any stateless session bean instance may be used to service any client Decide for local and/or remote client view (often just remote) Write home interface(s): EntryServiceRemoteHome, *LocalHome defines create-methods stateless session bean: exactly one method called create() without any arguments stateful session bean: 1 or more methods called create*() with optional arguments return value is matching component interface must throw javax.ejb.createexception 91

92 Writing a session bean (local/remote client view) 2/4 local home interface extends javax.ejb.ejblocalhome, createmethods return local interface remote home interface extends javax.ejb.ejbhome, createmethods throw RemoteException and return remote interface Write business interface(s): EntryServiceRemote, *Local contains only business methods does not extend any EJB interface local and/or remote business interface (differ in RemoteException) Write component interface(s): EntryServiceRemoteComp, *LocalComp local interface extends javax.ejb.ejblocalobject and local business interface remote interface extends javax.ejb.ejbobject and remote business interface is usually empty because all business methods are defined in the business interface 92

93 Writing a session bean (local/remote client view) 3/4 Write bean class: EntryServiceBean implements javax.ejb.sessionbean and business interface(s) public no-arg constructor implement all business methods (from business interface(s)) but don't declare RemoteException in throws clause implement one ejbcreate*() method for each create*() method in the home interface(s): same arguments and throws clause (but without RemoteException) ejbcreate*() return void (while create*() return component interface) implement container (life cycle) callbacks: ejbactivate(), ejbpassivate(); ejbremove() setsessioncontext(sessioncontext) and store passed session context instance variables (fields): statefull session bean: all fields must be serializable, "part of the EJB spec" or set to null in ejbpassivate() stateless session bean: best to not define any fields at all 93

94 Writing a session bean (local/remote client view) 4/4 Write deployment descriptors ejb-jar.xml J2EE standard deployment descriptor which describes all EJBs in an ejb-jar file name, class names of home and component interface and bean class, EJB type (+ stateful/stateless),... sun-ejb-jar.xml app server specific deployment descrptor which provides additional information about EJBs in the ejb-jar file jndi-name,... Package everthing in ejb-jar file Deploy ejb-jar to app server Example: DD, packaging and deployment of tasktracker-ejb.jar 94

95 Ejb jar file 95

96 Session beans, client and container 96

97 Creating a session bean instance 97

98 Removing a session bean instance 98

99 Stateless session bean life cycle 99

100 Stateful session bean life cycle 100

101 Reentrancy with session beans The EJB container serialises calls to each session bean instance each session bean instance sees only a serialized sequence of method calls (and not concurrent execution of its methods from multiple threads) this applies to all methods: business methods and container callbacks session beans do not have to be coded as reentrant If the client of a stateful session bean invokes methods on an instance from several threads concurrently, an exception is thrown to the client 101

102 Using a session bean (local/remote client view) 1/2 1. Lookup home interface through JNDI local home interface is cast directly Context ctx = new InitialContext(); CartLocalHome home = (CartLocalHome) ctx.lookup( java:comp/env/ejb/cart ); remote home interface is "cast" using PortableRemoteObject.narrow() Context ctx = new InitialContext(); CartRemoteHome home = (CartRemoteHome) PortableRemoteObject.narrow(ctx.lookup( java:comp/env/ejb/cart ), CartRemoteHome.class); 2. Create a session bean instance from the home interface CartRemoteComp cart = home.create("gerald", 35); local home interface create-method returns local interface remote home interface create-method returns remote interface and is remote method (may throw RemoteException) 102

103 Using a session bean (local/remote client view) 2/2 3. Call business methods on session bean instance cart.dosomething(); a stateful session bean instance is intended exclusively for the client which created the instance do not share reference to session bean instance call methods only from one thread local interface methods are local calls remote interface methods are remote methods (may throw RemoteException) 4. Remove session bean instance cart.remove(); local interface remove-method is local method remote interface remove-method is remote method (may throw RemoteException) 103

104 EJB home factory JNDI lookup for home interface is expensive because it usually requires a remote call to the JNDI server (which is part of the app server) Remote home interfaces need to be narrow()-ed An EJB Home Factory is a completely re-usable utility class that caches home interfaces and also correctly narrow()s them Home interfaces usually become stale (throw exception upon first usage) if the application server was recycled: need to be re-fetched 104

105 Business delegate Especially during development in a team, it is beneficial to allow client-developers and server-developers to work independently. But if client-developers call EJBs directly, they will depend on these EJBs working correctly. Remote EJB calls may need re-trying to gracefully handle temporary network problems Client-developers may feel uncomfortable using the normal EJB client view. A business delegate is a plain Java object that completely hides the EJB API from client developers and implements re-tries. constructor hides JNDI lookup and create-call methods mirror EJB business methods but without EJB exceptions; may be faked early in the project 105

106 EJB access using Spring Spring provides helper classes for all the common tasks needed to access an EJB: plain JNDI lookup: JndiObjectFactoryBean SimpleRemoteStatelessSessionProxyFactoryBean: combines JNDI lookup, EJB home factory and business delegate for remote statless session beans configurable caching and re-connect behaviour similarly: LocalStatelessSessionProxyFactoryBean Example: Task Tracker spring_webui.xml 106

107 Declarative security for EJBs Protectable resource: calling EJB methods An application's roles and access controls are declared in the deployment descriptor again: roles are a logical concept of the application; all roles must be enumerated in the deployment descriptor permissions (to call EJB methods) are assigned to roles roles are mapped to principals (users) and groups from the operating environment (e.g. in the app server specific deployment descriptor) Example: Task Tracker ejb-jar.xml, sun-application.xml 107

108 Programmatic security for EJBs Encoding authorisation requirements in code To be used (only) if declarative security is not enough (too static) API EJBContext iscallerinrole(string rolename) can be used to code more dynamic security policies than can be expressed (in the deployment descriptor) using declarative security getcallerprincipal() could be used to lookup information in database based on the name of the principal calling the EJB Role names used in code are logical role names that can be linked to "real" role names in the deployment descriptor (security-role-ref). Example: Task Tracker EntryServiceBean.createEntry() 108

109 J2EE applications 109

110 J2EE application review A J2EE application bundles several modules into one ear-file Deployment descritors (application.xml, sun-application.xml) describe the application as a whole and certain properties of each module if you know that modules will be used within an application, then move DD elements into the application DDs to avoid redundancy: context-root for web modules security-role-mapping from role names to users/groups Example: Task Tracker application.xml, sun-application.xml 110

111 J2EE application (ear) deployment descriptor META-INF/application.xml in.ear file 111

112 EAR file 112

113 JMS and message driven beans 113

114 Introduction to JMS 114

115 MOM, JMS and message driven beans overview Message-oriented middleware (MOM) is a class of enterprise software products that facilitates the programmatic exchange of messages this is not messaging is peer-to-peer via MOM possesses typical enterprise features: reliability, transaction support, scalability, security,... Java Messaging Service (JMS) is the Java API to MOM MOM-product is called JMS provider supports queues and topics Every J2EE app server contains a JMS provider (MOM product) A message-driven bean (MDB) is an EJB that consumes messages via JMS 115

116 Messaging Message Producer Sun Java System Message Queue BEA WebLogic JMS IBM WebSphere MQ Fiorano MQ Softwired ibus any J2EE app server + Msg. Acknowledgement + Msg. Persistence + Msg. Selectors Message Consumer 116

117 Publish/subscribe messaging domain Topic Topic Publishers + Durable Subscribers Topic Subscribers 117

118 Point to point messaging domain Queue Queue Senders Queue Receivers 118

119 Messaging and J2EE The application server contains the JMS provider Every component type (with the exception of applets) can produce messages Only application clients and message-driven beans can consume messages! 119

120 Destinations 120

121 Message types + Properties + Format Conversion 121

122 JMS message producer public class HelloQueueSender { public static final String D_NAME = "ex1queue"; public static final String CF_NAME = "QueueConnectionFactory"; } public static void main(string[] args) { try { Context ctx = new InitialContext(); QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup(cf_name); Queue q = (Queue) ctx.lookup(d_name); QueueConnection qc = qcf.createqueueconnection(); try { QueueSession qsess = qc.createqueuesession(false, Session.AUTO_ACKNOWLEDGE); QueueSender qsnd = qsess.createsender(q); TextMessage msg = qsess.createtextmessage("hello JMS World"); qsnd.send(msg); } finally { try {qc.close();} catch (Exception e) {} } } catch (Exception e) { System.out.println("Exception occurred: " + e.tostring()); } } 122

123 JMS message producer using Spring Spring provides helper classes that make sending JMS messages particularly easy plain JNDI lookup: JndiObjectFactoryBean Can be used to look up JMS connection factories and destinations JmsTemplate: handles all resource clean-up (finally blocks) provides convenience methods to send common message types Converts checked JMSException into unchecked JmsException integrates into Spring transaction infrastructure Example: Task Tracker spring_accounting_access.xml and AccountingServiceAOImpl 123

124 JMS message consumer public class HelloQueueReceiverAsynch implements MessageListener { public static final String D_NAME = "ex1queue"; public static final String CF_NAME = "QueueConnectionFactory"; public void onmessage(message message) { try { TextMessage msg = (TextMessage) message; System.out.println("Received: " + msg.gettext()); } catch (Exception e) { System.out.println("Exception occurred: " + e.tostring()); } } } public static void main(string[] args) { try { Context ctx = new InitialContext(); QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup(cf_name); Queue q = (Queue) ctx.lookup(d_name); QueueConnection qc = qcf.createqueueconnection(); QueueSession qsess = qc.createqueuesession(false, Session.AUTO_ACKNOWLEDGE); QueueReceiver qrcv = qsess.createreceiver(q); qrcv.setmessagelistener(new HelloQueueReceiverAsynch()); qc.start(); } catch (Exception e) { System.out.println("Exception occurred: " + e.tostring()); March } 2005 } 124

125 Message driven bean characteristics Asynchronous message consumer from queues and/or topics MDB can also listen on non-jms messages Stateless No home interface or component interface an MDB implements the interface MessageListener which defines one method onmessage(message) Client does not interact directly with MDB client sends message to queue/topic JMS provider delivers message to MDB complete decoupling of client and MDB client does not know of existence of MDB MDB does not know client identity (principal, caller, user, whatever) MDBs are a high-performance EJB type that is known only on the app server 125

126 MDB example public class MessageTraderBean implements MessageDrivenBean, MessageListener { private MessageDrivenContext ctx; } public void ejbcreate() {} public void ejbremove() {} public void setmessagedrivencontext(messagedrivencontext ctx) { this.ctx = ctx; } public void onmessage(message msg) { try { String msgtext = ((TextMessage) msg).gettext(); System.out.println("Message Received: "+ msgtext ); } catch (Exception e) { e.printstacktrace(); } } 126

127 EJB deployment descriptor <ejb-jar> <display-name>hellomdb</display-name> <enterprise-beans> <message-driven> <display-name>hellomdb</display-name> <ejb-name>hellomdb</ejb-name> <ejb-class>com.sun.jmsworkshop.ex1.hellomdb</ejb-class> <transaction-type>container</transaction-type> <message-driven-destination> <destination-type>javax.jms.queue</destination-type> </message-driven-destination> <security-identity> <run-as> <role-name>sepp</role-name> </run-as> </security-identity> </message-driven> </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>hellomdb</ejb-name> <method-name>onmessage</method-name> </method> <trans-attribute>required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar> 127

128 WLS deployment descriptor <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>hellomdb</ejb-name> <jndi-name>hellomdb</jndi-name> <message-driven-descriptor> <destination-jndi-name>ex1queue</destination-jndi-name> <connection-factory-jndi-name>queueconnectionfactory</connection-factory-jndi-name> </message-driven-descriptor> </weblogic-enterprise-bean> </weblogic-ejb-jar> 128

129 Messaging scenario 1: asynch backend connectivity Backend Service SB RequestQ ResultQ ResponseQ Backend Collector MDB Application Server Backend System 129

130 Messaging scenario 2: job scheduling Scheduler SB InputQ ResultQ Executor MDB Application Server 130

131 JMS provider implementation architectures 131

132 JMS and implementations JMS does not define implementation architectures for JMS Provider Different implementations have different characteristics: performance and scalability security reliability The value of some JMS features depends on the implementation architecture of the JMS provider e.g. filters 132

133 Pub/sub often broadcast based Pub/Sub Messaging Reliable Multicast UDP or IP Multicast 133

134 Pub/sub architecture I Connection-Based (TCP/IP, SSL) Broadcast-Based (UDP, IP Multicast) 134

135 Pub/sub architecture II Connection-Based (TCP/IP, SSL) Broadcast-Based (UDP, IP Multicast) 135

136 Pub/sub architecture III Connection-Based (TCP/IP, SSL) Broadcast-Based (UDP, IP Multicast) 136

137 PTP mostly connection based PTP Messaging TCP/IP or SSL 137

138 PTP architecture I Queue Permanent Connection Possibly Transient Connection 138

139 PTP architecture II Queue Queue Queue Queue Queue Permanent Connection Queue Possibly Transient Connection 139

140 JMS details 140

141 Provider model JMS comprises mostly Interfaces Program against JMS Interfaces only Factories return provider implemenations JMS defines API - not transport JMS is Java-only - but MOM product can be x-platform 141

142 Decoupling producer consumer In Space - distributed computing In Platform and Language In Time - asynchronous In Java Object Types (potentially) In TX-context 142

143 Message types TextMessage: string BytesMessage: unaltered, raw bytes ObjectMessage: serializable (Java-only) MapMessage: string->primitive value StreamMessage: ordered primitives Message: empty Message (only props) 143

144 XML messages Do you need it? - JMS is x-platform! (Un)Marshalling costs! Message size! Use TextMessage XML-filters provided by proprietary XMLMessage 144

145 Message properties Are optional name-value pairs name: string value: primitive Java type Not necessarily available outside JMS Filterable Message headers vs. optional properties headers: predefined, dedicated accessors in Message getjmscorrelationid(),... optional properties: type-safe accessors setstringproperty(), getintproperty(),... JMSX-prefix for names reserved Goody: type-conversion of values 145

146 Message selectors A message selector is a filter-expression for messages involving message properties which is evaluated by the JMS provider (either on client- or server-side) SQL where-clause using properties Case-sensitive property names Confirm availability outside JMS! Specify at message consumer creation in Session.createConsumer(), etc. Hope for server-side filtering with Queues and fear client-side filtering with Topics 146

147 Message headers Read-only for client (set-on-call): JMSDestination JMSDeliveryMode ((non-)persistent, see later) JMSExpiration (time-to-live, see later) JMSPriority (just a hint, 0=lowest - 9=highest) JMSMessageID (can be disabled) JMSTimeStamp (can be disabled) JMSRedelivered Writable by client: JMSCorrelationID (refers to earlier JMSMessageID) JMSReplyTo (set to (often temporary) destination for reply) JMSType 147

148 JMS factories ConnectionFactory -> Connection ConnectionFactory.createConnection() QueueConnectionFactory.createQueueConnection() TopicConnectionFactory.createTopicConnection() Connection -> Session Connection.createSession() QueueConnection.createQueueSession() TopicConnection.createTopicSession() Session -> msg producer / consumer Session.createProducer(),.createConsumer() QueueSession.createSender(),.createReceiver() TopicSession.createPublisher(),.createSubscriber(),.createDurableSubscriber() Session -> Message Session.create*Message() 148

149 Connection factory A connection factory is a factory for connections to the JMS provider Is an administered object, i.e. is created administratively in the JMS provider (and not programmatically) lookup via JNDI Encapsulates connection configuration parameters Either QueueConnectionFactory or TopicConnectionFactory, but both can be used via common ConnectionFactory superinterface 149

150 Session A session is used by one thread to produce and consume messages (via producer and consumer objects) not thread-safe A session has only one listener thread! all calls to a session's consumer's onmessage() are serialized Basis for TX Basis for acknowledgement mode Provides recovery via recover() Closing a connection also closes its sessions 150

151 Destination Destination is either Queue or Topics but can be used through common Destination super-interface They are administered objects, i.e. created in the JMS provider through administration and not programmatically lookup through JNDI - don't create dynamically Ignore session's factory methods! Session.createQueue(String queuename) Session.createTopic(String topicname) Temporary destinations valid for connection created via session's factory methods Session.createTemporaryQueue() Session.createTemporaryTopic() mostly used for request-reply helper classes QueueRequestor TopicRequestor 151

152 Message producer Created for destination or "unidentified" (null-destination) unidentified producers must specify destination at send()-time Default delivery properties administered in connection factory Set delivery properties can be disabled through administration for all messages sent through producer delivery mode, expiration (TTL), priority Send message possibly overriding delivery properties Closing a session also closes its message producers 152

153 Non MDB message consumer Created for destination Need to start() connection in order to be able to consume messages sending messages doen't require start() Handle (consume) messages either synchronously using a (blocking) receive() always provide time-out! or asynchronously using a message listener but delivery of the message to the client is always asynchronously! Only one listener per consumer Don't share listeners between sessions! Messages received read-only Closing a session also closes its message consumers 153

154 Durable topic subscriber Bridge topics to queues Provider keeps messages for un-connected durable subscribers in contrast: non-durable topic subscribers receive only those messages that were sent while they were connected Needs ClientID string for connection provide client-specific ConnectionFactory in JMS provider that has the clientid configured in J2EE 1.4 SDK app server: property "ClientId" Special factory method in TopicSession TopicSession.createDurableSubscriber() requires subscription identifier (name) unique within ClientID Needs msg expiration of some sort A real resource hog - use with care! 154

155 Multiple queue receivers on one queue Distribution semantics is not specified by JMS but by JMS provider product: enforce one receiver (prohibit multiple receivers) first-come first-serve round-robin client-fail-over 155

156 Delivery mode: persistent vs. non persistent messages Persistent messages provide reliability in case of provider failure a (successfully) sent message is persisted to "disk" provider needs persistent store configured file, database is the default Trade-off in performance (and space) Ways of setting delivery mode: administratively in ConnectionFactory set value is default for all messages sent via connections derived from the connection factory may suppress over-riding of delivery mode through programmatic means programmatically through MessageProducer.setDeliveryMode() set value is default for all messages sent through this producer programmatically at send()-time 156

157 Message expiry and time to live By default messages don't expire Message expiration enhances application stability especially for messages sent to durable topic subscribers! Ways of setting time-to-live: administratively in ConnectionFactory set value is default for all messages sent via connections derived from the connection factory may suppress over-riding of time-to-live through programmatic means programmatically through MessageProducer.setTimeToLive () set value is default for all messages sent through this producer programmatically at send()-time 157

158 QueueBrowser Peeks at Messages in Queue Created via QueueSession like Consumer May apply Filters Undefined: static vs. dynamic image 158

159 Request/reply and requestor helper classes Implement request/reply paradigm create temporary destination set JMSReplyTo header of a message to this temporary destination send message (consumer sends reply message to this temporary destination) (consumer should set JMSCorrelationID header in reply message to JMSMessageID of request message) "wait" for delivery of reply message QueueRequestor and TopicRequestor do exactly this the only conrete classes in JMS API using blocking receive to wait for reply message limited usefulness deadlocks when used within one TX!! 159

160 MDB subtleties Acknowledgement and TX -> see later MDB instances not reentrant onmessage()-calls serialised for each instance No seriality in message processing whatsoever MDB listens on only one Destination No available Connection or Session No use in throwing RuntimeException from within onmessage() -> see TX discussion Don't use EJBContext.*Caller*() 160

161 Acknowledgement, recovery and transactions in JMS 161

162 Acknowledgement/recovery/transaction decision tree no Use TX? yes Set Ackn Mode, Session.recover() Auto Acknowledge? no Onle one JMS Session involved or outside app server? no yes Transacted Session: Session.commit(), Session.rollback() Message.acknowledge() Distributed TX: Bean-managed (UserTransaction methods) Or Container-managed (EJBContext.setRollbackOnly()) 162

163 Message acknowledgement 1/2 Successful consumption of message takes place in 3 stages: client receives the message client processes the message the message is acknowledged (either by JMS provider or client) Acknowledgement semantics differs between queues and topics: queue: messages that were received by the client but not acknowledged when session is closed are re-delivered to the "next" receiver topic: durable subscribers: as with queue but more well-defined client identity non-durable subscriber: unacknowledged messages are dropped when session is closed 163

164 Message acknowledgement 2/2 Implicit as part of commit() for transacted sessions Governed by acknowledge mode for non-transacted sessions (set at session creation): AUTO_ACKNOWLEDGE automatic acknowledge if no RuntimeException in onmessage() message may still be redelivered if acknowledge itself fails! DUPS_OK_ACKNOWLEDGE like auto-acknowledge but allows for batch ackn of messages (higher performance) causes (more) duplicates if provider fails CLIENT_ACKNOWLEDGE client explicitly needs to call Message.acknowledge() 164

165 Session recovery Stops and restarts session with first unacknowledged message causes re-delivery unacknowledged messages (with the exception of non-durable topic subscribers) Explicit via Session.recover() for non-transacted sessions Implicitly as part of rollback() for transacted sessions 165

166 Transaction with JMS TX Context does not flow with messages separate TX for send and receive of a msg Two approaches (and APIs) to transaction demarcation JMS local transactions (via transacted session) use outside app server JTA distributed transactions use within app server Acknowledgement and recovery of received messages is handled automatically if receive is part of a transaction! 166

167 JMS local transactions via transacted sessions Do no used inside an app server! Acknowledgement mode ignored Atomic unit comprises messages produced and consumed in this Session (since the last commit()) commit() also begins new TX commit(): Ackn of consumed, sending of produced messages rollback(): recovery of consumed, dropping of produced message Need reference to Session in Listener in order to be able to use this form of transactions 167

168 Distributed transactions Mostly (and most easily) used from within app server Needed whenever atomic unit should comprise JMS and e.g. JDBC activity Also for more than one JMS Session Controlled using JTA's UserTransaction, not Session API JMS Session holds XAResource (XASession) Create sessions with connection.createsession(true, 0); 168

169 Transactions with message driven beans Use container-managed TX with tx attribute "required" otherwise TX doesn't include acknowledge! tx attribute only Required and NotSupported Requestors deadlock within one TX! There is no Session available inside an MDB Never use Message.acknowledge() Bean-managed transaction demarcation requires the acknowledge mode to be set: Auto-acknowledge or Dups-ok-acknowledge (and not clientacknowledge) 169

170 EJB deployment descriptor 1 <ejb-jar> <display-name>hellomdb</display-name> <enterprise-beans> <message-driven> <display-name>hellomdb</display-name> <ejb-name>hellomdb</ejb-name> <ejb-class>com.sun.jmsworkshop.ex1.hellomdb</ejb-class> <transaction-type>container</transaction-type> <message-driven-destination> <destination-type>javax.jms.queue</destination-type> </message-driven-destination> <security-identity> <run-as> <role-name>sepp</role-name> </run-as> </security-identity> </message-driven> </enterprise-beans> <assembly-descriptor> <container-transaction> <method> <ejb-name>hellomdb</ejb-name> <method-name>onmessage</method-name> </method> <trans-attribute>required</trans-attribute> </container-transaction> </assembly-descriptor> </ejb-jar> 170

171 EJB deployment descriptor 2 <ejb-jar> <display-name>hellomdb</display-name> <enterprise-beans> <message-driven> <display-name>hellomdb</display-name> <ejb-name>hellomdb</ejb-name> <ejb-class>com.sun.jmsworkshop.ex1.hellomdb</ejb-class> <transaction-type>bean</transaction-type> <acknowledge-mode>dups_ok_acknowledge</acknowledge-mode> <message-driven-destination> <destination-type>javax.jms.queue</destination-type> </message-driven-destination> <security-identity> <run-as> <role-name>sepp</role-name> </run-as> </security-identity> </message-driven> </enterprise-beans> </ejb-jar> 171

172 Acknowledgement/recovery/transaction decision tree no Use TX? yes Set Ackn Mode, Session.recover() Onle one JMS Session involved? no yes Auto Acknowledge? no Transacted Session: Session.commit(), Session.rollback() Message.acknowledge() Distributed TX: Bean-managed (UserTransaction methods) Or Container-managed (EJBContext.setRollbackOnly()) 172

173 Last messages 173

174 Performance tips 1/2 Topics (if broadcast-based) faster and more scalable than Queues (if connection-based) SSL is connection-based (sockets) and outrules broadcasts Beware of durable topic subscribers Turn off what you don't need: generation of timestamps generation of message IDs Be conscious about TX requirements Use distributed TX only if you have to Use JMS-local TX only if you have to Use DUPS_OK_ACKNOWLEDGE and deal with duplicate messages Complete onmessage() quickly at Jax

175 Performance tips 2/2 Beware of message selectors avoid them if evaluated on client (which often is the case for topics (at least if broadcast-based)) Increase parallelism by using more than one session and deal with out-of-order messages and complicated TX handling Use XML messages only where necessary Have a good DBA 175

176 Security considerations 1/2 Authentication for JNDI access security principal and security credentials supplied in constructor for InitialContext Access control for JNDI lookup on per-object basis Other means to get administered objects, bypassing JNDI access control API to create Connection Factories and Destinations re-use objects from other installation Access control on per-destination basis browse/send/receive permissions granted to individual user/groups Message encryption to prevent wire sniffing by all-java application using ObjectMessage and Java Cryptography Extensions (body only) by JMS Provider via SSL, HTTPS, T3S, etc. messaging inside VPN at Jax

177 Security considerations 2/2 Signing Messages to prevent Message Faking Ensures that Message was sent by who claims to have it sent Message is left unaltered, with secure hash appended at Jax

178 JMS is suited to EAI because MOM is mature and x-platform (provides not only a JMS interface) Message format conversion (also custom) No need to run systems within single executable image Systems remain in their native environment (host, Linux, Windows, ) No need to synchronise execution of systems but beware of queue overflow Gerald.Loeffler@sun.com at Jax

179 Task Tracker and messaging TTQ App Server Entry JMS Message Entry JMS Message Entry EntryService Session Bean createentry() EntryReplicator MDB onmessage() 179

180 JMS administered objects in Sun application server 180

181 Creating a JMS connection factory 1. Java Message Service -> Connection Factories 2. -> New: The Create JMS Connection Factory screen appears 3. Enter JNDI Name, e.g. jms/ttqcf 4. Choose javax.jms.queueconnectionfactory from the Type menu 5. Select "Enabled" 6. Click OK 7. Verify in config/domain.xml 181

182 Creating a physical queue 1. Java Message Service -> Physical Destinations 2. -> New: The Create Physical Destination pane appears 3. Enter Physical Destination Name, e.g. TTPhysicalQ 4. Choose queue from the Type menu 5. Click OK 6. Verify in config/domain.xml 182

183 Creating a destination resource 1. Java Message Service -> Destination Resources 2. -> New: The Create JMS Destination Resource pane appears 3. Enter JNDI Name, e.g. jms/ttq 4. Choose javax.jms.queue from the Type menu 5. Select "Enabled" 6. Additional Properties -> Add 7. Enter "Name" in the Name field 8. Enter "TTPhysicalQ" in the Value field 9. Click OK 10.Verify in config/domain.xml 183

184 J2EE component environment and references 184

185 Componentʹs environment entries Defined in component's deployment descriptor <env-entry> <description>my age</description> <env-entry-name>age</env-entry-name> <env-entry-type>java.lang.integer</env-entry-type> <env-entry-value>35</env-entry-value> </env-entry> Accessed by JNDI lookup in "java:comp/env" Context ctx = new InitialContext(); Integer age = (Integer) ctx.lookup( java:comp/env/age ); 185

186 J2EE component and dependencies (references) Component 186

187 Componentʹs EJB references 1/2 To refer to EJB homes using logical names defined by the (using) component Defined in (using) component's deployment descriptor in "ejb" sub-context: <ejb-ref> <ejb-ref-name>ejb/myentryservice</ejb-ref-name> <ejb-ref-type>session</ejb-ref-type> <home>com.sun.tasktracker...entryservicehome</home> <remote>com.sun.tasktracker...entryservice</remote> <ejb-link>entryserviceejb</ejb-link> </ejb-ref> Uses ejb-link in deployment descriptor to resolve EJB reference by stating the ejb-name of the referenced EJB 187

188 Componentʹs EJB references 2/2 Using component uses logical name in JNDI lookup Context ctx = new InitialContext(); Object o = ctx.lookup( "java:comp/env/ejb/myentryservice"); EntryServiceHome home = (EntryServiceHome) PortableRemoteObject.narrow(o, EntryServiceHome.class); Example: TTFrontController, EntryServiceDelegate, web.xml, ejb-jar.xml 188

189 Componentʹs resource manager connection factory references 1/2 E.g. a javax.sql.datasource is a resource manager connection factory for resource manager connections (of type java.sql.connection) to a RDBMS To refer to resource manager connection factories using logical names defined by the (using) component Defined in (using) component's deployment descriptor in subcontext for resource manager type: "jdbc" for JDBC DataSource "jms" for JMS ConnectionFactory "mail" for JavaMail connection factory "url" for URL connection factory Provide authentication data in deployment descriptor (preferred) or Java code 189

190 Componentʹs resource manager connection factory references 2/2 Definition in (using) components deployment descriptor: <resource-ref> <description>bla</description> <res-ref-name>jdbc/thedb</res-ref-name> <res-type>javax.sql.datasource</res-type> <res-auth>container</res-auth> <res-sharing-scope>shareable</res-sharing-scope> </resource-ref> Use LinkRef in deployment descriptor to resolve reference Using component uses its logical name in JNDI lookup and obtains connection from factory Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup( "java:comp/env/jdbc/thedb"); Connection con = ds.getconnection(); 190

191 Componentʹs message destination references 1/2 To refer to JMS Queues and Topics using logical names defined by the (using) component Definition in (using) components deployment descriptor: <message-destination-ref> <description>bla</description> <message-destination-ref-name> jms/stockqeue </message-destination-ref-name> <message-destination-type> javax.jms.queue </message-destination-type> <message-destination-usage> Produces </message-destination-usage> </message-destination-ref> 191

192 Componentʹs message destination references 2/2 Use message-destination-link in deployment descriptor to resolve reference Using component uses its logical name in JNDI lookup Context ctx = new InitialContext(); Queue q = (Queue) ctx.lookup( "java:comp/env/jms/stockqueue"); As an alternative to using this message destination reference mechanism, the resource-env-ref approach works as well: <resource-env-ref> <resource-env-ref-name>jms/myq</resource-env-ref-name> <resource-env-ref-type>javax.jms.queue </resource-env-ref-type> </resource-env-ref> 192

193 Transactions 193

194 Transaction fundamentals 1/4 A transaction is a unit of work that has the ACID properties atomicity:either the complete unit of work is performed or none at all - all or nothing consistency:by executing the unit of work, a system is transferred from one consistent state to another consistent state, irrespective of whether the transaction succeeds or fails isolation:the effects of a transaction are invisible to other transactions as long as the (original) transaction has not succeeded (cf. transaction isolation level) durability: the effect of a transaction is (usually) persistent and survives system failures/shutdowns Local transaction vs. global (distributed) transaction a local transaction involves exactly one transactional resource, e.g. a relational database a distributed transaction involves several transactional resources, e.g. a relational database and a messaging system (JMS provider) 194

195 Transaction fundamentals 2/4 Participants in a distributed transaction: application: uses the facilities of the application server to begin/commit/rollback transactions, which in turn delegates this responsibility to the transaction manager application server: uses a transaction manager (which is usually part of the application server) to coordinate transactions by calling begin(), commit(), etc. on the transaction manager transaction manager: coordinates transactions across several transactional resources by enlisting them and orchestrating a twophase commit protocol among them resource (manager): the resource manager is the entity that interacts with the transaction manager on behalf of a transactional resource, e.g. a RDBMS would be a transactional resource and the JDBC driver would be the resource manager for that resource 195

196 Transaction fundamentals 3/4 The Distributed Transaction Processing (DTP) model of the Open Group (formerly X/Open) defines interfaces between the basic components of a distributed transaction system: TX is the interface that a transaction manager exposes to the application or application server begin(), commit(), rollback() XA is the (bidrectional) interface between a resource manager and a transaction manager e.g. the database and its JDBC driver must implement XA JTA (Java Transaction API) consists of javax.transaction packages builds on X/Open DTP defines the contracts between application, app server, transaction manager and resource manager defines UserTransaction class to be used by J2EE developer 196

197 Transaction fundamentals 4/4 Two-phase commit is the protocol executed by the transaction manager in a distributed transaction to ensure ACID properties e.g. in a successful scenario: 197

198 Transactions in J2EE Distributed transactions must be supported by app server involve multiple transactional resources involve multiple components (in particular EJBs) app server contains transaction manager that coordinates twophase commit across multiple XA-capable resources Transactional resources in J2EE: RDBMS accessed via JDBC connection MOM (message-oriented middleware) accessed via JMS session EIS accessed via resource adapter (connector) Some resources (or their adapters) may not support XA! IIOP transaction propagation protocol currently not required (= transaction managers need not be implemented in terms of JTS) Only flat transactions (no nested transactions) 198

199 A distributed transaction scenario 199

200 Another distributed transaction scenario 200

201 Transaction demarcation in servlets/jsps 1/2 Not recommended (use EJB methods instead) Demarcation with javax.transaction.usertransaction begin(), commit(), rollback() all within one call to service() (TX can not span requests) UserTransaction object retrieved through JNDI-lookup with name "java:comp/usertransaction" Context ctx = new InitialContext(); UserTransaction tx = (UserTransaction) ctx.lookup( "java:comp/usertransaction"); tx.begin(); //... tx.commit(); 201

202 Transaction demarcation in servlets/jsps 2/2 Access multiple resource managers and/or EJBs within one TX TX context propagated automatically EJBs must be deployed in same app server for TX context propagation Servlet/JSP can begin a transaction but not continue it TX context does not flow with HTTP requests but: Invocation with RequestDispatcher also "imports" TX 202

203 Transaction demarcation in EJBs The EJB developer decides whether transaction demarcation (i.e. begin and commit/rollback of transactions) for an EJB is done either programmatically in the EJB's source code (bean-managed transaction demarcation) or by the EJB container according to declarations in the EJB's deployment descriptor (container-managed transaction demarcation) The transactions for an EJB are either completely bean- or container-managed (no mixing) The transaction isolation level must be stated for each resource manager and hence the API is not part of J2EE (except JDBC) usually must set isolation level before transaction begin e.g. using JDBC and bean-managed transactions, use java.sql.connection.settransactionisolation() 203

204 Container managed transaction demarcation 1/2 Deployment descriptor specifies transaction-type "Container" for the EJB Deployment descriptor contains instructions (transaction attributes) to EJB container that state (in essence) if a method requires a transaction or not transaction attribute applies to methods of component interface, i.e. the business methods (exception: entity beans) possible values: NotSupported, Required, Supports, RequiresNew, Mandatory, Never (for some EJBs only sub-set allowed) In the EJB's code, EJBContext.setRollbackOnly() marks the current transaction for rollback (which is initiated by the container after return from the method) if setrollbackonly() is not called, the transaction is commit()-ed all other methods of fiddling with transactions are forbidden! 204

205 Container managed transaction demarcation 2/2 Preferred if possible Entity beans must always use container-managed transactions Example: Task Tracker ejb-jar.xml 205

206 Transaction attributes for container managed tx 206

207 Bean managed transaction demarcation 1/2 Deployment descriptor specifies transaction-type "Bean" for the EJB In the EJB's code, SessionContext.getUserTransaction() or a JNDI-lookup for "java:comp/usertransaction" returns UserTransaction object that must be used by the EJB's methods to demarcate the transaction (using its begin(), commit(), rollback() methods) Java-code (if JNDI-lookup is used) is identical to transaction demarcation in Servlets/JSPs For stateful session beans: a transaction must not be completed in the method invocation that started it, i.e. a transaction may span several method invocations on a stateful session bean stateless session beans and message-driven beans must complete transaction within the method invocation that started it Not an option for entity beans 207

208 Bean managed transaction demarcation 2/2 InitialContext ctx = new InitialContext(); DataSource ds1 = (DataSource) ctx.lookup( "java:comp/env/jdbc/db1"); Connection con1 = ds1.getconnection(); PreparedStatement stmt1 = con1.preparestatement("..."); DataSource ds2 = (DataSource) ctx.lookup( "java:comp/env/jdbc/db2"); Connection con2 = ds2.getconnection(); PreparedStatement stmt2 = con2.createstatement("..."); UserTransaction ut = ejbcontext.getusertransaction(); ut.begin(); stmt1.executeupdate(); stmt2.executeupdate(); ut.commit(); stmt1.close(); stmt2.close(); con1.close(); con2.close(); 208

209 Exceptions thrown from EJB methods 1/3 Application exceptions are all checked exceptions (not a sub-class of RuntimeException) that are not sub-classes of RemoteException are used to report business logic problems, not technical problems the intention of an application exception is to signal to the client that the EJB ran into an expected condition that prevents it from fulfilling the request, e.g. illegal arguments supplied to the EJB method, precondition of calling the EJB method not met e.g. javax.ejb.createexception, javax.ejb.removeexception, com.sun.tasktracker...entryserviceargumentexception can be thrown from any method in home or component interface An application exception thrown from an EJB method does not cause an automatic rollback of a pending transaction: in the EJB method you need to either explicitly rollback transaction (EJBContext.setRollbackOnly()) or make sure that a commit leads to a consistent state of the EJB 209

210 Exceptions thrown from EJB methods 2/3 System exceptions are all sub-classes of RuntimeException including EJBException EJB methods must not throw RemoteException are used to report unexpected problems or problems that the EJB can not recover from e.g., OutOfMemoryError occured in method body, inability to obtain database connection/make JNDI lookup/send JMS message, unexpected RuntimeExceptions occured in method body should be thrown by the EJB method as follows: EJB method bodies should not catch RuntimeException (but pass it through as a system exception) EJB method bodies must catch unrecoverable checked exceptions (e.g. JNDI's NamingException) and throw an EJBException throw EJBException if anything else unrecoverable happens 210

211 Exceptions thrown from EJB methods 3/3 A system exception thrown from an EJB method is caught by the EJB container and causes a rollback of the current transaction (regardless of whether the transaction was started by the container or by the bean (and is not commited or rolled back)) causes the client to receive a RemoteException (for remote clients) or EJBException (for local clients) the EJB instance is not used by the container any more The EJB method does not have to worry about clean-up if it throws a system exception transction is rolled-back (see before) the container releases any resources (DB connections, etc.) that are declared in the EJB's environment (!) 211

212 Persistence in J2EE applications 212

213 Object/relational mapping (ORM) object graph class B { int d; C e; } B2 d e a A1 b c Set C4 class A { int a; B b; Set c; } C2 C3 class C {} 213

214 Object/relational mapping (ORM) relations B pk d e pk A a b C... pk fka

215 ORM of inheritance hierarchies 1/4 Type hierarchy abstract class A { int a1; float a2; } class B extends A { int b1; float b2; } class C extends A { int c1; float c2; } class D extends C { int d1; float d2; } 215

216 ORM of inheritance hierarchies 2/4 One table per type (ʺclassʺ) hierarchy ABCD pk type a1 a2 b1 b2 c1 c2 d1 d2 C B D x x x x x x x x x x x x x x 216

217 ORM of inheritance hierarchies 3/4 One table per type (ʺsub classʺ) A pk C type a1 a2 pk c1 c2 C x x 1 x x B x x 3 x x D x x B pk 2 D b1 b2 pk d1 d2 x x 3 x x 217

218 ORM of inheritance hierarchies 4/4 One table per concrete type (class) B pk a1 a2 b1 b2 2 x x x x C pk 1 a1 a2 c1 c2 x x x x D pk a1 a2 c1 c2 d1 d2 3 x x x x x x 218

219 Entity beans 1/2 Entity beans are a class of EJBs should only have local interfaces (for performance reasons) must use container managed transaction demarcation An entity bean type represents a persistent type, e.g. a table An entity bean instance represents an instance of that persistent type, e.g. a column of that table an entity bean instance has an identiy (primary key) the instance variables of an entity bean typically correspond to the columns in the table Entity beans must implement additional container callbacks that have to do with reading/writing from/to persistent store ejbload(), ejbstore() 219

220 Entity beans 2/2 Two approaches to implementing the database access for an entity bean: bean-managed persistence (BMP) developer of BMP entity bean codes explicit database access (typically using JDBC) in the appropriate methods/callbacks of the entity bean container-managed persistence (CMP) developer uses a ORM tool (the CMP engine) to "generate" the database access code for a CMP entity bean queries are expressed in the EJB query language (EJB QL) in a portable fashion centered around objects (entity beans) not tables CMP is usually preferred over BMP because the performance of the database access code of a good CMP engine is typically much better than that of hand-written JDBC 220

221 Java Data Objects (JDO) Provide programmers with a transparent Java-centric view of persistent information Enables pluggable implementations of datastores into application servers The Java Data Objects architecture defines a standard API to data contained in local storage systems and heterogeneous enterprise information systems, such as ERP, mainframe transaction processing and database systems Typically, JDO is used as the API to access object databases (ODBMSs) and relational databases (RDBMSs, through ORM) JDO is not focused on ORM (as Hibernate is) but can be used as the API to ORM tools JDO is a Java standard (in contrast to Hibernate) the JDO reference implementation is not a useful ORM tool 221

222 Hibernate heavily based on ʺObject/Relational Mapping with Hibernateʺ by Gavin King 222

223 Lightweight ORM solutions Transparent persistence (POJO/JavaBeans) as opposed to entity beans Persistent/transient instances instances of the same class can be either transient or persistent Automatic dirty Cchecking Transitive persistence ( persistence-by-reachability) dependent (child) objects are automatically persisted when parent object (which holds a reference to the child object) is persisted Lazy fetching fetch members of collections when they are needed and not when the parent object (which owns the collection) is read from the database Outer join fetching Runtime SQL generation Three basic inheritance mapping strategies one table per class hierarchy one table per sub-class (one table per concrete class: no polymorphism in collections) 223

224 Why lightweight ORM? Natural programming model Minimize LOC Code can be run and/or tested outside the container Classes may be reused in nonpersistent context Minimize database access with smart fetching strategies Opportunities for aggressive caching Structural mapping more robust when object/data model changes 224

225 Entity beans compared to lightweight ORM Transparent persistence: N/A Persistent/transient instances: no Automatic dirty checking: yes (CMP) Transitive persistence: no Lazy fetching: yes Outer join fetching: to some degree Runtime SQL generation: to some degree Three basic inheritance mapping strategies: N/A Entity beans in EJB 3.0 (J2EE 5.0) will follow a lightweight ORM approach very similar to Hibernate! 225

226 What do RDBMs do well? Work with large amounts of data searching, sorting Work with sets of data joining, aggregating Sharing concurrency (transactions, locking) many applications Integrity constraints transaction isolation 226

227 What do RDBMs do badly? Modeling no polymorphism (inheritance) fine grained models usually result in performance problems Business logic stored procedures should be ruled out unless performance requirements are extremely demanding Distribution Oracle 10g? 227

228 Data is important Even so, the relational model is important precise, well-understood The data will be around much longer than the Java application! 228

229 The goal Take advantage of those things that relational databases do well Without leaving the language of objects / classes Reduce the effort (number of artefacts, lines-of-code) required for accessing RDBMs from Java Improve the performance of DB-access from Java that is achievable under "normal project conditions" 229

230 Hibernate Opensource (LGPL) initiated and led by Gavin King Mature Popular ( downloads/month) Custom API Will be core of JBoss CMP 2.0 engine similarly, Sun's JDO implementation is the core of the CMP engine of Sun's application server 230

231 Hibernate Persistence for JavaBeans Support for very fine-grained, richly typed object models Powerful queries Support for detached persistent objects 231

232 Auction object model and DB schema AUCTION_ITEM item_id desc successful_bid_id BID bid_id amount datetime item_id 232

233 Persistent class Default constructor Get/set pairs Collection property is an interface type Identifier property public class AuctionItem { private Long _id; private Set _bids; private Bid _successfulbid private String _description; } public Long getid() { return _id; } private void setid(long id) { _id = id; } public String getdescription() { return _description; } public void setdescription(string desc) { _description=desc; } 233

234 XML mapping Readable metadata Column / table mappings Surrogate key generation strategy Collection metadata Fetching strategies <class name= AuctionItem table= AUCTION_ITEM > <id name= id column= ITEM_ID > </id> <generator class= native /> <property name= description column= DESC /> <many-to-one name= successfulbid column= SUCCESSFUL_BID_ID /> <set name= bids </set> </class> cascade= all lazy= true > <key column= ITEM_ID /> <one-to-many class= Bid /> 234

235 Dirty checking Retrieve an AuctionItem and change description Session session = sessionfactory.opensession(); Transaction tx = s.begintransaction(); AuctionItem item = (AuctionItem) session.get(auctionitem.class, itemid); item.setdescription(newdescription); tx.commit(); session.close(); 235

236 Transitive persistence Retrieve an AuctionItem and create a new persistent Bid Bid bid = new Bid(); bid.setamount(bidamount); Session session = sf.opensession(); Transaction tx = session.begintransaction(); AuctionItem item = (AuctionItem) session.get(auctionitem.class, itemid); bid.setitem(item); item.getbids().add(bid); tx.commit(); session.close(); 236

237 Detachment Retrieve an AuctionItem, change it outside tx and attach it to new tx (but beware of changing lazily fetched data!) Session session = sf.opensession(); Transaction tx = session.begintransaction(); AuctionItem item = (AuctionItem) session.get(auctionitem.class, itemid); tx.commit(); session.close(); item.setdescription(newdescription); Session session2 = sf.opensession(); Transaction tx = session2.begintransaction(); session2.update(item); tx.commit(); session2.close(); 237

238 Optimizing data access Lazy fetching Eager (outer join) fetching Batch fetching 238

239 Transparent lazy fetching AuctionItem item = (AuctionItem) session.get(auctionitem.class, itemid); SELECT FROM AUCTION_ITEM ITEM WHERE ITEM.ITEM_ID =? Iterator iter = item.getbids().iterator(); SELECT FROM BID BID WHERE BID.ITEM_ID =? item.getsuccessfulbid().getamount(); SELECT FROM BID BID WHERE BID.BID_ID =? 239

240 Eager (outer join) fetching 1/2 <class name= AuctionItem table= AUCTION_ITEM > <id name= id column= ITEM_ID > <generator class= native /> </id> <property name= description column= DESC /> <many-to-one name= successfulbid outer-join= true column= SUCCESSFUL_BID_ID /> <set name= bids cascade= all outer-join= true > <key column= ITEM_ID /> <one-to-many class= Bid /> </set> </class> 240

241 Eager (outer join) fetching 2/2 AuctionItem item = (AuctionItem) s.get(auctionitem.class, itemid); SELECT FROM AUCTION_ITEM ITEM LEFT OUTER JOIN BID BID1 ON BID1.ITEM_ID = ITEM.ITEM_ID LEFT OUTER JOIN BID BID2 ON BID2.BID_ID = ITEM.SUCCESSFUL_BID_ID WHERE ITEM.ITEM_ID =? 241

242 Optimizing data access Minimize row reads use lazy fetching N+1 selects problem (=> too many roundtrips) Minimize database roundtrips use outer join fetching cartesian product problem (=> huge result set) (Much less important) Minimize column reads see later Solution to optimization dilemma are runtime fetch strategies: just say what objects you need and navigate the object graph 242

243 Hibernate query options Hibernate Query Language (HQL) minimal OO dialect of ANSI SQL "SQL formulated in terms of objects and properties instead of tables and columns" a HQL query is a string Criteria queries extensible framework for expressing query criteria as objects includes query by example a Criteria query is an object Native SQL queries as a last resort when a query can not be expressed (in a performant way) otherwise 243

244 Hibernate Query Language (HQL) Make SQL be object oriented classes and properties instead of tables and columns polymorphism associations much less verbose than SQL Full support for relational operations inner/outer/full joins, cartesian products projection (!) aggregation (max, avg) and grouping ordering subqueries SQL function calls HQL is a language for talking about sets of objects It unifies relational operations with object models 244

245 HQL examples 1/5 Simplest HQL Query: from AuctionItem i.e. get all the AuctionItems: List allauctions = session.createquery( from AuctionItem ).list(); 245

246 HQL examples 2/5 More realistic example: select item from AuctionItem item join item.bids bid where item.description like hib% and bid.amount > 100 i.e. get all the AuctionItems with a Bid worth > 100 and description that begins with hib 246

247 HQL examples 3/5 Projection: select item.description, bid.amount from AuctionItem item join item.bids bid where bid.amount > 100 order by bid.amount desc i.e. get the description and amount for all the AuctionItems with a Bid worth >

248 HQL examples 4/5 Aggregation: select max(bid.amount), count(bid) from AuctionItem item left join item.bids bid group by item.type order by max(bid.amount) 248

249 HQL examples 5/5 Runtime fetch strategies: from AuctionItem item left join fetch item.bids join fetch item.successfulbid where item.id = 12 AuctionItem item = session.createquery( ).uniqueresult(); //associations already fetched item.getbids().iterator(); item.getsuccessfulbid().getamount(); 249

250 Criteria query List auctionitems = session.createcriteria(auctionitem.class).setfetchmode( bids, FetchMode.EAGER).add( Expression.like( description, description) ).createcriteria( successfulbid ).add( Expression.gt( amount, minamount) ).list(); Equivalent HQL: from AuctionItem item left join fetch item.bids where item.description like :description and item.successfulbid.amount > :minamount 250

251 Criteria query as ʺquery by exampleʺ AuctionItem item = new AuctionItem(); item.setdescription( hib ); Bid bid = new Bid(); bid.setamount(1.0); List auctionitems = session.createcriteria(auctionitem.class).add( Example.create(item).enableLike(MatchMode.START) ).createcriteria( bids ).add( Example.create(bid) ).list(); Equivalent HQL: from AuctionItem item join item.bids bid where item.description like hib% and bid.amount >

252 Fine grained persistence More classes than tables Fine-grained object models are good greater code reuse more typesafety better encapsulation come naturally with the application of many popular OO patterns Support in Hibernate mainly through components "component" as in "composition" not in the J2EE sense! 252

253 Components Address class street, city, postcode properties STREET, CITY, POST_CODE columns of the PERSON and ORGANIZATION tables Mutable class <class name= Person table= PERSON > <component name= address > <property name= street column= STREET /> <property name= city column= CITY /> <property name= postcode column= POST_CODE /> </component> </class> 253

254 Detached object support 1/5 With detached object support, the objects of persistent classes can be used as Data Transfer Objects (DTOs) classical DTOs are just serializable data holders useless extra LOC not objects (no behavior) parallel class hierarchies usually are bad design no need for classical DTOs with detached object support For applications using servlets + session beans serialize objects to the web tier, then serialize them back to the EJB tier in the next request You don t need to select a row when you only want to update it! Hibernate lets you selectively reassociate a subgraph! (essential for performance) 254

255 Detached object support 2/5 Step 1: Retrieve some objects in a session bean: public List getitems() throws { return getsession().createquery("from AuctionItem item " + "where item.type = :itemtype").setparameter( itemtype, itemtype).list(); } 255

256 Detached object support 3/5 Step 2: Collect user input in a servlet/action: item.setdescription(newdescription); 256

257 Detached object support 4/5 Step 3: Make the changes persistent, back in the session bean: public void updateitem(auctionitem item) throws { } getsession().update(item); 257

258 Detached object support 5/5 Detached objects and transitive persistence: Session session = sf.opensession(); Transaction tx = session.begintransaction(); AuctionItem item = (AuctionItem) session.get(auctionitem.class, itemid); tx.commit(); session.close(); Bid bid = new Bid(); bid.setamount(bidamount); bid.setitem(item); item.getbids().add(bid); Session session2 = sf.opensession(); Transaction tx = session2.begintransaction(); session2.update(item); tx.commit(); session2.close(); 258

259 Detached objects and transitive persistence How do we distinguish between newly instantiated objects and detached objects that are already persistent in the database? version property (if there is one) identifier value e.g. null or unsaved-value= 0 (only works for generated surrogate keys, not for natural keys in legacy data) write your own strategy, implement Interceptor.isUnsaved() 259

260 Using Hibernate in a web component or EJB C.f. Task Tracker hibernate.cfg.xml, spring_dao.xml and e.g. EntryDAOImpl Use the Spring DAO helpers for Hibernate! HibernateDaoSupport correct transaction synchronization and flushing translation of checked HibernateException to unchecked DataAccessException resource clean-up, thread-local Hibernate sessions, and many more Configure Hibernate to get database connections from (XA-capable) DataSource to integrate with JTA with an application server specific (!) class that tells Hibernate how to lookup the JTA TransactionManager Using Hibernate with bean managed transactions use JTA to demarcate transactions as usual 260

261 Using Hibernate in a web component or EJB Using Hibernate with container managed transactions don't demarcate transactions at all and rely on Spring helpers to call Session.flush() where you would normally call commit() may call EJBContext.setRollbackOnly() Doesn t really fit into the data access layer philosophy in which DAOs should be written (hence TaskTracker does not use this approach but rather throws a RuntimeException to trigger a transaction rollback) 261

262 Hibernate tools XDoclet supports Hibernate (in addition to EJBs, etc.) generates mapping files from JavaDoc-like markup in Java source SchemaExport, hbm2ddl generates DDL ("create table") from mapping file appreciates (indeed requires) SQL dialect relies on additional attributes in mapping file (e.g. length, not-null) CodeGenerator, hbm2java generates Java source from mapping file: skeleton implementation of persistent classes MapGenerator, class2hbm generates skeletal (!) mapping files from Java class files 262

263 Persistence J2EE administration details 263

264 Creating a DataSource in Sun app server 1/3 The jar containing the JDBC driver must be on the classpath either: copy jar to domain/lib directory or: add jar to "classpath suffix" in admin console JVM settings PointBase jars (pbclient.jar, pbembedded.jar) are on classpath by default Create a connection pool, e.g. to PointBase embedded for Task Tracker: name: TTDBPool DataSource class name: com.pointbase.xa.xadatasource resource type: user review pool setting turn on connection validation and close connections on failure choose transaction isolation level 264

265 Creating a DataSource in Sun app server 2/3 additional properties: databasename: jdbc:pointbase:embedded:sample;database.home= C:/Sun/AppServer/pointbase/databases User: PBPUBLIC Password: pbpublic Create the DataSource itself ("JDBC resource"): provide JNDI name, e.g. jdbc/ttdb reference the previously created connection pool enable the resource To achieve all configuration changes, add this to domain.xml file for your app server domain (e.g. C:\Sun\AppServer\domains\domain1\config\domain.xml): <jdbc-resource enabled="true" jndiname="jdbc/ttdb" object-type="user" poolname="ttdbpool"/> 265

266 Creating a DataSource in Sun app server 3/3 <jdbc-connection-pool connection-validationmethod="auto-commit" datasourceclassname="com.pointbase.xa.xadatasource" fail-allconnections="true" idle-timeout-in-seconds="300" isconnection-validation-required="true" is-isolationlevel-guaranteed="true" max-pool-size="4" max-wait-timein-millis="60000" name="ttdbpool" pool-resizequantity="1" res-type="javax.sql.xadatasource" steadypool-size="2"> <property name="databasename" value="jdbc:pointbase:embedded:sample;database.home=c:/s un/appserver/pointbase/databases"/> <property name="user" value="pbpublic"/> <property name="password" value="pbpublic"/> </jdbc-connection-pool> <resource-ref enabled="true" ref="jdbc/ttdb"/> 266

267 Hibernate Hibernate needs a read and write PropertyPermission and permission to reflect on and access non-public class members both permissions are usually not granted by default by app servers add the following grant-statement to the app server's policy file (e.g. in C:\Sun\AppServer\domains\domain1\config\server.policy grant { grant { permission java.util.propertypermission "*", "read,write"; permission java.lang.reflect.reflectpermission "suppressaccesschecks ; permission java.lang.runtimepermission "getprotectiondomain"; }; }; 267

268 Epilogue 268

269 Portability of J2EE applications 1/3 Most areas of J2EE are sufficiently standardised so that the Java code of J2EE components need not rely on vendor-specific libraries this means that the Java code (source and bytecode) of J2EE components should be 100% portable notable example: "startup classes", i.e. classes ("components") that are activated at app server startup and deactivated at app server shutdown. Every J2EE module must in reality supply an app server specific deployment descriptor this means that the J2EE modules (in their packaged form, including DDs) will run (deploy) unchanged only on the app server for which app server specific DDs are supplied most app servers are available on several platforms (hardware/os): the J2EE modules will run unchanged on all of them 269

270 Portability of J2EE applications 2/3 Porting a J2EE application from one app server to another app server usually involves the re-writing of the app server specific deployment descriptors Runtime behaviour can vary significantly between app servers, and can to a certain degree be configured in the DDs: thread pool size, timeouts,... clustering capabilities whether several instances of an app server cluster can share the state of HTTP sessions, stateful session beans and/or entity beans how load is distributed over the instances of an app server cluster optimisations local (call-by-reference) optimisation for calls through remote interfaces within same JVM, read-only and read-mostly entity beans 270

271 Portability of J2EE applications 3/3 Services offered by different application servers can vary significantly clustering capabilities access to "user stores" via security realms local to app server: file-based, own DB or LDAP enterprise-wide: Unix passwd, "central" LDAP, Windows domains,... integration with system management tools (e.g. via SNMP) Installation, administration and montoring of application servers is highly product-dependent Deployment of J2EE modules/applications to an app server is highly product dependent and may use command-line tools Ant tasks GUI tools, probably as plug-in to IDE (Integrated Development Env) 271

272 What we didnʹt talk about (in sufficient detail) 1/3 Web components HTTP filters Web event listeners Client-side components Applets (and the applet container) Application clients (and the application client container) Entity Beans Resource adapters ("connectors), J2EE connector architecture and a component's resource environment entries The service providers view (SPIs) of J2EE J2EE platform roles JavaIDL, IIOP and a component's ORB references 272

273 What we didnʹt talk about (in sufficient detail) 2/3 Some J2EE APIs JavaIDL (and IIOP) JavaMail JAXP JAX-RPC SAAJ JAAS J2EE Management, JMX JNDI beyond accessing the app server naming service Advanced security concepts Web services, both from the implementers view (web service view of a stateless session bean) and the client's view (JAX- RPC) 273

274 What we didnʹt talk about (in sufficient detail) 3/3 Additional EJB concepts EJB handle, session bean identity, SessionSynchronization, timer service, run-as identity Packaging of jar-files by reference Automated build/deploy (Ant) Version control (CVS) 274

275 The End Dr. Gerald Loeffler Java Architect Sun Software Services, Sun

276 Sub section heading here 276

Using Message Driven Beans.

Using Message Driven Beans. Using Message Driven Beans Gerald.Loeffler@sun.com Contents JMS - Java Messaging Service EJBs - Enterprise Java Beans MDBs - Message Driven Beans MDB Usage Szenarios 2002-04-22 Gerald.Loeffler@sun.com

More information

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java EJB Enterprise Java EJB Beans ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY Peter R. Egli 1/23 Contents 1. What is a bean? 2. Why EJB? 3. Evolution

More information

Enterprise JavaBeans, Version 3 (EJB3) Programming

Enterprise JavaBeans, Version 3 (EJB3) Programming Enterprise JavaBeans, Version 3 (EJB3) Programming Description Audience This course teaches developers how to write Java Enterprise Edition (JEE) applications that use Enterprise JavaBeans, version 3.

More information

Problems in Scaling an Application Client

Problems in Scaling an Application Client J2EE What now? At this point, you understand how to design servers and how to design clients Where do you draw the line? What are issues in complex enterprise platform? How many servers? How many forms

More information

J2EE Interview Questions

J2EE Interview Questions 1) What is J2EE? J2EE Interview Questions J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces

More information

Deccansoft Software Services. J2EE Syllabus

Deccansoft Software Services. J2EE Syllabus Overview: Java is a language and J2EE is a platform which implements java language. J2EE standard for Java 2 Enterprise Edition. Core Java and advanced java are the standard editions of java whereas J2EE

More information

jar command Java Archive inherits from tar : Tape Archive commands: jar cvf filename jar tvf filename jar xvf filename java jar filename.

jar command Java Archive inherits from tar : Tape Archive commands: jar cvf filename jar tvf filename jar xvf filename java jar filename. jar & jar files jar command Java Archive inherits from tar : Tape Archive commands: jar cvf filename jar tvf filename jar xvf filename java jar filename.jar jar file A JAR file can contain Java class files,

More information

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

Java- EE Web Application Development with Enterprise JavaBeans and Web Services Java- EE Web Application Development with Enterprise JavaBeans and Web Services Duration:60 HOURS Price: INR 8000 SAVE NOW! INR 7000 until December 1, 2011 Students Will Learn How to write Session, Message-Driven

More information

Vision of J2EE. Why J2EE? Need for. J2EE Suite. J2EE Based Distributed Application Architecture Overview. Umair Javed 1

Vision of J2EE. Why J2EE? Need for. J2EE Suite. J2EE Based Distributed Application Architecture Overview. Umair Javed 1 Umair Javed 2004 J2EE Based Distributed Application Architecture Overview Lecture - 2 Distributed Software Systems Development Why J2EE? Vision of J2EE An open standard Umbrella for anything Java-related

More information

Chapter 6 Enterprise Java Beans

Chapter 6 Enterprise Java Beans Chapter 6 Enterprise Java Beans Overview of the EJB Architecture and J2EE platform The new specification of Java EJB 2.1 was released by Sun Microsystems Inc. in 2002. The EJB technology is widely used

More information

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format. J2EE Development Detail: Audience www.peaksolutions.com/ittraining Java developers, web page designers and other professionals that will be designing, developing and implementing web applications using

More information

Java J Course Outline

Java J Course Outline JAVA EE - J2SE - CORE JAVA After all having a lot number of programming languages. Why JAVA; yet another language!!! AND NOW WHY ONLY JAVA??? CHAPTER 1: INTRODUCTION What is Java? History Versioning The

More information

Course Content for Java J2EE

Course Content for Java J2EE CORE JAVA Course Content for Java J2EE After all having a lot number of programming languages. Why JAVA; yet another language!!! AND NOW WHY ONLY JAVA??? PART-1 Basics & Core Components Features and History

More information

Application Servers in E-Commerce Applications

Application Servers in E-Commerce Applications Application Servers in E-Commerce Applications Péter Mileff 1, Károly Nehéz 2 1 PhD student, 2 PhD, Department of Information Engineering, University of Miskolc Abstract Nowadays there is a growing demand

More information

Fast Track to EJB 3.0 and the JPA Using JBoss

Fast Track to EJB 3.0 and the JPA Using JBoss Fast Track to EJB 3.0 and the JPA Using JBoss The Enterprise JavaBeans 3.0 specification is a deep overhaul of the EJB specification that is intended to improve the EJB architecture by reducing its complexity

More information

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve

Introduction. Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve Enterprise Java Introduction Enterprise Java Instructor: Please introduce yourself Name Experience in Java Enterprise Edition Goals you hope to achieve Course Description This course focuses on developing

More information

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP 2013 Empowering Innovation DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP contact@dninfotech.com www.dninfotech.com 1 JAVA 500: Core JAVA Java Programming Overview Applications Compiler Class Libraries

More information

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved.

Borland Application Server Certification. Study Guide. Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved. Borland Application Server Certification Study Guide Version 1.0 Copyright 2001 Borland Software Corporation. All Rights Reserved. Introduction This study guide is designed to walk you through requisite

More information

Oracle 10g: Build J2EE Applications

Oracle 10g: Build J2EE Applications Oracle University Contact Us: (09) 5494 1551 Oracle 10g: Build J2EE Applications Duration: 5 Days What you will learn Leading companies are tackling the complexity of their application and IT environments

More information

Fast Track to Java EE

Fast Track to Java EE Java Enterprise Edition is a powerful platform for building web applications. This platform offers all the advantages of developing in Java plus a comprehensive suite of server-side technologies. This

More information

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA Web Application Development Using JEE, Enterprise Java and JPA Duration: 35 hours Price: $750 Delivery Option: Attend training via an on-demand, self-paced platform paired with personal instructor facilitation.

More information

Enterprise Java Security Fundamentals

Enterprise Java Security Fundamentals Pistoia_ch03.fm Page 55 Tuesday, January 6, 2004 1:56 PM CHAPTER3 Enterprise Java Security Fundamentals THE J2EE platform has achieved remarkable success in meeting enterprise needs, resulting in its widespread

More information

What's New in J2EE 1.4

What's New in J2EE 1.4 What's New in J2EE 1.4 Dave Landers BEA Systems, Inc. dave.landers@4dv.net dave.landers@bea.com Page 1 Agenda Quick Overview of J2EE 1.4 New Kids on the Block New specs and those new to J2EE The Gory Details

More information

UNIT-III EJB APPLICATIONS

UNIT-III EJB APPLICATIONS UNIT-III EJB APPLICATIONS CONTENTS EJB Session Beans EJB entity beans EJB clients EJB Deployment Building an application with EJB. EJB Types Types of Enterprise Beans Session beans: Also called business

More information

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Web Application Development Using JEE, Enterprise JavaBeans and JPA Web Application Development Using JEE, Enterprise Java and JPA Duration: 5 days Price: $2795 *California residents and government employees call for pricing. Discounts: We offer multiple discount options.

More information

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX

Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Introduction to Web Application Development Using JEE, Frameworks, Web Services and AJAX Duration: 5 Days US Price: $2795 UK Price: 1,995 *Prices are subject to VAT CA Price: CDN$3,275 *Prices are subject

More information

Java Enterprise Edition

Java Enterprise Edition Java Enterprise Edition The Big Problem Enterprise Architecture: Critical, large-scale systems Performance Millions of requests per day Concurrency Thousands of users Transactions Large amounts of data

More information

ive JAVA EE C u r r i c u l u m

ive JAVA EE C u r r i c u l u m C u r r i c u l u m ive chnoworld Development Training Consultancy Collection Framework - The Collection Interface(List,Set,Sorted Set). - The Collection Classes. (ArrayList,Linked List,HashSet,TreeSet)

More information

Appendix A - Glossary(of OO software term s)

Appendix A - Glossary(of OO software term s) Appendix A - Glossary(of OO software term s) Abstract Class A class that does not supply an implementation for its entire interface, and so consequently, cannot be instantiated. ActiveX Microsoft s component

More information

index_ qxd 7/18/02 11:48 AM Page 259 Index

index_ qxd 7/18/02 11:48 AM Page 259 Index index_259-265.qxd 7/18/02 11:48 AM Page 259 Index acceptance testing, 222 activity definition, 249 key concept in RUP, 40 Actor artifact analysis and iterative development, 98 described, 97 136 in the

More information

Notes. Submit homework on Blackboard The first homework deadline is the end of Sunday, Feb 11 th. Final slides have 'Spring 2018' in chapter title

Notes. Submit homework on Blackboard The first homework deadline is the end of Sunday, Feb 11 th. Final slides have 'Spring 2018' in chapter title Notes Ask course content questions on Slack (is651-spring-2018.slack.com) Contact me by email to add you to Slack Make sure you checked Additional Links at homework page before you ask In-class discussion

More information

BEAAquaLogic. Service Bus. Interoperability With EJB Transport

BEAAquaLogic. Service Bus. Interoperability With EJB Transport BEAAquaLogic Service Bus Interoperability With EJB Transport Version 3.0 Revised: February 2008 Contents EJB Transport Introduction...........................................................1-1 Invoking

More information

Introduction to Messaging using JMS

Introduction to Messaging using JMS Introduction to Messaging using JMS Evan Mamas emamas@ca.ibm.com IBM Toronto Lab Outline Basic Concepts API Architecture API Programming Model Advanced features Integration with J2EE Simple applications

More information

Asynchrone Kommunikation mit Message Driven Beans

Asynchrone Kommunikation mit Message Driven Beans Asynchrone Kommunikation mit Message Driven Beans Arnold Senn (Technical Consultant) asenn@borland.com Outline Why Messaging Systems? Concepts JMS specification Messaging Modes Messages Implementation

More information

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes

Type of Classes Nested Classes Inner Classes Local and Anonymous Inner Classes Java CORE JAVA Core Java Programing (Course Duration: 40 Hours) Introduction to Java What is Java? Why should we use Java? Java Platform Architecture Java Virtual Machine Java Runtime Environment A Simple

More information

BEAWebLogic. Server. Programming WebLogic Deployment

BEAWebLogic. Server. Programming WebLogic Deployment BEAWebLogic Server Programming WebLogic Deployment Version 10.0 Revised: March 30, 2007 Contents 1. Introduction and Roadmap Document Scope and Audience............................................. 1-1

More information

presentation DAD Distributed Applications Development Cristian Toma

presentation DAD Distributed Applications Development Cristian Toma Lecture 12 S4 - Core Distributed Middleware Programming in JEE Distributed Development of Business Logic Layer presentation DAD Distributed Applications Development Cristian Toma D.I.C.E/D.E.I.C Department

More information

NetBeans IDE Field Guide

NetBeans IDE Field Guide NetBeans IDE Field Guide Copyright 2005 Sun Microsystems, Inc. All rights reserved. Table of Contents Extending Web Applications with Business Logic: Introducing EJB Components...1 EJB Project type Wizards...2

More information

Designing a Distributed System

Designing a Distributed System Introduction Building distributed IT applications involves assembling distributed components and coordinating their behavior to achieve the desired functionality. Specifying, designing, building, and deploying

More information

Introduction to JSP and Servlets Training 5-days

Introduction to JSP and Servlets Training 5-days QWERTYUIOP{ Introduction to JSP and Servlets Training 5-days Introduction to JSP and Servlets training course develops skills in JavaServer Pages, or JSP, which is the standard means of authoring dynamic

More information

<Insert Picture Here> WebLogic JMS Messaging Infrastructure WebLogic Server 11gR1 Labs

<Insert Picture Here> WebLogic JMS Messaging Infrastructure WebLogic Server 11gR1 Labs WebLogic JMS Messaging Infrastructure WebLogic Server 11gR1 Labs Messaging Basics Built-in Best-of-Breed Messaging (JMS) Engine Years of hardening. Strong performance.

More information

Page 1

Page 1 Java 1. Core java a. Core Java Programming Introduction of Java Introduction to Java; features of Java Comparison with C and C++ Download and install JDK/JRE (Environment variables set up) The JDK Directory

More information

Enterprise Java Beans

Enterprise Java Beans Enterprise Java Beans Objectives Three Tiered Architecture Why EJB? What all we should know? EJB Fundamentals 2 Three Tiered Architecture Introduction Distributed three-tier design is needed for Increased

More information

Distributed Systems. Messaging and JMS Distributed Systems 1. Master of Information System Management

Distributed Systems. Messaging and JMS Distributed Systems 1. Master of Information System Management Distributed Systems Messaging and JMS 1 Example scenario Scenario: Store inventory is low This impacts multiple departments Inventory Sends a message to the factory when the inventory level for a product

More information

Index. attributes, visual modeling of, , 565, 566, 567, 568 authentication, Authorization Constraint wizard, , 396

Index. attributes, visual modeling of, , 565, 566, 567, 568 authentication, Authorization Constraint wizard, , 396 A absolute positioning in Swing, 437 acknowledge mode, JMS messages, MDBs, and, 301 action beans, Struts and, 54, 55 Action class, Struts and, 65-68, 66, 67-68 action listeners, 442-443, 443, 448-451,

More information

(9A05803) WEB SERVICES (ELECTIVE - III)

(9A05803) WEB SERVICES (ELECTIVE - III) 1 UNIT III (9A05803) WEB SERVICES (ELECTIVE - III) Web services Architecture: web services architecture and its characteristics, core building blocks of web services, standards and technologies available

More information

Outline. Project Goal. Overview of J2EE. J2EE Architecture. J2EE Container. San H. Aung 26 September, 2003

Outline. Project Goal. Overview of J2EE. J2EE Architecture. J2EE Container. San H. Aung 26 September, 2003 Outline Web-based Distributed EJB BugsTracker www.cs.rit.edu/~sha5239/msproject San H. Aung 26 September, 2003 Project Goal Overview of J2EE Overview of EJBs and its construct Overview of Struts Framework

More information

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently.

Socket attaches to a Ratchet. 2) Bridge Decouple an abstraction from its implementation so that the two can vary independently. Gang of Four Software Design Patterns with examples STRUCTURAL 1) Adapter Convert the interface of a class into another interface clients expect. It lets the classes work together that couldn't otherwise

More information

/ / JAVA TRAINING

/ / JAVA TRAINING www.tekclasses.com +91-8970005497/+91-7411642061 info@tekclasses.com / contact@tekclasses.com JAVA TRAINING If you are looking for JAVA Training, then Tek Classes is the right place to get the knowledge.

More information

Teamcenter Global Services Customization Guide. Publication Number PLM00091 J

Teamcenter Global Services Customization Guide. Publication Number PLM00091 J Teamcenter 10.1 Global Services Customization Guide Publication Number PLM00091 J Proprietary and restricted rights notice This software and related documentation are proprietary to Siemens Product Lifecycle

More information

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies

J2EE - Version: 25. Developing Enterprise Applications with J2EE Enterprise Technologies J2EE - Version: 25 Developing Enterprise Applications with J2EE Enterprise Technologies Developing Enterprise Applications with J2EE Enterprise Technologies J2EE - Version: 25 5 days Course Description:

More information

Exam Actual. Higher Quality. Better Service! QUESTION & ANSWER

Exam Actual. Higher Quality. Better Service! QUESTION & ANSWER Higher Quality Better Service! Exam Actual QUESTION & ANSWER Accurate study guides, High passing rate! Exam Actual provides update free of charge in one year! http://www.examactual.com Exam : 310-090 Title

More information

Java SE7 Fundamentals

Java SE7 Fundamentals Java SE7 Fundamentals Introducing the Java Technology Relating Java with other languages Showing how to download, install, and configure the Java environment on a Windows system. Describing the various

More information

Exam Questions 1Z0-895

Exam Questions 1Z0-895 Exam Questions 1Z0-895 Java Platform, Enterprise Edition 6 Enterprise JavaBeans Developer Certified Expert Exam https://www.2passeasy.com/dumps/1z0-895/ QUESTION NO: 1 A developer needs to deliver a large-scale

More information

Java EE 7: Back-End Server Application Development

Java EE 7: Back-End Server Application Development Oracle University Contact Us: Local: 0845 777 7 711 Intl: +44 845 777 7 711 Java EE 7: Back-End Server Application Development Duration: 5 Days What you will learn The Java EE 7: Back-End Server Application

More information

Advanced Java Programming

Advanced Java Programming Advanced Java Programming Length: 4 days Description: This course presents several advanced topics of the Java programming language, including Servlets, Object Serialization and Enterprise JavaBeans. In

More information

ITdumpsFree. Get free valid exam dumps and pass your exam test with confidence

ITdumpsFree.  Get free valid exam dumps and pass your exam test with confidence ITdumpsFree http://www.itdumpsfree.com Get free valid exam dumps and pass your exam test with confidence Exam : 310-090 Title : Sun Certified Business Component Developer for J2EE 1.3 Vendors : SUN Version

More information

Enterprise JavaBeans (I) K.P. Chow University of Hong Kong

Enterprise JavaBeans (I) K.P. Chow University of Hong Kong Enterprise JavaBeans (I) K.P. Chow University of Hong Kong JavaBeans Components are self contained, reusable software units that can be visually composed into composite components using visual builder

More information

~ Ian Hunneybell: CBSD Revision Notes (07/06/2006) ~

~ Ian Hunneybell: CBSD Revision Notes (07/06/2006) ~ 1 Component: Szyperski s definition of a component: A software component is a unit of composition with contractually specified interfaces and explicit context dependencies only. A software component can

More information

This course is intended for Java programmers who wish to write programs using many of the advanced Java features.

This course is intended for Java programmers who wish to write programs using many of the advanced Java features. COURSE DESCRIPTION: Advanced Java is a comprehensive study of many advanced Java topics. These include assertions, collection classes, searching and sorting, regular expressions, logging, bit manipulation,

More information

Artix for J2EE. Version 4.2, March 2007

Artix for J2EE. Version 4.2, March 2007 Artix for J2EE Version 4.2, March 2007 IONA Technologies PLC and/or its subsidiaries may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject

More information

Enterprise JavaBeans 3.1

Enterprise JavaBeans 3.1 SIXTH EDITION Enterprise JavaBeans 3.1 Andrew Lee Rubinger and Bill Burke O'REILLY* Beijing Cambridge Farnham Kbln Sebastopol Tokyo Table of Contents Preface xv Part I. Why Enterprise JavaBeans? 1. Introduction

More information

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module Java Platform, Enterprise Edition 5 (Java EE 5) Core Java EE Java EE 5 Platform Overview Java EE Platform Distributed Multi tiered Applications Java EE Web & Business Components Java EE Containers services

More information

CO Java EE 7: Back-End Server Application Development

CO Java EE 7: Back-End Server Application Development CO-85116 Java EE 7: Back-End Server Application Development Summary Duration 5 Days Audience Application Developers, Developers, J2EE Developers, Java Developers and System Integrators Level Professional

More information

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java.

[Course Overview] After completing this module you are ready to: Develop Desktop applications, Networking & Multi-threaded programs in java. [Course Overview] The Core Java technologies and application programming interfaces (APIs) are the foundation of the Java Platform, Standard Edition (Java SE). They are used in all classes of Java programming,

More information

"Charting the Course... Mastering EJB 3.0 Applications. Course Summary

Charting the Course... Mastering EJB 3.0 Applications. Course Summary Course Summary Description Our training is technology centric. Although a specific application server product will be used throughout the course, the comprehensive labs and lessons geared towards teaching

More information

J2EE. Enterprise Architecture Styles: Two-Tier Architectures:

J2EE. Enterprise Architecture Styles: Two-Tier Architectures: J2EE J2EE is a unified standard for distributed applications through a component-based application model. It is a specification, not a product. There is a reference implementation available from Sun. We

More information

THIS IS ONLY SAMPLE RESUME - DO NOT COPY AND PASTE INTO YOUR RESUME. WE ARE NOT RESPONSIBLE Name: xxxxxx

THIS IS ONLY SAMPLE RESUME - DO NOT COPY AND PASTE INTO YOUR RESUME. WE ARE NOT RESPONSIBLE Name: xxxxxx Name: xxxxxx Email ID: xxxxxx Ph: xxxxxx Summary: Over 7 years of experience in object oriented programming, design and development of Multi-Tier distributed, Enterprise applications using Java and J2EE

More information

Oracle EXAM - 1Z Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam. Buy Full Product.

Oracle EXAM - 1Z Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam. Buy Full Product. Oracle EXAM - 1Z0-895 Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam Buy Full Product http://www.examskey.com/1z0-895.html Examskey Oracle 1Z0-895 exam demo product is here for you to test

More information

DESIGN PATTERN - INTERVIEW QUESTIONS

DESIGN PATTERN - INTERVIEW QUESTIONS DESIGN PATTERN - INTERVIEW QUESTIONS http://www.tutorialspoint.com/design_pattern/design_pattern_interview_questions.htm Copyright tutorialspoint.com Dear readers, these Design Pattern Interview Questions

More information

Enhydra 6.2 Application Architecture. Tanja Jovanovic

Enhydra 6.2 Application Architecture. Tanja Jovanovic Enhydra 6.2 Application Architecture Tanja Jovanovic Table of Contents 1.Introduction...1 2. The Application Object... 2 3. The Presentation Object... 4 4. Writing Presentation Objects with XMLC... 6 5.

More information

Chapter 10 Web-based Information Systems

Chapter 10 Web-based Information Systems Prof. Dr.-Ing. Stefan Deßloch AG Heterogene Informationssysteme Geb. 36, Raum 329 Tel. 0631/205 3275 dessloch@informatik.uni-kl.de Chapter 10 Web-based Information Systems Role of the WWW for IS Initial

More information

Building the Enterprise

Building the Enterprise Building the Enterprise The Tools of Java Enterprise Edition 2003-2007 DevelopIntelligence LLC Presentation Topics In this presentation, we will discuss: Overview of Java EE Java EE Platform Java EE Development

More information

CMP 436/774. Introduction to Java Enterprise Edition. Java Enterprise Edition

CMP 436/774. Introduction to Java Enterprise Edition. Java Enterprise Edition CMP 436/774 Introduction to Java Enterprise Edition Fall 2013 Department of Mathematics and Computer Science Lehman College, CUNY 1 Java Enterprise Edition Developers today increasingly recognize the need

More information

Erik Dörnenburg JAOO 2003

Erik Dörnenburg JAOO 2003 Persistence Neutrality using the Enterprise Object Broker application service framework Erik Dörnenburg JAOO 2003 Sample project Simple application Heavy client One business entity Basic operations Person

More information

J2EE Packaging and Deployment

J2EE Packaging and Deployment Summary of Contents Introduction 1 Chapter 1: The J2EE Platform 9 Chapter 2: Directory Services and JNDI 39 Chapter 3: Distributed Computing Using RMI 83 Chapter 4 Database Programming with JDBC 157 Chapter

More information

Using JNDI from J2EE components

Using JNDI from J2EE components Using JNDI from J2EE components Stand-alone Java program have to specify the location of the naming server when using JNDI private static InitialContext createinitialcontext() throws NamingException {

More information

Java 2 Platform, Enterprise Edition: Platform and Component Specifications

Java 2 Platform, Enterprise Edition: Platform and Component Specifications Table of Contents Java 2 Platform, Enterprise Edition: Platform and Component Specifications By Bill Shannon, Mark Hapner, Vlada Matena, James Davidson, Eduardo Pelegri-Llopart, Larry Cable, Enterprise

More information

Services Oriented Architecture and the Enterprise Services Bus

Services Oriented Architecture and the Enterprise Services Bus IBM Software Group Services Oriented Architecture and the Enterprise Services Bus The next step to an on demand business Geoff Hambrick Distinguished Engineer, ISSW Enablement Team ghambric@us.ibm.com

More information

Java Training Center, Noida - Java Expert Program

Java Training Center, Noida - Java Expert Program Java Training Center, Noida - Java Expert Program Database Concepts Introduction to Database Limitation of File system Introduction to RDBMS Steps to install MySQL and oracle 10g in windows OS SQL (Structured

More information

User Guide. The mom4j development team

User Guide.  The mom4j development team http://mom4j.sourceforge.net The mom4j development team 01.12.2004 Table of Contents 1. INTRODUCTION...3 2. INSTALLING AND RUNNING MOM4J...3 3. JNDI (JAVA NAMING AND DIRECTORY INTERFACE)...3 4. CONFIGURATION...3

More information

BEAWebLogic Server and WebLogic Express. Programming WebLogic JNDI

BEAWebLogic Server and WebLogic Express. Programming WebLogic JNDI BEAWebLogic Server and WebLogic Express Programming WebLogic JNDI Version 10.0 Document Revised: March 30, 2007 Contents 1. Introduction and Roadmap Document Scope and Audience.............................................

More information

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand)

Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand) Oracle - Developing Applications for the Java EE 7 Platform Ed 1 (Training On Demand) Code: URL: D101074GC10 View Online The Developing Applications for the Java EE 7 Platform training teaches you how

More information

Data Management in Application Servers. Dean Jacobs BEA Systems

Data Management in Application Servers. Dean Jacobs BEA Systems Data Management in Application Servers Dean Jacobs BEA Systems Outline Clustered Application Servers Adding Web Services Java 2 Enterprise Edition (J2EE) The Application Server platform for Java Java Servlets

More information

Installing and Configuring the Runtime Processes 2

Installing and Configuring the Runtime Processes 2 2 Installing and Configuring the Runtime Processes 2 The first step in deploying a J2EE application is setting up the production environment on the appropriate hosts. This involves installing all necessary

More information

Stateless Session Bean

Stateless Session Bean Session Beans As its name implies, a session bean is an interactive bean and its lifetime is during the session with a specific client. It is non-persistent. When a client terminates the session, the bean

More information

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p. Preface p. xiii Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p. 11 Creating the Deployment Descriptor p. 14 Deploying Servlets

More information

Mastering BEA WebLogic Server Best Practices for Building and Deploying J2EE Applications

Mastering BEA WebLogic Server Best Practices for Building and Deploying J2EE Applications Mastering BEA WebLogic Server Best Practices for Building and Deploying J2EE Applications Gregory Nyberg Robert Patrick Paul Bauerschmidt Jeffrey McDaniel Raja Mukherjee Mastering BEA WebLogic Server

More information

JBoss SOAP Web Services User Guide. Version: M5

JBoss SOAP Web Services User Guide. Version: M5 JBoss SOAP Web Services User Guide Version: 3.3.0.M5 1. JBoss SOAP Web Services Runtime and Tools support Overview... 1 1.1. Key Features of JBossWS... 1 2. Creating a Simple Web Service... 3 2.1. Generation...

More information

Java/J2EE Interview Questions(255 Questions)

Java/J2EE Interview Questions(255 Questions) Java/J2EE Interview Questions(255 Questions) We are providing the complete set of Java Interview Questions to the Java/J2EE Developers, which occurs frequently in the interview. Java:- 1)What is static

More information

Fast Track to Java EE 5 with Servlets, JSP & JDBC

Fast Track to Java EE 5 with Servlets, JSP & JDBC Duration: 5 days Description Java Enterprise Edition (Java EE 5) is a powerful platform for building web applications. The Java EE platform offers all the advantages of developing in Java plus a comprehensive

More information

Advanced Topics in Operating Systems

Advanced Topics in Operating Systems Advanced Topics in Operating Systems MSc in Computer Science UNYT-UoG Dr. Marenglen Biba 8-9-10 January 2010 Lesson 10 01: Introduction 02: Architectures 03: Processes 04: Communication 05: Naming 06:

More information

WebSphere Application Server - Overview

WebSphere Application Server - Overview IBM Italia SpA WebSphere Application Server - Overview Marco Dragoni IBM Software Group Technical Sales Specialist IBM Italia S.p.A. Milan, 07 January 2008 2007 IBM Corporation Agenda IBM Value Assessment

More information

Techniques for Building J2EE Applications

Techniques for Building J2EE Applications Techniques for Building J2EE Applications Dave Landers BEA Systems, Inc. dave.landers@4dv.net dave.landers@bea.com Why are we Here? Discuss issues encountered with J2EE Application deployment Based on

More information

1Z Oracle. Java Enterprise Edition 5 Enterprise Architect Certified Master

1Z Oracle. Java Enterprise Edition 5 Enterprise Architect Certified Master Oracle 1Z0-864 Java Enterprise Edition 5 Enterprise Architect Certified Master Download Full Version : http://killexams.com/pass4sure/exam-detail/1z0-864 Answer: A, C QUESTION: 226 Your company is bidding

More information

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline Advanced Java Database Programming JDBC overview SQL- Structured Query Language JDBC Programming Concepts Query Execution Scrollable

More information

OCP JavaEE 6 EJB Developer Study Notes

OCP JavaEE 6 EJB Developer Study Notes OCP JavaEE 6 EJB Developer Study Notes by Ivan A Krizsan Version: April 8, 2012 Copyright 2010-2012 Ivan A Krizsan. All Rights Reserved. 1 Table of Contents Table of Contents... 2 Purpose... 9 Structure...

More information

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1 Introducing Object Oriented Programming... 2 Explaining OOP concepts... 2 Objects...3

More information

DS 2009: middleware. David Evans

DS 2009: middleware. David Evans DS 2009: middleware David Evans de239@cl.cam.ac.uk What is middleware? distributed applications middleware remote calls, method invocations, messages,... OS comms. interface sockets, IP,... layer between

More information

Enterprise Java and Rational Rose -- Part I

Enterprise Java and Rational Rose -- Part I Enterprise Java and Rational Rose -- Part I by Khawar Ahmed Technical Marketing Engineer Rational Software Loïc Julien Software Engineer Rational Software "We believe that the Enterprise JavaBeans component

More information