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

j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

Embed Size (px)

Citation preview

Page 1: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

J2EE: Introduction and Practice

Dr. Gerald LoefflerJava ArchitectSun Software Services, Sun Microsystems

Page 2: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 3: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 4: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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.

Page 5: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 6: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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.

Page 7: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 8: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 9: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 10: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

10

Introduction

Page 11: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 12: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 13: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 14: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 15: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 16: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 17: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 18: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 19: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 20: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 21: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 22: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 23: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

23

Examples of J2EE architectures 1/3

Simple web-centric application

Page 24: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 25: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 26: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 27: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

27

J2EE component interplay

Page 28: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

28

Components, containers, protocols

Page 29: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

29

Protocols

Page 30: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 31: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

31

Task Tracker use cases

Page 32: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

32

Task Tracker domain object model

Page 33: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

33

Task Tracker database schema

Page 34: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

34

Components, modules, deployment descriptors 1/3

Page 35: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 36: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 37: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

37

Web development with J2EE

Page 38: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 39: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 40: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0Transitional//EN">

<HTML>…</HTML>

Page 41: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

41

HTML forms - HTTP GET

<form action="http://localhost/servlet"method="GET">name=<input type="text" name="name">age=<input type="text" name="age"><input type="submit" VALUE="Submit via GET!">

</form>

->

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

Page 42: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

42

HTML forms - HTTP POST

<form action="http://localhost/servlet"method="POST">name=<input type="text" name="name">age=<input type="text" name="age"><input type="submit" VALUE="Submit via GET!">

</form>

->

http://localhost/servlet

Page 43: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 44: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 45: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 46: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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!

Page 47: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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 .

Page 48: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

48

Web archive (WAR) 2/2

Page 49: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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– <%@ 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"/>

Page 50: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 51: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 52: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 53: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 54: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 55: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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.

Page 56: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 57: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 58: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 59: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 60: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

60

Enterprise JavaBeans

Page 61: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 62: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 63: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 64: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

64

Remote access to an EJB

Page 65: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 66: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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!

Page 67: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 68: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 69: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 70: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 71: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 72: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 73: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 74: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 75: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 76: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

76

Ejb-jar file

Page 77: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

77

Session beans, client and container

Page 78: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

78

Creating a session bean instance

Page 79: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

79

Removing a session bean instance

Page 80: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

80

Stateless session bean life cycle

Page 81: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

81

Stateful session bean life cycle

Page 82: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 83: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 84: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 85: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 86: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 87: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 88: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 89: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

89

J2EE applications

Page 90: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 91: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

91

J2EE application (ear) deployment descriptor

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

Page 92: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

92

EAR file

Page 93: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

93

JMS and message-driven beans

Page 94: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

94

Introduction to JMS

Page 95: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 96: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 97: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

97

TopicPublishers

TopicSubscribers

Topic

+ Durable Subscribers

Publish/subscribe messaging domain

Page 98: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

98

Point-to-point messaging domain

QueueSenders

QueueReceivers

Queue

Page 99: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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!

Page 100: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

100

Destinations

Page 101: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

101

Message types

+ Properties+ Format Conversion

Page 102: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

}}

Page 103: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

}}

}

Page 104: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 105: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

}}

}

Page 106: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

106

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>

Page 107: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

107

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>

Page 108: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 109: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

109

Messaging scenario 2: job scheduling

Application Server

SchedulerSB

Executor MDBResultQ

InputQ

Page 110: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

110

JMS provider implementation architectures

Page 111: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 112: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

112

Pub/sub often broadcast-based

UDP orIP Multicast

Reliable MulticastPub/Sub Messaging

Page 113: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 114: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 115: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 116: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

116

PTP mostly connection-based

TCP/IP orSSL

PTP Messaging

Page 117: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

117

PTP architecture I

Permanent Connection

Possibly Transient Connection

Queue

Page 118: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 119: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

119

JMS details

Page 120: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 121: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 122: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 123: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 124: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 125: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 126: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 127: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 128: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 129: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 130: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 131: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 132: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 133: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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!

Page 134: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 135: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 136: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 137: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 138: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 139: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 140: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

140

Acknowledgement, recovery and transactions in JMS

Page 141: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 142: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 143: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 144: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 145: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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!

Page 146: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 147: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 148: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 149: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

149

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>

Page 150: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

150

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>

Page 151: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 152: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

152

Last messages

Page 153: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 154: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 155: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 156: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 157: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 158: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 159: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

159

JMS administered objects in J2EE 1.4 SDK app server

Page 160: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 161: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 162: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 163: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

163

J2EE component environment and references

Page 164: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

164

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

Page 165: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

165

J2EE component and dependencies (references)

Component

Page 166: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 167: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 168: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 169: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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:

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

Page 170: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 171: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 172: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

172

Transactions

Page 173: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 174: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 175: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 176: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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:

Page 177: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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)

Page 178: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

178

A distributed transaction scenario

Page 179: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

179

Another distributed transaction scenario

Page 180: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 181: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 182: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

Page 183: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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) if a methodrequires 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!

Page 184: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

184

Container-managed transaction demarcation 2/2

• Preferred if possible• Entity beans must always use container-managed transactions• Example: Task Tracker ejb-jar.xml

Page 185: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

185

Transaction attributes for container-managed tx

Page 186: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

186

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

Page 187: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

187

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

Page 188: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

188

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 EJBmethod you need to– either explicitly rollback transaction (EJBContext.setRollbackOnly())– or make sure that a commit leads to a consistent state of the EJB

Page 189: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

189

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

Page 190: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

190

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

Page 191: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

191

Persistence in J2EE applications

Page 192: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

192

Object/relational mapping (ORM) - object graph

bc

e

a

d

A1

B2

C4

C2 C3

class A {int a;B b;Set c;

}

class B {int d;C e;

}

class C {}

Set

Page 193: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

193

Object/relational mapping (ORM) - relations

a b2

A

d e

4

B

pk12...

pk12... pk

1234...

CfkA

11

Page 194: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

194

ORM of inheritance hierarchies 1/4

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

}

Type hierarchy

Page 195: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

195

ORM of inheritance hierarchies 2/4One table per type ("class") hierarchy

type a1 a2 b1 b2 c1 c2 d1 d2pk

1

2

3

C

B

D

x x x

x x

x

x x xx x x

x x

ABCD

Page 196: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

196

ORM of inheritance hierarchies 3/4One table per type ("sub-class")

type a1 a2

b1 b2

c1 c2

d1 d2

pk

1

2

3

C

B

D

x x x

x x

x

x

x x

x

x x x x

pk

2

pk

3

pk

1

3

A

B

C

D

Page 197: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

197

ORM of inheritance hierarchies 4/4One table per concrete type (class)

a1 a2 b1 b2

c1 c2

d1 d2

x x x

x x

x

xx x x

x x

x x

pk

2

pk

3

pk

1

B

C

D

a1 a2

a1 a2 c1 c2

Page 198: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

198

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

Page 199: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

199

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

Page 200: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

200

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

Page 201: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

201

Hibernateheavily based on "Object/Relational Mapping with Hibernate" by Gavin King

Page 202: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

202

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)

Page 203: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

203

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

Page 204: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

204

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

Page 205: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

205

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

Page 206: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

206

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?

Page 207: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

207

Data is important

• Even so, the relational model is important…– precise, well-understood

• The data will be around much longer than the Java application!

Page 208: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

208

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"

Page 209: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

209

Hibernate

• Opensource (LGPL)– initiated and led by Gavin King

• Mature• Popular (13 000 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

Page 210: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

210

Hibernate

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

Page 211: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

211

Auction object model and DB schema

AUCTION_ITEMitem_iddescsuccessful_bid_id

BIDbid_idamountdatetimeitem_id

Page 212: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

212

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 _successfulBidprivate 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;}…

}

Page 213: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

213

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

<generator class=“native”/></id><property name=“description” column=“DESC”/><many-to-one name=“successfulBid”

column=“SUCCESSFUL_BID_ID”/><set name=“bids”

cascade=“all”lazy=“true”><key column=“ITEM_ID”/><one-to-many class=“Bid”/>

</set></class>

Page 214: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

214

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

Page 215: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

215

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

Page 216: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

216

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

Page 217: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

217

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

Page 218: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

218

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 = ?

Page 219: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

219

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>

Page 220: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

220

Eager (outer join) fetching 2/2AuctionItem item = (AuctionItem) s.get(AuctionItem.class, itemId);

SELECT … FROM AUCTION_ITEM ITEMLEFT OUTER JOIN BID BID1 ON BID1.ITEM_ID = ITEM.ITEM_IDLEFT OUTER JOIN BID BID2 ON BID2.BID_ID = ITEM.SUCCESSFUL_BID_IDWHERE ITEM.ITEM_ID = ?

Page 221: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

221

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

Page 222: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

222

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

Page 223: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

223

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

Page 224: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

224

HQL examples 1/5

Simplest HQL Query:

from AuctionItem

i.e. get all the AuctionItems:

List allAuctions = session.createQuery(“from AuctionItem”).list();

Page 225: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

225

HQL examples 2/5

More realistic example:

select itemfrom AuctionItem item

join item.bids bidwhere 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”

Page 226: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

226

HQL examples 3/5

Projection:

select item.description, bid.amountfrom AuctionItem item

join item.bids bidwhere bid.amount > 100order by bid.amount desc

i.e. get the description and amount for all the AuctionItems with a Bid worth > 100

Page 227: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

227

HQL examples 4/5

Aggregation:

select max(bid.amount), count(bid)from AuctionItem item

left join item.bids bidgroup by item.typeorder by max(bid.amount)

Page 228: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

228

HQL examples 5/5

Runtime fetch strategies:

from AuctionItem itemleft join fetch item.bidsjoin fetch item.successfulBid

where item.id = 12

AuctionItem item = session.createQuery(…).uniqueResult(); //associations already fetched

item.getBids().iterator();item.getSuccessfulBid().getAmount();

Page 229: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

229

Criteria queryList 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 itemleft join fetch item.bids

where item.description like :descriptionand item.successfulbid.amount > :minAmount

Page 230: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

230

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 itemjoin item.bids bid

where item.description like ‘hib%’and bid.amount > 1.0

Page 231: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

231

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!

Page 232: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

232

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>

Page 233: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

233

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

• Hibernate lets you selectively reassociate a subgraph! (essential for performance)

Page 234: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

234

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

}

Page 235: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

235

Detached object support 3/5

Step 2: Collect user input in a servlet/action:

item.setDescription(newDescription);

Page 236: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

236

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

}

Page 237: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

237

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

Page 238: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

238

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

Page 239: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

239

Using Hibernate in a web component or EJB

• C.f. Task Tracker hibernate.cfg.xml• Tell Hibernate to get database connections from DataSource

– connection.datasource: java:comp/env/jdbc/MyDB• Using Hibernate with bean managed transactions

– use the Hibernate transaction API to demarcate transactions (!):• Session.beginTransaction() and Transaction.commit()

– tell Hibernate to use a UserTransaction retrieved via the correct JNDI lookup:

• transaction.factory_class: ...JTATransactionFactory• jta.UserTransaction: java:comp/UserTransaction

• Using Hibernate with container managed transactions– don't demarcate transactions at all

• but call Session.flush() where you would call commit()!!• may call EJBContext.setRollbackOnly()

– don' configure Hibernate's transaction.factory_class

Page 240: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

240

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

Page 241: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

241

Persistence J2EE administration details

Page 242: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

242

Creating a DataSource in J2EE 1.4 SDK 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

Page 243: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

243

Creating a DataSource in J2EE 1.4 SDK 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" jndi-

name="jdbc/TTDB" object-type="user" pool-name="TTDBPool"/>

Page 244: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

244

Creating a DataSource in J2EE 1.4 SDK app server 3/3

– <jdbc-connection-pool connection-validation-method="auto-commit" datasource-classname="com.pointbase.xa.xaDataSource" fail-all-connections="true" idle-timeout-in-seconds="300" is-connection-validation-required="true" is-isolation-level-guaranteed="true" max-pool-size="4" max-wait-time-in-millis="60000" name="TTDBPool" pool-resize-quantity="1" res-type="javax.sql.XADataSource" steady-pool-size="2">

<property name="DatabaseName" value="jdbc:pointbase:embedded:sample;database.home=C:/Sun/AppServer/pointbase/databases"/>

<property name="User" value="PBPUBLIC"/><property name="Password" value="pbpublic"/>

</jdbc-connection-pool>– <resource-ref enabled="true" ref="jdbc/TTDB"/>

Page 245: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

245

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.policygrant {

permission java.util.PropertyPermission "*","read,write";

permission java.lang.reflect.ReflectPermission"suppressAccessChecks";

};

Page 246: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

246

Something to reflect on

Page 247: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

247

Task Tracker software layers

• What is the precise layering in Task Tracker?:– identify layers– identify dependencies between layers (a layer is dependent on

another layer if the classes in the first layer "know" about theclasses in the second layer)

– draw a layer diagram capturing this information– what are the implications of this particular layering?

Page 248: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

248

Epilogue

Page 249: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

249

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

Page 250: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

250

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

Page 251: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

251

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)

Page 252: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

252

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

Page 253: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

253

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)

Page 254: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

254

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)

Page 255: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

- The End -

Dr. Gerald LoefflerJava ArchitectSun Software Services, Sun Microsystems

Page 256: j2ee introduction and practice - ssw.uni-linz.ac.at · – Aufruf einer session bean, die via Hibernate alle Jobs des momentan eingelogten Users aus der Datenbank liest. – Anzeige

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

256

Sub-section heading here