j2ee introduction and practice...march 2004 j2ee - introduction and practice, gerald loeffler, sun...

256
J2EE: Introduction and Practice Dr. Gerald Loeffler Java Architect Sun Software Services, Sun Microsystems

Upload: others

Post on 16-Feb-2021

3 views

Category:

Documents


0 download

TRANSCRIPT

  • J2EE: Introduction and Practice

    Dr. Gerald LoefflerJava ArchitectSun Software Services, Sun Microsystems

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    2

    About this course

    • Course materialhttp://www.ssw.uni-linz.ac.at/Teaching/Lectures/SpezialLVA/Loeffler

    – 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– be able to develop web/EJB/database applications using a

    simplified development process

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    3

    Benotung 1/2

    • Die Ermittlung der Note für die KV erfolgt auf Basis einer mündlichen Prüfung und eines optionalen Softwareentwicklungsprojektes.– Wird nur die mündliche Prüfung abgelegt, so wird die Note für die

    KV auf Basis dieser Prüfung im Bereich 2-5 vergeben.– Wird zusätzlich das Ergebnis des Softwareentwicklungsprojektes

    im Rahmen der mündlichen Prüfung demonstriert, dann verbessert sich die Gesamtnote für die KV um 1 Grad gegenüber dem Ergebns der mündlichen Prüfung

    • Mündliche Prüfung– 7. Mai 2004, 08:30-17:00– 4. Juni 2004, 08:30-17:00– Prüfungen erfolgen immer paarweise:

    • 15' für 2 StudentInnen ohne Projektdemontration• 30' für 2 StudentInnen mit einer gemeinsamen Projektdemonstration

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    4

    Benotung 2/2

    – Anmeldung für die Prüfung durch Eintragung in eine Liste die am "weissen Brett" des SSW aushängt

    • Geprüft wird das Verständniss 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 dieser Präsentation eine prominente Rolle einnehmen.

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    5

    Das Softwareentwicklungsprojekt 1/3

    • Ist optional - siehe Benotung. Aber nur vollständige Implementationen des Projekts werden benotet.

    • In Teams zu 2 Personen zu entwickeln und zu präsentieren (d.h. dass diese 2 Personen im gleichen 30'-Slot zur Prüfung antreten müssen)

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    6

    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.

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    7

    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 buil/package/deploy ist frei und deshalb sind build-scripts

    nicht Teil der deliverables

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    8

    Literature and References 1/2

    • Selected J2EE specifications (freely available, in the course material)– Java2 Platform Enterprise Edition Specification, v1.4, Sun

    Microsystems– Java Servlet Specification, Version 2.4, Sun Microsystems– JavaServer Pages Specification, Version2.0, Sun Microsystems– Enterprise JavaBeans Specification, Version 2.1, Sun

    Microsystems• The J2EE 1.4 Tutorial, Eric Armstrong et al., Sun Microsystems

    (in the course material)• Core J2EE Patterns, Deepak Alur et al.• EJB Design Patterns, Floyd Marinescu• Patterns of Enterprise Application Architecture, Martin Fowler

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    9

    Literature and References 2/2

    • Enterprise JMS Programming, Shaun Terry• Hibernate2 Reference Documentation, Version 2.1.2 (included

    in the Hibernate distribution, which is in the course material)• Presentation "Object/Relational Mapping with Hibernate" by

    Gavin King

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    10

    Introduction

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    11

    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)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    12

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    13

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    14

    Levels of J2EE knowledge

    General (distributed) computing concepts

    J2EE concepts and terminology

    J2EE software development artifacts

    J2EE tool mechanicsDon't lose the perspective -differentiate between mastering important concepts and "tool wrestling"!

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    15

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    16

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    17

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    18

    J2EE 1.4 APIs 3/4

    • JavaMail 1.3– for sending (SMTP) and accessing (POP, IMAP) email 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)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    19

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    20

    J2EE component overview

    • Servlet– Java class that consumes HTTP request and produces HTTP

    response– front controller in web apps, Gateway to HTTP-based protocols

    (SOAP)• JSP

    – "markup (HTML) file with Java code", compiled to Servlet– view in web apps

    • EJB– 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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    21

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    22

    Software products used in this course

    • Application server: J2EE 1.4 SDK app server– alternatives:

    • Sun Java System application server• 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: text-editor, J2SE, Ant– alternatives: IDEs

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    23

    Examples of J2EE architectures 1/3

    Simple web-centric application

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    24

    Examples of J2EE architectures 2/3

    Web application using EJBs ("3.5 tier"), e.g. Task Tracker

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    25

    Examples of J2EE architectures 3/3

    Mixed-client (web service, Corba and DB) distributed application

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    26

    Interception by the application server / container

    Client Component

    Application Server / Container

    Requestover any protocol

    Response

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    27

    J2EE component interplay

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    28

    Components, containers, protocols

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    29

    Protocols

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    30

    Task Tracker - the example application

    • Web frontend generated by Servlet, JSPs• Business logic encapsulated in/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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    31

    Task Tracker use cases

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    32

    Task Tracker domain object model

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    33

    Task Tracker database schema

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    34

    Components, modules, deployment descriptors 1/3

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    35

    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)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    36

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    37

    Web development with J2EE

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    38

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    39

    HTTP GET request

    GET /articles/news/today.asp HTTP/1.1Accept: */*Accept-Language: en-usConnection: Keep-AliveHost: localhostReferer: http://localhost/links.aspUser-Agent: Mozilla/4.0 (compatible; MSIE 5.5;

    Windows NT 5.0)Accept-Encoding: gzip, deflate

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    40

    HTTP response

    HTTP/1.1 200 OKDate: Wed, 13 Jan 1999 13:19:42 GMTServer: Apache/1.3.1 (Unix)Connection: closeCache-control: privateContent-Type: text/html

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    41

    HTML forms - HTTP GET

    name=age=

    ->

    http://localhost/servlet?name=anton&age=35

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    42

    HTML forms - HTTP POST

    name=age=

    ->

    http://localhost/servlet

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    43

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    44

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    45

    Servlet request URL

    • Available from HttpServletRequest• http://www.you.com/superapp/buy/confirm?value=OK

    – Protocol: http– Host: www.you.com– Request path: /superapp/buy/confirm– Context path: /superapp– Servlet path: /buy– Path info: /confirm– Query string: value=OK

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    46

    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 (http://host/a/b/c.jsp;jsessionid=12321): 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!

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    47

    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 .

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    48

    Web archive (WAR) 2/2

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    49

    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–

    • Scriptlets–

    • Expressions–

    • JSP elements/tags– ,

    • Arbitrary taglib elements/tags (e.g. JSTL)–

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    50

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    51

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    52

    Task Tracker web frontend

    • TTFrontController servlet• view JSPs• web.xml• tasktracker.war• deploying war to app server via

    – admin console– deploytool– autodeploy

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    53

    Struts

    • Open source, quasi-standard framework for MVC web apps• Supports MVC implementation but still exposes HTTP's request-

    response nature– very similar in nature to TaskTracker example but ready-to-use

    implementation of controller (ActionServlet) and a lot of general MVC support

    Client

    Model

    view.jsp

    struts-config.xml

    ActionServlet

    ActionMappings

    Action

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    54

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    55

    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.

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    56

    OperatingEnvironment

    Security terminology 3/3

    Application

    Role1

    Role2

    Group1 Group2

    User1

    User2 User3

    Permission1

    Permission2

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    57

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    58

    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: TaskTrackerweb.xml, sun-web.xml,sun-application.xml,admin console

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    59

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    60

    Enterprise JavaBeans

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    61

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    62

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    63

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    64

    Remote access to an EJB

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    65

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    66

    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!

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    67

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    68

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    69

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    70

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    71

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    72

    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): EntryServiceHome, *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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    73

    Writing a session bean (local/remote client view) 2/4

    – local home interface extends javax.ejb.EJBLocalHome, create-methods return local interface

    – remote home interface extends javax.ejb.EJBHome, create-methods throw RemoteException and return remote interface

    • Write business interface(s): EntryServiceBusiness, *LocalB.– contains only business methods– does not extend any EJB interface– local and/or remote business interface (differ in RemoteException)

    • Write component interface(s): EntryService, *Local– 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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    74

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    75

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    76

    Ejb-jar file

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    77

    Session beans, client and container

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    78

    Creating a session bean instance

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    79

    Removing a session bean instance

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    80

    Stateless session bean life cycle

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    81

    Stateful session bean life cycle

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    82

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    83

    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();CartHome home = (CartHome) ctx.lookup(“java:comp/env/ejb/cart”);

    – remote home interface is "cast" using PortableRemoteObject.narrow()• Context ctx = new InitialContext();

    CartHome home = (CartHome)PortableRemoteObject.narrow(ctx.lookup(“java:comp/env/ejb/cart”), CartHome.class);

    2. Create a session bean instance from the home interface– Cart 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)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    84

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    85

    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• Example: EJBHomeFactory

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    86

    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 hidesthe 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• Example: EntryServiceDelegate, TTFrontController

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    87

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    88

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    89

    J2EE applications

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    90

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    91

    J2EE application (ear) deployment descriptor

    • META-INF/application.xml in .ear file

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    92

    EAR file

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    93

    JMS and message-driven beans

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    94

    Introduction to JMS

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    95

    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 email– 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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    96

    Messaging

    MessageProducer

    MessageConsumer

    Sun Java System Message QueueBEA WebLogic JMSIBM WebSphere MQFiorano MQSoftwired iBusany J2EE app server

    + Msg. Acknowledgement+ Msg. Persistence+ Msg. Selectors

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    97

    TopicPublishers

    TopicSubscribers

    Topic

    + Durable Subscribers

    Publish/subscribe messaging domain

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    98

    Point-to-point messaging domain

    QueueSenders

    QueueReceivers

    Queue

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    99

    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!

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    100

    Destinations

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    101

    Message types

    + Properties+ Format Conversion

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    102

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

    }}

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    103

    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 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    104

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    105

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

    }}

    }

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    106

    EJB deployment descriptor

    HelloMDB

    HelloMDBHelloMDBcom.sun.jmsworkshop.ex1.HelloMDBContainer

    javax.jms.Queue

    Sepp

    HelloMDBonMessage

    Required

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    107

    WLS deployment descriptor

    HelloMDBHelloMDB

    ex1QueueQueueConnectionFactory

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    108

    Messaging scenario 1: asynch backend connectivity

    Application Server

    BackendService SB

    BackendCollector MDB

    ResultQ

    BackendSystem

    RequestQ

    ResponseQ

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    109

    Messaging scenario 2: job scheduling

    Application Server

    SchedulerSB

    Executor MDBResultQ

    InputQ

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    110

    JMS provider implementation architectures

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    111

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    112

    Pub/sub often broadcast-based

    UDP orIP Multicast

    Reliable MulticastPub/Sub Messaging

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    113

    Pub/sub architecture I

    Connection-Based (TCP/IP, SSL)

    Broadcast-Based (UDP, IP Multicast)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    114

    Pub/sub architecture II

    Connection-Based (TCP/IP, SSL)

    Broadcast-Based (UDP, IP Multicast)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    115

    Pub/sub architecture III

    Connection-Based (TCP/IP, SSL)

    Broadcast-Based (UDP, IP Multicast)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    116

    PTP mostly connection-based

    TCP/IP orSSL

    PTP Messaging

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    117

    PTP architecture I

    Permanent Connection

    Possibly Transient Connection

    Queue

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    118

    PTP architecture II

    Queue

    Queue

    Queue

    Queue

    Queue

    Queue

    Permanent Connection

    Possibly Transient Connection

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    119

    JMS details

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    120

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    121

    Decoupling producer-consumer

    • In Space - distributed computing• In Platform and Language• In Time - asynchronous• In Java Object Types (potentially)• In TX-context

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    122

    Message types

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    123

    XML messages

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    124

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    125

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    126

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    127

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    128

    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 super-interface

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    129

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    130

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    131

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    132

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    133

    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!

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    134

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    135

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    136

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    137

    QueueBrowser

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    138

    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!!

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    139

    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*()

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    140

    Acknowledgement, recovery and transactions in JMS

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    141

    Acknowledgement/recovery/transaction decision tree

    Set Ackn Mode,Session.recover()

    Use TX?no yes

    Auto Acknowledge?no

    Message.acknowledge()

    Onle one JMS Session involved or outside app server?

    no yes

    Transacted Session:Session.commit(),Session.rollback()

    Distributed TX:Bean-managed (UserTransaction methods)

    Or Container-managed (EJBContext.setRollbackOnly())

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    142

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    143

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    144

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    145

    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!

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    146

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    147

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    148

    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 client-

    acknowledge)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    149

    EJB deployment descriptor 1

    HelloMDB

    HelloMDBHelloMDBcom.sun.jmsworkshop.ex1.HelloMDBContainer

    javax.jms.Queue

    Sepp

    HelloMDBonMessage

    Required

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    150

    EJB deployment descriptor 2

    HelloMDB

    HelloMDBHelloMDBcom.sun.jmsworkshop.ex1.HelloMDBBeanDups_ok_acknowledge

    javax.jms.Queue

    Sepp

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    151

    Acknowledgement/recovery/transaction decision tree

    Set Ackn Mode,Session.recover()

    Use TX?no yes

    Auto Acknowledge?no

    Message.acknowledge()

    Onle one JMSSession involved?

    no yes

    Transacted Session:Session.commit(),Session.rollback()

    Distributed TX:Bean-managed (UserTransaction methods)

    Or Container-managed (EJBContext.setRollbackOnly())

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    152

    Last messages

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    153

    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

    [email protected] at Jax2002

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    154

    • 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

    Performance tips 2/2

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    155

    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

    [email protected] at Jax2002

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    156

    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

    [email protected] at Jax2002

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    157

    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

    [email protected] at Jax2002

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    158

    Task Tracker and messaging

    EntryServiceSession BeancreateEntry()

    TTQ

    EntryReplicatorMDB

    onMessage()

    Entry

    JMS Message

    Entry

    Entry

    JMS Message

    App Server

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    159

    JMS administered objects in J2EE 1.4 SDK app server

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    160

    Creating a JMS connection factory

    1. Java Message Service -> Connection Factories2. -> New: The Create JMS Connection Factory screen appears3. Enter JNDI Name, e.g. jms/TTQCF4. Choose javax.jms.QueueConnectionFactory from the Type

    menu5. Select "Enabled"6. Click OK7. Verify in config/domain.xml

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    161

    Creating a physical queue

    1. Java Message Service -> Physical Destinations2. -> New: The Create Physical Destination pane appears3. Enter Physical Destination Name, e.g. TTPhysicalQ4. Choose queue from the Type menu5. Click OK6. Verify in config/domain.xml

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    162

    Creating a destination resource

    1. Java Message Service -> Destination Resources2. -> New: The Create JMS Destination Resource pane appears3. Enter JNDI Name, e.g. jms/TTQ4. Choose javax.jms.Queue from the Type menu5. Select "Enabled"6. Additional Properties -> Add7. Enter "Name" in the Name field8. Enter "TTPhysicalQ" in the Value field9. Click OK10.Verify in config/domain.xml

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    163

    J2EE component environment and references

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    164

    Component's environment entries

    • Defined in component's deployment descriptor–

    my ageagejava.lang.Integer35

    • Accessed by JNDI lookup in "java:comp/env"– Context ctx = new InitialContext();

    Integer age = (Integer) ctx.lookup(“java:comp/env/age”);

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    165

    J2EE component and dependencies (references)

    Component

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    166

    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/MyEntryServiceSessioncom.sun.tasktracker...EntryServiceHomecom.sun.tasktracker...EntryServiceEntryServiceEJB

    • Uses ejb-link in deployment descriptor to resolve EJB reference by stating the ejb-name of the referenced EJB

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    167

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    168

    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 sub-context 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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    169

    Component's resource manager connection factory references 2/2• Definition in (using) components deployment descriptor:

    – blajdbc/TheDBjavax.sql.DataSourceContainerShareable

    • 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();

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    170

    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:

    bla

    jms/StockQeue

    javax.jms.Queue

    Produces

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    171

    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 lookupContext 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:

    jms/MyQjavax.jms.Queue

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    172

    Transactions

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    173

    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)

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    174

    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 thisresponsibility to the transaction manager

    – application server: uses a transaction manager (which is usuallypart 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 two-phase 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 theJDBC driver would be the resource manager for that resource

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    175

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    176

    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:

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    177

    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 two-

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    178

    A distributed transaction scenario

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    179

    Another distributed transaction scenario

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    180

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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    181

    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

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    182

    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 resourcemanager 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()

  • March 2004 J2EE - Introduction and Practice, Gerald Loeffler, Sun Microsystems

    183

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