dr. gerald loeffler java architect sun client solutions ... · pdf filemarch 2005 j2ee, gerald...

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

Upload: vutruc

Post on 07-Feb-2018

217 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

J2EE: Introduction, Practice and Software Architecture

Dr. Gerald LoefflerJava ArchitectSun Client Solutions, Sun Microsystems

Page 2: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

2

About this course 1/2

• 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

Page 3: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

3

About this course

– be able to develop web/EJB/database applications using a simplified development process

– understand the basics of inversion of control/dependency injectionand Spring‘s implementation thereof

– understand how Spring can help in separating and configuring the layers of your software and performing common J2EE tasks

Page 4: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

4

Table of contents

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

Page 5: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

5

Benotung

• Die Ermittlung der Note für die KV erfolgt auf Basis einer schriftlichen multiple-choice Prüfung:– Do. 19. Mai 2005, 13:45-15:15, HS10 oder HS16– Geprüft wird das Verständnis der Konzepte von J2EE und ihrer

Zusammenhänge, und nicht ein enzyklopädisches Wissen über Programmierdetails!

• Sie müssen J2EE-Konzepte benennen und erklären können.• Sie müssen nicht die exakten Namen von Java Packages, Classes,

Interfaces und Methods von J2EE kennen, aber es ist sehr wohl nötig, über die prinzipielle Existenz und den Nutzen jener Java-Konstrukte Bescheid zu wissen, die in dieser KV eine prominente Rolle einnehmen.

Page 6: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

6

Das Softwareentwicklungsprojekt 1/3

• Ist optional und wird nicht benotet – ist aber ein wesentlicher Bestandteil der KV und sollte von allen Teilnehmern durchgeführt werden!– Sie können sich hierzu zu Gruppen (optimaler Weise zu 2

Personen) zusammenschließen.• Zu entwickeln ist:

– Asynchroner J2EE Job Scheduler– Architektur: Web frontend, EJB layer, DB access mit Hibernate, DB

creation scripts (table creation und sample data creation), access control zu web frontend und EJBs

– Database schema / persistent classes ungefähr wie folgt:• JobClass: pk, priority (integer, 1-3), name (low/medium/high)• Job: pk, JobClass (foreign key auf JobClass.pk), username,

description, input (integer), result (integer)

Page 7: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

7

Das Softwareentwicklungsprojekt 2/3

– Use cases:• Submit job:

– Im web frontend auswählen der JobClass und Eingabe von description und input des Jobs.

– Aufruf einer session bean durch den Front Controller, die den username des neuen Job auf den momentan eingelogten User setzt und dann den Job viaJMS 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 8: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

8

Das Softwareentwicklungsprojekt 3/3

– Deliverables:• Use case diagram (auch auf Papier möglich)• Domain object model (auch auf Papier möglich)• Source code (incl. aller deployment descriptors)• J2EE application module (ear-file)• Methode des build/package/deploy ist frei und deshalb sind build-

scripts (z.B. Ant-scripts) nicht Teil der deliverables

Page 9: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

9

Literature and References 1/2

• Selected J2EE specifications– 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 10: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

10

Literature and References 2/2

• Enterprise JMS Programming, Shaun Terry• Hibernate

– „Hibernate in Action“, Christian Bauer and Gavin King– 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• Spring

– Spring - java/j2ee Application Framework, Rod Johnson et al.• included in the Spring distribution, which is in the course material

– „J2EE without EJB“, Rod Johnson with Juergen Hoeller

Page 11: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

11

Software architecture and design fundamentals

Page 12: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

12

Layering (in software design)

• Layering is a means of reducing the complexity (of software)– By reducing the dependencies of (software) artefacts

• Layers are arranged in a stack• Each layer depends only on the services offered by the next

lower layer(s)– ...and not on the services offered by layers further down in the

stack– Every layer is ignorant of all higher layers

• Layer is a logical concept– Tier goes further and includes physical separation 4

3

2

1

12

34

Page 13: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

13

Layering in J2EE applications 1/4

• Typically, J2EE applications use three layers:– Presentation layer (GUI layer)

• Handles user interaction• Rich-client GUI, web-based user interface (Web-UI)• Often structured according to MVC (model-view-controller)

– Business logic layer (domain layer)• The heart of the system• Business rules, domain logic, validation, computation, workflow

decisions– Data access layer (DAOs, persistence layer, data source layer, EIS

(enterprise information system) access layer)• Handles access to and communication with back-end systems such as

– relational databases (RDBMSs)– Object-oriented databases (OODBMSs)– Message-oriented middleware (messaging systems)– Enterprise resource planning (ERP) systems such as SAP

• Typically, these back-end systems reside in a separate tier

Page 14: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

14

Layering in J2EE applications 2/4

• The principles of layering imply:– The business logic layer and data access layer are independent of

the presentation layer– The data access layer is independent of the business logic layer

• Often not strictly the case• Typically, classes belonging to different layers reside in different

Java packages• Here we advocate a software architecture with the following

additional characteristics:– Business logic layer is sub-divided into

• Service layer: offers exactly the services needed by the presentation layer and the use cases it implements, often in a procedural way. Only(!) the service layer manages (demarcates) transactions!

• Domain objects (business objects, domain model), i.e. an object-oriented implementation of domain concepts and their behaviour. Often the domain objects are persistent.

Page 15: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

15

Layering in J2EE applications 3/4

– All layers make use of the business objects, i.e., all layers depend on the business objects.

• Presentation layer and service layer are strongly correlated (but the service layer is independent of the presentation layer!) and designed around the use cases of the application– Often, there is more than one pair of presentation and service layer,

because there is more than one „category“ of use cases (actors!) for the interaction with the application:

• Normal users and the use cases they execute through the „normal“ GUI of the application

• Admin users and a separate admin GUI for their use cases• Monitoring systems and a distinct set of use cases (and technology

(JMX)) for the interaction between monitoring systems and the application

Page 16: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

16

Layering in J2EE applications 4/4

service layer

presentation layer

data/EIS access layer

DB SAP

dom

ain

obje

cts

normal user admin user monitoringsystem

• Exercise: think of sensible assignments of these layers to tiers!– For different types of application: web app, standalone app

Page 17: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

17

Other basic software design building blocks 1/2

• The classical GOF (Gamma et al.) design patterns– Singleton: Ensures a class only has one instance, and provide a

global point of access to it– (Abstract) Factory: Provides an interface for creating families of

related objects without specifying their concrete classes– Prototype: Specify the kinds of objects to create using a

prototypical instance, and create new objects by copying this prototype

– Facade: Provides a unified interface to a set of interfaces in a subsystem. Defines a higher-level interface that makes the subsystem easier to use.

– Proxy: Provide a surrogate or placeholder for another object to control access to it

– ...

Page 18: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

18

Other basic software design building blocks 2/2

• Model-View-Controller (MVC) as a general design principle for user interfaces

• Distributed computing/J2EE/EJB patterns– Data Transfer Object: (Plain Java) classes which contain and

encapsulate bulk data in one network transportable bundle• Domain Data Transfer Object vs. Custom Data Transfer Object

– Session Facade: Clients should have access only to session beans (and not to entity beans)

– EJBHomeFactory, BusinessDelegate, Business Interface: see later• Very basic OO design principles

– Encapsulation– Separation of concerns– ...

Page 19: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

19

Introduction

Page 20: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

20

Examples of J2EE applications 1/3

• Portfolio Management System– intranet clients on bank-controlled PCs, globally; Swing frontend– one application server per continent– IIOP as protocol between clients and servers– database (data warehouse) to store portfolio information in– mainframes as back-end systems to handle trading (connected via

message-oriented middleware (MOM)

Page 21: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

21

Examples of J2EE applications 2/3

• MMS processing system– MMS-capable phones as clients– mobile network infrastructure translates requests into HTTP– load-balanced application servers handle HTTP requests– MMS after processing passed on to delivery system

Page 22: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

22

Examples of J2EE applications 3/3

• Mobile work management system– PDAs in factory setting as clients, receive work-units and confirm

cmpletion; AWT-frontend– occasional HTTP-based connection to application server– web-application as control station to distribute work to clients– SAP back-end defines work-units and is notified of completion– database to "buffer" data between application core and SAP

Page 23: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

23

Levels of J2EE knowledge

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

J2EE software development artifacts

J2EE concepts and terminology

General (distributed) computing concepts

Page 24: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

24

J2EE is...

• ... Java2 Enterprise Edition• ... a collection of Java technologies to build distributed

applications (incl. web applications)• ... a set of specifications to write applications against (that will

run in an application server)• ... a set of specifications to define the behaviour of application

servers and hence to write application servers against• ... a component technology• ... an umbrella Java Specification Request (JSR) (for J2EE) and

numerous JSRs (for each of the constituing technologies)• ... very complex if considered in it's entire breadth and depth• ... not a software product (IDE, server, whatever)• ... targeted at the same application space as Microsoft's .Net,

which uses some of the same architectural concepts

Page 25: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

25

J2EE 1.4 APIs 1/4

• J2SE 1.4 APIs– JDBC 3.0 (Java Database Connectivity)

• for accessing relational (SQL) databases (RDBMSs)– Java IDL ((Corba) Interface Definition Language)

• to implement clients of Corba objects– RMI-IIOP ((Java) Remote Method Invocation over (Corba) Internet

Inter-Orb Protocol)• to implement clients of Corba objects using the RMI API• include ubiquitous javax.rmi.PortableRemoteObject.narrow() method

– JNDI (Java Naming and Directory Interface)• to retrieve "administered objects" from the app server:

– EJBHome, UserTransaction, JDBC DataSource, JMS ConnectionFactory, JMS Destination, JavaMail Session, URL, "connection" ConnectionFactory, ORB, component environment entries, ...

Page 26: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

26

J2EE 1.4 APIs 2/4

– JAXP 1.2 (Java API for XML Processing)• for parsing, creating and transforming XML documents• includes at least one DOM2 parser, SAX2 parser and XSLT engine

– JAAS (Java Authentication and Authorization Service)• for programmatic extensions of security aspects

• EJB 2.1 (Enterprise JavaBeans)• Servlet 2.4• JSP 2.0 (Java Server Pages)• JMS 1.1 (Java Messaging Service)• JTA 1.0 (Java Transaction API)

– to demarcate transaction using UserTransaction object– defines interfaces app server - transaction manager - resource

manager

Page 27: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

27

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 28: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

28

J2EE 1.4 APIs 4/4

• JAXR 1.0 (Java API for XML Registries)– to implement clients to UDDI and ebXML registries

• J2EE Management 1.0– for management tools to interact with app server

• JMX 1.2 (Java Management Extensions)– used by J2EE Management API

• J2EE Deployment 1.1– for app server providers to implement standardized plugins into

deployment tools (IDEs)• JACC 1.0 (Java Authorization Service Provider Contract for

Containers)– defines interface between app server and authorization policy

provider

Page 29: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

29

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 30: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

30

Application server

• Runtime environment for J2EE components• (Logically) made up of containers:

– web container (hosts Servlets/JSPs)– EJB container (hosts EJBs)

• Provides services to (and encapsulates) components:– thread pooling– state management– security

• authentication, authorization, access control, encryption– transactions

• ...is a web server, Corba server, includes a transaction manager, ...

• -> demo J2EE 1.4 SDK app server admin console

Page 31: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

31

Software products used in this course

• Application server: Sun Java System Application Server Platform Edition 8.1– alternatives:

• BEA WebLogic• IBM WebSphere• JBoss

• Writing deployment descriptors, packaging and deployment: text-editor, XML-editor, J2EE 1.4 deploytool, Ant scripts– alternatives: Integrated Development Environments (IDEs) such as

• Sun Java Studio• Eclipse• Borland JBuilder

• Writing and compiling Java code: Eclipse, J2SE, Ant– alternatives: other IDEs, text-editor

Page 32: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

32

Examples of J2EE architectures 1/3

Simple web-centric application

Page 33: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

33

Examples of J2EE architectures 2/3

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

Page 34: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

34

Examples of J2EE architectures 3/3

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

Page 35: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

35

Interception by the application server / container

Client Component

Application Server / Container

Requestover any protocol

Response

Page 36: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

36

J2EE component interplay

Page 37: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

37

Components, containers, protocols

Page 38: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

38

Protocols

Page 39: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

39

Task Tracker ‐ the example application

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

Page 40: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

40

Task Tracker use cases

Page 41: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

41

Task Tracker domain object model

Page 42: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

42

Task Tracker database schema

Page 43: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

43

Components, modules, deployment descriptors 1/3

Page 44: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

44

Components, modules, deployment descriptors 2/3

• Compononents are collections of Java classes/interfaces:– web: Servlet, JSP, ...– EJB: session bean, message driven bean, entity bean– ...

• Modules are jar-files that bundle components and follow a specific layout:– EJB module = ejb-jar file (xyz-ejb.jar)

• DD: ejb-jar.xml (J2EE standard), sun-ejb-jar.xml (app server specific)– web app module = war (Web Archive) file (xyz.war)

• DD: web.xml (J2EE standard), sun-web.xml (app server specific)– ...

• J2EE application (= ear (Enterprise Archive) file) is a jar-file that bundles other modules and follows a specific layout– DD: application.xml (J2EE standard), sun-application.xml (app

server specific)

Page 45: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

45

Components, modules, deployment descriptors 3/3

• Example:– Task Tracker modules (war, ejb-jar and ear) and deployment

descriptors for each module– J2EE SDK deploytool– J2EE SDK admin console

Page 46: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

46

Inversion of control and dependency injection, Spring

Page 47: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

47

Motivation 1/4

• Suppose class A depends on a service S

public class A {private S s;public void m() {

s.do();}

}

public interface S {void do();

}

Page 48: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

48

Motivation 2/4

• Class A might create (instantiate) an implementation of service S itself

public class A {private S s = new SImpl();//…

}

– Disadvantage: creates explicit dependency of class A on service implementation SImpl

Page 49: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

49

Motivation 3/4

• Or Class A might delegate the creation of the implementation of service S to a factory

public class A {private S s = SFactory.getInstance();//…

}

– Disadvantage: creates explicit dependency of class A on factory SFactory

Page 50: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

50

Motivation 4/4

• Or Class A might expose it‘s dependency on service S to the „outside world“ and rely on dependency injection to satisfy this dependency

public class A {private S s;public A(S s) {

this.s = s;}//…

}– This is called (constructor-based) dependency injection or inversion of

control (IoC) (because who/what controls the creation of the serviceimplementation is inverted compared to our original example)

– Disadvantage: requires the existence of an IoC container to satisfy the dependencies

• But neither A nor C nor CImpl have an explicit dependency on the IoC container!

Page 51: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

51

Setter‐base dependency injection

• With constructor-based dependency injection, constructor arguments might get confusing

• Setter-based dependency injection uses one JavaBean setter method to inject each dependency:

public class A {private S s;public void setS(S s) {

this.s = s;}//…

}

Page 52: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

52

IoC and J2EE

• The basic IoC mechanism can be used to great advantage in the J2EE world:– Moving JNDI lookups to the IoC container– Linking a DataSource to a data access object (DAO)– Linking a DAO to a service object– Linking a service object to an EJB facade– Linking an EJB client to the EJB

• Examples for each of these points are given in the TaskTracker application and in the rest of this presentation.

Page 53: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

53

Spring bean factory

• Provides the basic services of an IoC container (objects arecalled beans in this context):– Bean creation– Bean configuration– Bean wiring, i.e. setting bean references to create an object graph– Bean lookup

• <bean id=„s“ class=„com.xyz.SImpl“/><bean id=„a“ class=„com.xyz.A“>

<property name=„s“><ref bean=„s“/>

</property></bean>

• f = new XmlBeanFactory(new ClassPathResource(„xml“));A a = (A) f.getBean(„a“);

Page 54: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

54

Spring and layering in J2EE applications 1/2

• Use Spring to define and configure the objects that form the interface of each layer in a J2EE application, using e.g. a separate Spring bean definition file per layer:– The DAOs of the data access layer– The service objects of the service layer

• Depend on DAOs, e.g. bean definition file for service layer could import DAO bean definition file

– The session beans of a session facade layer• Depend on service objects, e.g. session facade layer could access

beans form bean factory using the service layer bean definition file– The actions of the presentation layer

• Depend on service objects– Either, bean definition file for presentation layer defines EJB proxies to

access session facade layer– Or, bean definition file for presentation layer could import service layer bean

definition file (if access is to POJOs of service layer directly)

Page 55: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

55

Spring and layering in J2EE applications 2/2

data access layer

service layer

session façade layer

presentation layercontroller

actions

session beans

service objects

DAOs

Page 56: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

56

Web development with J2EE

Page 57: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

57

HTTP basics

• RFC 1945 (HTTP/1.0), RFC 2616 (HTTP/1.1)– http://www.rfc.net/

• 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 58: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

58

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 59: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

59

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 60: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

60

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 61: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

61

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 62: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

62

HttpServlet 1/2

• A Java class• Managed by servlet container• Triggered by HTTP requests arriving at container, produces

HTTP response– service() dispatches to doGet(), doPost(), ...– HTTP request encapsulated as Java object of type

HttpServletRequest• headers, parameters (strings), attributes (objects)• request URL (see later)

– output is Java object of type HttpServletResponse that encapsulates the HTTP response

• content-type, content

• I.e.: servlets (and JSPs) fully expose the request-responsenature of HTTP

Page 63: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

63

HttpServlet 2/2

• A servlet instance's methods may be called from any number of threads simultaneously - be careful (avoid) instance variables.

• How to use:– don't produce (significant) markup from servlet - use JSPs for that– servlet acts as Front Controller in web apps:

• cf. MVC (Model-View-Controller)• all HTTP requests arrive at Front Controller• decode actions• call business logic (i.e. interact with Model)• pass model to JSP (the View), via forward/include which produces

markup

Page 64: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

64

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 65: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

65

Servlet (web) sessions

• Session ties together HTTP requests from one client• HttpServletRequest.getSession() of all requests (within a

session) returns the same session object– call before getting Writer/OutputStream so that a cookie can be set

• Session identity maintained between requests– via cookies (stored on client and sent with requests)– via URL rewriting (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 66: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

66

Web archive (WAR) 1/2

• Packaging and deployment unit of web apps• Contains

– web components (servlets, JSPs)– server-side Java classes– static web content (HTML, images, …)– client-side Java classes (applets, support classes)– standard and app-server-specific deployment descriptor (web.xml

and sun-web.xml)• Packaged as jar with extension war

– jar cvf example.war .

Page 67: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

67

Web archive (WAR) 2/2

Page 68: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

68

Java Server Pages (JSP) basics 1/2

• JSPs are "inside-out servlets", which are translated to "real" servlets at runtime or deployment time– JSP body becomes service() methods

• Directives– <%@ page import="java.util.*, com.sun.*" %>

• Scriptlets– <% for (int i = 0; i < 10; i++) {…} %>

• Expressions– <%= book.getTitle() %>

• JSP elements/tags– <jsp:useBean>, <jsp:include>

• Arbitrary taglib elements/tags (e.g. JSTL)– <c:redirect url="/begin.jsp"/>

Page 69: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

69

Java Server Pages (JSP) basics 2/2

• Implicitly available objects:– application: javax.servlet.ServletContext (Web Context)– config: javax.servlet.ServletConfig– exception: Throwable (within error pages)– out: javax.servlet.jsp.JspWriter– request: javax.servlet.ServletRequest– response: javax.servlet.ServletResponse– session: javax.servlet.http.HttpSession

Page 70: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

70

Java Standard Tag Library (JSTL)

• Available from JSP 2.0 (J2EE 1.4)• Introduced Expression Language (EL) into JSP• Core tags

– basics, flow control, URL management• XML tags

– Core, flow control, transformation• I18N tags

– Locale, message formatting, number and date formatting• Database tags

– DataSource support, SQL

Page 71: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

71

Task Tracker web frontend

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

– admin console– deploytool– autodeploy

Page 72: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

72

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

Client

Model

view.jsp

struts-config.xml

ActionServlet

ActionMappings

Action

Page 73: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

73

Security terminology 1/3

• Principal– the authenticated subject, e.g. a user– has name

• Authentication data– e.g. password

• Authentication– the process of proving the identity of a principal– matching principal and authentication data against a "store"– e.g., entering username/password which is validated

• Credential– encodes to the app server what the user is allowed to do– result of (successful) authentication

Page 74: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

74

Security terminology 2/3

• (Security) role– a logical concept that is used by a (J2EE) application to group

permissions– an application's security roles are mapped to users (principals) and

groups from the operating environment– e.g. tt-admin, tt-user, tt-vip-user

• Authorization, Access control– the process of providing/restricting a principal's access to resources

based on the principal's roles• Security (policy) domain, realm

– scope of one security policy• Security context

– used by app server to hold credentials, etc.

Page 75: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

75

Security terminology 3/3

OperatingEnvironment

Application

Role1

Role2

Group1 Group2

User1

User2 User3

Permission1

Permission2

Page 76: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

76

Declarative security for web components 1/2

• An application's roles and access controls are declared in the deployment descriptor

• Protectable resource: URLs• Web authentication mechanisms:

– HTTP basic authentication• username/password (base64-encoded)• handled by web browser

– HTTP form-based authentication• username/password, but app provides HTML form

– HTTPS client authentication• user needs Public Key Certificate

Page 77: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

77

Declarative security for web components 2/2

• Transport guarantee is the means of specifying encrypted communication (i.e. HTTPS)

• Security roles are identified in the deployment descriptor(web.xml) and mapped to users/groups from the operating environment in the app-server-specific deployment descriptor(sun-web.xml or sun-application.xml)

• Example: TaskTrackerweb.xml, sun-web.xml,sun-application.xml,admin console

Page 78: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

78

Programmatic security for web components

• Encoding authorisation requirements in code• To be used (only) if declarative security is not enough (too

static)• API

– HttpServletRequest• getRemoteUser(): the login name of the user making the request (if (!)

sent with the request)• isUserInRole(String roleName)• getUserPrincipal(): the name of the currently authenticated user

(wrapped in a Principal object); null means not logged in

• Role names used in code are logical role names that can be linked to "real" role names in the deployment descriptor(security-role-ref).

Page 79: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

79

Enterprise JavaBeans

Page 80: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

80

Enterprise Java Bean (EJB) principles 1/3

• Managed by EJB container in app server (container callbacks!)• Clients can be remote (most usual), local or (remote) web

service clients• Home interface

– defined by developer to include factory methods (create), a remove-method, finders, etc.

– methods act on EJBs of one type ("substitute for static methods")– remote home interface or local home interface– lookup via JNDI (i.e. by name)

• Component interface– defined by developer to include business methods– methods act on EJB instance (although, in the case of SLSBs,

instances indistinguishable)– remote interface or local interface

Page 81: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

81

Enterprise Java Bean (EJB) principles 2/3

• Security and transaction support– declarative or programmatic

• Packaged in ejb-jar file (includes deployment descriptors)• Session bean: a component that implements some business

logic running on the server– stateful ("objects") or stateless ("scoped procedures")– remote clients or local clients– stateless session beans may also have web service clients– executes for one (stateful) or all (stateless) client(s), short-lived

Page 82: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

82

Enterprise Java Bean (EJB) principles 3/3

• Entity bean: a component that represents an object-oriented view of some entities stored in persistent storage (database)– remote clients or local clients– an object view of persistent data ("one instance represents one

record from a table")– has primary key– shared access from multiple clients, long-lived

• Message driven bean: a component that implements some asynchronous business logic running on the server– asynchronously (!) executes logic on server triggered by arrival of

JMS messages– no clients (either local, remote or web service)– no home and component interface– stateless, no identity (similar to SLSB), short-lived

Page 83: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

83

Remote access to an EJB

Page 84: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

84

A bit of perspective on EJBs 1/2

• It is not complex to write EJBs, but it is definitely more effort than to write plain old Java objects (POJOs)– 1 class vs. 1 class + home interface(s) + (business interface(s)) +

component interface(s) + deployment descriptors• The most common decision to be made is for a web application

whether to package business logic in session beans or POJOs– EJBs (session beans, in this case) offer over POJOs (when used

from the web container):• declarative security and transactions (can be changed without touching

the code)• remote access (important if there is also a non-web client; provides

possibility for further load-balancing between web end ejb tiers)• formal interface definition and encapsulation

– it is usually little effort to provide a session facade that hides POJOs which implement the application logic

Page 85: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

85

A bit of perspective on EJBs 2/2

– if there is very little application logic (just database access, as in the TaskTracker application) then database access (properly encapsulated in a database access layer!) could also be done directly from within the action-objects of the web user interface

• You do not have to use EJBs!

Page 86: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

86

EJB remote client view and remote clients

• Applies to session and entity beans– but don't use for entity beans for performance reasons

• Location independence– API and semantics of using remote client view is the same whether

EJB runs in same JVM as client or in remote JVM– Java RMI-based (i.e. (also) Corba/IIOP-based)– pass-by-value semantics for arguments and return values

(serialization)• EJB remote client view defined through:

– remote home interface– remote (component) interface

• Clients can be non-Java (if they speak Corba)– but web services are a more widely supported choice as an

interface to non-Java clients

Page 87: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

87

EJB local client view and local clients

• Applies to session and entity beans• Client and EJB execute in same JVM

– no location independence– pass-by-reference semantics for arguments and return-values

(normal Java method call semantics) – avoids overhead of remote call!

• methods can be more fine-grained than with remote view

• EJB local client view defined through:– local home interface– local (component) interface

• Clients "must" be Java

Page 88: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

88

EJB web service client view and web service clients

• Applies only to stateless session beans• Exposes the EJB as a web service

– calls via SOAP over HTTP(S) (replaces IIOP in "normal" remote client view)

– provides location independence (SOAP calls are remote calls)• EJB web service client view defined through:

– WSDL document (replaces remote (component) interface)• Clients can be non-Java

– quickly becoming the best supported cross-platform distributed computing technology

– Java clients use JAX-RPC to access (any) web service

Page 89: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

89

Know what you do when using a remote view

• Applies to remote client view and web service client view• Martin Fowler's first law of distributed objects: "Don't distribute

your objects"• Location independence is beautiful and provides flexibility in

deployment but remote calls– have high latency (network, network stack,

marhsalling/unmarshalling ("copying") of parameters and return values)

– must therefore be coarse-grained: few remote calls, transporting as much data as is sensible and possible

– may fail due to network problems, unavailable server, etc.• Local EJBs offer mainly "only" (declarative) security and

transaction support over normal Java objects• The developer decides between remote and/or local client view

Page 90: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

90

Passivation and activation

• Applies to stateful session beans and entity beans• The app server (ejb container) actively manages memory by

serializing/deserializing bean instances to/from disk when required: passivation/activation– all fields in an EJB must be serializable, "part of the EJB spec" (or

null at the moment of passivation)– don't use transient fields

• ejbPassivate() and ejbActivate() methods called by container immediately before passivation and after activation, respectively– ejbPassivate()

• close any open resources (e.g. DB connections)• set all fields to null that are not serializable or "part of the EJB spec"

– ejbActivate()• re-open any resources (e.g. DB connections)• re-initialize any null-fields

Page 91: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

91

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

• Decide between stateful vs. stateless– stateless session beans may not contain any conversational state

in instance variables between method calls (best to avoid any instance variables)

– any stateless session bean instance may be used to service any client

• Decide for local and/or remote client view (often just remote)• Write home interface(s): EntryServiceRemoteHome,

*LocalHome– defines create-methods

• stateless session bean: exactly one method called create() without any arguments

• stateful session bean: 1 or more methods called create*() with optional arguments

• return value is matching component interface• must throw javax.ejb.CreateException

Page 92: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

92

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): EntryServiceRemote, *Local– contains only business methods– does not extend any EJB interface– local and/or remote business interface (differ in RemoteException)

• Write component interface(s): EntryServiceRemoteComp, *LocalComp– local interface extends javax.ejb.EJBLocalObject and local

business interface– remote interface extends javax.ejb.EJBObject and remote business

interface– is usually empty because all business methods are defined in the

business interface

Page 93: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

93

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

• Write bean class: EntryServiceBean– implements javax.ejb.SessionBean and business interface(s)– public no-arg constructor– implement all business methods (from business interface(s)) but

don't declare RemoteException in throws clause– implement one ejbCreate*() method for each create*() method in

the home interface(s):• same arguments and throws clause (but without RemoteException)• ejbCreate*() return void (while create*() return component interface)

– implement container (life cycle) callbacks:• ejbActivate(), ejbPassivate(); ejbRemove()• setSessionContext(SessionContext) and store passed session context

– instance variables (fields):• statefull session bean: all fields must be serializable, "part of the EJB

spec" or set to null in ejbPassivate()• stateless session bean: best to not define any fields at all

Page 94: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

94

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

• Write deployment descriptors– ejb-jar.xml

• J2EE standard deployment descriptor which describes all EJBs in an ejb-jar file

– name, class names of home and component interface and bean class, EJB type (+ stateful/stateless), ...

– sun-ejb-jar.xml• app server specific deployment descrptor which provides additional

information about EJBs in the ejb-jar file– jndi-name, ...

• Package everthing in ejb-jar file• Deploy ejb-jar to app server• Example: DD, packaging and deployment of tasktracker-ejb.jar

Page 95: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

95

Ejb‐jar file

Page 96: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

96

Session beans, client and container

Page 97: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

97

Creating a session bean instance

Page 98: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

98

Removing a session bean instance

Page 99: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

99

Stateless session bean life cycle

Page 100: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

100

Stateful session bean life cycle

Page 101: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

101

Reentrancy with session beans

• The EJB container serialises calls to each session bean instance– each session bean instance sees only a serialized sequence of

method calls (and not concurrent execution of its methods frommultiple 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 102: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

102

Using a session bean (local/remote client view) 1/2

1. Lookup home interface through JNDI– local home interface is cast directly

• Context ctx = new InitialContext();CartLocalHome home = (CartLocalHome) ctx.lookup(“java:comp/env/ejb/cart”);

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

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

2. Create a session bean instance from the home interface– CartRemoteComp cart = home.create("gerald", 35);– local home interface create-method returns local interface– remote home interface create-method returns remote interface and

is remote method (may throw RemoteException)

Page 103: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

103

Using a session bean (local/remote client view) 2/2

3. Call business methods on session bean instance– cart.doSomething();

– a stateful session bean instance is intended exclusively for the client which created the instance

• do not share reference to session bean instance• call methods only from one thread

– local interface methods are local calls– remote interface methods are remote methods (may throw

RemoteException)4. Remove session bean instance

– cart.remove();

– local interface remove-method is local method– remote interface remove-method is remote method (may throw

RemoteException)

Page 104: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

104

EJB home factory

• JNDI lookup for home interface is expensive because it usually requires a remote call to the JNDI server (which is part of the app server)

• Remote home interfaces need to be narrow()-ed• An EJB Home Factory is a completely re-usable utility class that

caches home interfaces and also correctly narrow()s them– Home interfaces usually become stale (throw exception upon first

usage) if the application server was recycled: need to be re-fetched

Page 105: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

105

Business delegate

• Especially during development in a team, it is beneficial to allowclient-developers and server-developers to work independently. But if client-developers call EJBs directly, they will depend on these EJBs working correctly.

• Remote EJB calls may need re-trying to gracefully handle temporary network problems

• Client-developers may feel uncomfortable using the normal EJB client view.

• A business delegate is a plain Java object that completely hides the EJB API from client developers and implements re-tries.– constructor hides JNDI lookup and create-call– methods mirror EJB business methods but without EJB exceptions;

may be faked early in the project

Page 106: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

106

EJB access using Spring

• Spring provides helper classes for all the common tasks needed to access an EJB:– plain JNDI lookup: JndiObjectFactoryBean– SimpleRemoteStatelessSessionProxyFactoryBean:

• combines JNDI lookup, EJB home factory and business delegate for remote statless session beans

• configurable caching and re-connect behaviour• similarly: LocalStatelessSessionProxyFactoryBean

• Example: Task Tracker spring_webui.xml

Page 107: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

107

Declarative security for EJBs

• Protectable resource: calling EJB methods• An application's roles and access controls are declared in the

deployment descriptor– again: roles are a logical concept of the application; all roles must

be enumerated in the deployment descriptor– permissions (to call EJB methods) are assigned to roles– roles are mapped to principals (users) and groups from the

operating environment (e.g. in the app server specific deployment descriptor)

• Example: Task Tracker ejb-jar.xml, sun-application.xml

Page 108: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

108

Programmatic security for EJBs

• Encoding authorisation requirements in code• To be used (only) if declarative security is not enough (too

static)• API

– EJBContext• isCallerInRole(String roleName)

– can be used to code more dynamic security policies than can be expressed(in the deployment descriptor) using declarative security

• getCallerPrincipal()– could be used to lookup information in database based on the name of the

principal calling the EJB

• Role names used in code are logical role names that can be linked to "real" role names in the deployment descriptor(security-role-ref).

• Example: Task Tracker EntryServiceBean.createEntry()

Page 109: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

109

J2EE applications

Page 110: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

110

J2EE application review

• A J2EE application bundles several modules into one ear-file• Deployment descritors (application.xml, sun-application.xml)

describe the application as a whole and certain properties of each module– if you know that modules will be used within an application, then

move DD elements into the application DDs to avoid redundancy:• context-root for web modules• security-role-mapping from role names to users/groups

• Example: Task Tracker application.xml, sun-application.xml

Page 111: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

111

J2EE application (ear) deployment descriptor

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

Page 112: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

112

EAR file

Page 113: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

113

JMS and message‐driven beans

Page 114: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

114

Introduction to JMS

Page 115: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

115

MOM, JMS and message‐driven beans overview

• Message-oriented middleware (MOM) is a class of enterprisesoftware 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 116: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

116

Messaging

MessageProducer

MessageConsumer

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

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

Page 117: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

117

TopicPublishers

TopicSubscribers

Topic

+ Durable Subscribers

Publish/subscribe messaging domain

Page 118: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

118

Point‐to‐point messaging domain

Queue

QueueSenders

QueueReceivers

Page 119: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

119

Messaging and J2EE

• The application server contains the JMS provider• Every component type (with the exception of applets) can

produce messages• Only application clients and message-driven beans can

consume messages!

Page 120: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

120

Destinations

Page 121: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

121

Message types

+ Properties+ Format Conversion

Page 122: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

122

JMS message producer

public class HelloQueueSender {public static final String D_NAME = "ex1Queue";public static final String CF_NAME = "QueueConnectionFactory";

public static void main(String[] args) { try {

Context ctx = new InitialContext();QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup(CF_NAME);Queue q = (Queue) ctx.lookup(D_NAME);QueueConnection qc = qcf.createQueueConnection();try {

QueueSession qsess = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

QueueSender qsnd = qsess.createSender(q);TextMessage msg = qsess.createTextMessage("Hello JMS World");qsnd.send(msg);

} finally {try {qc.close();} catch (Exception e) {}

}} catch (Exception e) {

System.out.println("Exception occurred: " + e.toString());}

}}

Page 123: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

123

JMS message producer using Spring

• Spring provides helper classes that make sending JMS messages particularly easy– plain JNDI lookup: JndiObjectFactoryBean

• Can be used to look up JMS connection factories and destinations– JmsTemplate:

• handles all resource clean-up (finally blocks)• provides convenience methods to send common message types• Converts checked JMSException into unchecked JmsException• integrates into Spring transaction infrastructure

• Example: Task Tracker spring_accounting_access.xml and AccountingServiceAOImpl

Page 124: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

124

JMS message consumer

public class HelloQueueReceiverAsynch implements MessageListener {public static final String D_NAME = "ex1Queue";public static final String CF_NAME = "QueueConnectionFactory";

public void onMessage(Message message) {try {

TextMessage msg = (TextMessage) message;System.out.println("Received: " + msg.getText());

} catch (Exception e) {System.out.println("Exception occurred: " + e.toString());

}}

public static void main(String[] args) { try {

Context ctx = new InitialContext();QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup(CF_NAME);Queue q = (Queue) ctx.lookup(D_NAME);QueueConnection qc = qcf.createQueueConnection();QueueSession qsess = qc.createQueueSession(false,

Session.AUTO_ACKNOWLEDGE);QueueReceiver qrcv = qsess.createReceiver(q);qrcv.setMessageListener(new HelloQueueReceiverAsynch());qc.start();

} catch (Exception e) {System.out.println("Exception occurred: " + e.toString());

}}

}

Page 125: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

125

Message‐driven bean characteristics

• Asynchronous message consumer from queues and/or topics• MDB can also listen on non-JMS messages• Stateless• No home interface or component interface

– an MDB implements the interface MessageListener which defines one method onMessage(Message)

• Client does not interact directly with MDB– client sends message to queue/topic– JMS provider delivers message to MDB– complete decoupling of client and MDB

• client does not know of existence of MDB• MDB does not know client identity (principal, caller, user, whatever)

• MDBs are a high-performance EJB type that is known only on the app server

Page 126: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

126

MDB example

public class MessageTraderBean implements MessageDrivenBean, MessageListener {private MessageDrivenContext ctx;

public void ejbCreate() {}public void ejbRemove() {}

public void setMessageDrivenContext(MessageDrivenContext ctx) {this.ctx = ctx;

}

public void onMessage(Message msg) {try {

String msgText = ((TextMessage) msg).getText();System.out.println("Message Received: "+ msgText );

} catch (Exception e) {e.printStackTrace();

}}

}

Page 127: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

127

EJB deployment descriptor<ejb-jar>

<display-name>HelloMDB</display-name><enterprise-beans>

<message-driven><display-name>HelloMDB</display-name><ejb-name>HelloMDB</ejb-name><ejb-class>com.sun.jmsworkshop.ex1.HelloMDB</ejb-class><transaction-type>Container</transaction-type><message-driven-destination><destination-type>javax.jms.Queue</destination-type>

</message-driven-destination><security-identity><run-as>

<role-name>Sepp</role-name></run-as>

</security-identity></message-driven>

</enterprise-beans><assembly-descriptor>

<container-transaction><method><ejb-name>HelloMDB</ejb-name><method-name>onMessage</method-name>

</method><trans-attribute>Required</trans-attribute>

</container-transaction></assembly-descriptor>

</ejb-jar>

Page 128: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

128

WLS deployment descriptor

<weblogic-ejb-jar><weblogic-enterprise-bean>

<ejb-name>HelloMDB</ejb-name><jndi-name>HelloMDB</jndi-name><message-driven-descriptor>

<destination-jndi-name>ex1Queue</destination-jndi-name><connection-factory-jndi-name>QueueConnectionFactory</connection-factory-jndi-name>

</message-driven-descriptor></weblogic-enterprise-bean>

</weblogic-ejb-jar>

Page 129: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

129

Messaging scenario 1: asynch backend connectivity

Application Server

BackendService SB

BackendCollector MDB

ResultQ

BackendSystem

RequestQ

ResponseQ

Page 130: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

130

Messaging scenario 2: job scheduling

Application Server

SchedulerSB

Executor MDBResultQ

InputQ

Page 131: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

131

JMS provider implementation architectures

Page 132: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

132

JMS and implementations

• JMS does not define implementation architectures for JMS Provider

• Different implementations have different characteristics:– performance and scalability– security– reliability

• The value of some JMS features depends on the implementation architecture of the JMS provider

– e.g. filters

Page 133: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

133

Pub/sub often broadcast‐based

Pub/Sub MessagingReliable Multicast

UDP orIP Multicast

Page 134: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

134

Pub/sub architecture I

Connection-Based (TCP/IP, SSL)

Broadcast-Based (UDP, IP Multicast)

Page 135: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

135

Pub/sub architecture II

Connection-Based (TCP/IP, SSL)

Broadcast-Based (UDP, IP Multicast)

Page 136: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

136

Pub/sub architecture III

Connection-Based (TCP/IP, SSL)

Broadcast-Based (UDP, IP Multicast)

Page 137: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

137

PTP mostly connection‐based

PTP MessagingTCP/IP or

SSL

Page 138: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

138

PTP architecture I

Queue

Permanent Connection

Possibly Transient Connection

Page 139: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

139

PTP architecture II

Queue

Queue

Queue

Queue

Queue

Permanent Connection Queue

Possibly Transient Connection

Page 140: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

140

JMS details

Page 141: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

141

Provider model

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

Page 142: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

142

Decoupling producer‐consumer

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

Page 143: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

143

Message types

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

Page 144: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

144

XML messages

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

Page 145: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

145

Message properties

• Are optional name-value pairs– name: string– value: primitive Java type

• Not necessarily available outside JMS• Filterable• Message headers vs. optional properties

– headers: predefined, dedicated accessors in Message• getJMSCorrelationID(), ...

– optional properties: type-safe accessors• setStringProperty(), getIntProperty(), ...

• JMSX-prefix for names reserved• Goody: type-conversion of values

Page 146: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

146

Message selectors

• A message selector is a filter-expression for messages involving message properties which is evaluated by the JMS provider(either on client- or server-side)

• SQL where-clause using properties• Case-sensitive property names• Confirm availability outside JMS!• Specify at message consumer creation

– in Session.createConsumer(), etc.• Hope for server-side filtering with Queues and fear client-side

filtering with Topics

Page 147: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

147

Message headers

• Read-only for client (set-on-call):– JMSDestination– JMSDeliveryMode ((non-)persistent, see later)– JMSExpiration (time-to-live, see later)– JMSPriority (just a hint, 0=lowest - 9=highest)– JMSMessageID (can be disabled)– JMSTimeStamp (can be disabled)– JMSRedelivered

• Writable by client:– JMSCorrelationID (refers to earlier JMSMessageID)– JMSReplyTo (set to (often temporary) destination for reply)– JMSType

Page 148: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

148

JMS factories

• ConnectionFactory -> Connection– ConnectionFactory.createConnection()– QueueConnectionFactory.createQueueConnection()– TopicConnectionFactory.createTopicConnection()

• Connection -> Session– Connection.createSession()– QueueConnection.createQueueSession()– TopicConnection.createTopicSession()

• Session -> msg producer / consumer– Session.createProducer(), .createConsumer()– QueueSession.createSender(), .createReceiver()– TopicSession.createPublisher(), .createSubscriber(),

.createDurableSubscriber()• Session -> Message

– Session.create*Message()

Page 149: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

149

Connection factory

• A connection factory is a factory for connections to the JMS provider

• Is an administered object, i.e. is created administratively in theJMS 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 150: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

150

Session

• A session is used by one thread to produce and consume messages (via producer and consumer objects)– not thread-safe

• A session has only one listener thread!– all calls to a session's consumer's onMessage() are serialized

• Basis for TX• Basis for acknowledgement mode• Provides recovery via recover()• Closing a connection also closes its sessions

Page 151: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

151

Destination

• Destination is either Queue or Topics– but can be used through common Destination super-interface

• They are administered objects, i.e. created in the JMS provider through administration and not programmatically

– lookup through JNDI - don't create dynamically• Ignore session's factory methods!

– Session.createQueue(String queueName)– Session.createTopic(String topicName)

• Temporary destinations– valid for connection– created via session's factory methods

• Session.createTemporaryQueue()• Session.createTemporaryTopic()

– mostly used for request-reply• helper classes QueueRequestor TopicRequestor

Page 152: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

152

Message producer

• Created for destination or "unidentified" (null-destination)– unidentified producers must specify destination at send()-time

• Default delivery properties administered in connection factory• Set delivery properties

– can be disabled through administration– for all messages sent through producer– delivery mode, expiration (TTL), priority

• Send message– possibly overriding delivery properties

• Closing a session also closes its message producers

Page 153: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

153

Non‐MDB message consumer

• Created for destination• Need to start() connection in order to be able to consume

messages– sending messages doen't require start()

• Handle (consume) messages– either synchronously using a (blocking) receive()

• always provide time-out!– or asynchronously using a message listener– but delivery of the message to the client is always asynchronously!

• Only one listener per consumer• Don't share listeners between sessions!• Messages received read-only• Closing a session also closes its message consumers

Page 154: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

154

Durable topic subscriber

• Bridge topics to queues• Provider keeps messages for un-connected durable subscribers

– in contrast: non-durable topic subscribers receive only those messages that were sent while they were connected

• Needs ClientID string for connection– provide client-specific ConnectionFactory in JMS provider that has

the clientID configured• in J2EE 1.4 SDK app server: property "ClientId"

• Special factory method in TopicSession– TopicSession.createDurableSubscriber()– requires subscription identifier (name) unique within ClientID

• Needs msg expiration of some sort• A real resource hog - use with care!

Page 155: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

155

Multiple queue receivers on one queue

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

Page 156: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

156

Delivery mode: persistent vs. non‐persistent messages

• Persistent messages provide reliability in case of provider failure– a (successfully) sent message is persisted to "disk"– provider needs persistent store configured

• file, database– is the default

• Trade-off in performance (and space)• Ways of setting delivery mode:

– administratively in ConnectionFactory• set value is default for all messages sent via connections derived from

the connection factory• may suppress over-riding of delivery mode through programmatic

means– programmatically through MessageProducer.setDeliveryMode()

• set value is default for all messages sent through this producer– programmatically at send()-time

Page 157: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

157

Message expiry and time‐to‐live

• By default messages don't expire• Message expiration enhances application stability

– especially for messages sent to durable topic subscribers!• Ways of setting time-to-live:

– administratively in ConnectionFactory• set value is default for all messages sent via connections derived from

the connection factory• may suppress over-riding of time-to-live through programmatic means

– programmatically through MessageProducer.setTimeToLive ()• set value is default for all messages sent through this producer

– programmatically at send()-time

Page 158: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

158

QueueBrowser

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

Page 159: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

159

Request/reply and requestor helper classes

• Implement request/reply paradigm– create temporary destination– set JMSReplyTo header of a message to this temporary destination– send message– (consumer sends reply message to this temporary destination)– (consumer should set JMSCorrelationID header in reply message

to JMSMessageID of request message)– "wait" for delivery of reply message

• QueueRequestor and TopicRequestor do exactly this– the only conrete classes in JMS API– using blocking receive to wait for reply message

• limited usefulness• deadlocks when used within one TX!!

Page 160: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

160

MDB subtleties

• Acknowledgement and TX -> see later• MDB instances not reentrant

– onMessage()-calls serialised for each instance• No seriality in message processing whatsoever• MDB listens on only one Destination• No available Connection or Session• No use in throwing RuntimeException from within onMessage()

-> see TX discussion• Don't use EJBContext.*Caller*()

Page 161: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

161

Acknowledgement, recovery and transactions in JMS

Page 162: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

162

Acknowledgement/recovery/transaction decision tree

Set Ackn Mode,Session.recover()

Use TX?no yes

Onle one JMS Session involved or outside app server?

no yes

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

Auto Acknowledge?no

Message.acknowledge() Distributed TX:Bean-managed (UserTransaction methods)

Or Container-managed (EJBContext.setRollbackOnly())

Page 163: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

163

Message acknowledgement 1/2

• Successful consumption of message takes place in 3 stages:– client receives the message– client processes the message– the message is acknowledged (either by JMS provider or client)

• Acknowledgement semantics differs between queues and topics:– queue: messages that were received by the client but not

acknowledged when session is closed are re-delivered to the "next" receiver

– topic:• durable subscribers: as with queue but more well-defined client identity• non-durable subscriber: unacknowledged messages are dropped when

session is closed

Page 164: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

164

Message acknowledgement 2/2

• Implicit as part of commit() for transacted sessions• Governed by acknowledge mode for non-transacted sessions

(set at session creation):– AUTO_ACKNOWLEDGE

• automatic acknowledge if no RuntimeException in onMessage()• message may still be redelivered if acknowledge itself fails!

– DUPS_OK_ACKNOWLEDGE• like auto-acknowledge but allows for batch ackn of messages (higher

performance)• causes (more) duplicates if provider fails

– CLIENT_ACKNOWLEDGE• client explicitly needs to call Message.acknowledge()

Page 165: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

165

Session recovery

• Stops and restarts session with first unacknowledged message– causes re-delivery unacknowledged messages (with the exception

of non-durable topic subscribers)• Explicit via Session.recover() for non-transacted sessions• Implicitly as part of rollback() for transacted sessions

Page 166: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

166

Transaction with JMS

• TX Context does not flow with messages– separate TX for send and receive of a msg

• Two approaches (and APIs) to transaction demarcation– JMS local transactions (via transacted session)

• use outside app server– JTA distributed transactions

• use within app server

• Acknowledgement and recovery of received messages is handled automatically if receive is part of a transaction!

Page 167: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

167

JMS local transactions via transacted sessions

• Do no used inside an app server!• Acknowledgement mode ignored• Atomic unit comprises messages produced and consumed in

this Session (since the last commit())• commit() also begins new TX• commit(): Ackn of consumed, sending of produced messages• rollback(): recovery of consumed, dropping of produced

message• Need reference to Session in Listener in order to be able to use

this form of transactions

Page 168: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

168

Distributed transactions

• Mostly (and most easily) used from within app server• Needed whenever atomic unit should comprise JMS and e.g.

JDBC activity• Also for more than one JMS Session• Controlled using JTA's UserTransaction, not Session API• JMS Session holds XAResource (XASession)• Create sessions with connection.createSession(true, 0);

Page 169: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

169

Transactions with message driven beans

• Use container-managed TX with tx attribute "required"– otherwise TX doesn't include acknowledge!– tx attribute only Required and NotSupported

• Requestors deadlock within one TX!• There is no Session available inside an MDB• Never use Message.acknowledge()• Bean-managed transaction demarcation requires the

acknowledge mode to be set:– Auto-acknowledge or Dups-ok-acknowledge (and not client-

acknowledge)

Page 170: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

170

EJB deployment descriptor 1<ejb-jar>

<display-name>HelloMDB</display-name><enterprise-beans>

<message-driven><display-name>HelloMDB</display-name><ejb-name>HelloMDB</ejb-name><ejb-class>com.sun.jmsworkshop.ex1.HelloMDB</ejb-class><transaction-type>Container</transaction-type><message-driven-destination><destination-type>javax.jms.Queue</destination-type>

</message-driven-destination><security-identity><run-as>

<role-name>Sepp</role-name></run-as>

</security-identity></message-driven>

</enterprise-beans><assembly-descriptor>

<container-transaction><method><ejb-name>HelloMDB</ejb-name><method-name>onMessage</method-name>

</method><trans-attribute>Required</trans-attribute>

</container-transaction></assembly-descriptor>

</ejb-jar>

Page 171: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

171

EJB deployment descriptor 2

<ejb-jar><display-name>HelloMDB</display-name><enterprise-beans>

<message-driven><display-name>HelloMDB</display-name><ejb-name>HelloMDB</ejb-name><ejb-class>com.sun.jmsworkshop.ex1.HelloMDB</ejb-class><transaction-type>Bean</transaction-type><acknowledge-mode>Dups_ok_acknowledge</acknowledge-mode><message-driven-destination><destination-type>javax.jms.Queue</destination-type>

</message-driven-destination><security-identity><run-as>

<role-name>Sepp</role-name></run-as>

</security-identity></message-driven>

</enterprise-beans></ejb-jar>

Page 172: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

172

Acknowledgement/recovery/transaction decision tree

Set Ackn Mode,Session.recover()

Use TX?no yes

Onle one JMSSession involved?

no yes

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

Auto Acknowledge?no

Message.acknowledge() Distributed TX:Bean-managed (UserTransaction methods)

Or Container-managed (EJBContext.setRollbackOnly())

Page 173: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

173

Last messages

Page 174: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

174

Performance tips 1/2

• Topics (if broadcast-based) faster and more scalable thanQueues (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 175: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

175

Performance tips 2/2

• Beware of message selectors– avoid them if evaluated on client (which often is the case for topics

(at least if broadcast-based))• Increase parallelism by using more than one session

– …and deal with out-of-order messages and complicated TX handling

• Use XML messages only where necessary• Have a good DBA

Page 176: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

176

Security considerations 1/2

• Authentication for JNDI access– security principal and security credentials supplied in constructor for

InitialContext• Access control for JNDI lookup on per-object basis• Other means to get administered objects, bypassing JNDI

access control– API to create Connection Factories and Destinations– re-use objects from other installation

• Access control on per-destination basis– browse/send/receive permissions granted to individual user/groups

• Message encryption to prevent wire sniffing– by all-Java application using ObjectMessage and Java

Cryptography Extensions (body only)– by JMS Provider via SSL, HTTPS, T3S, etc.– messaging inside VPN

[email protected] at Jax2002

Page 177: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

177

Security considerations 2/2

• Signing Messages to prevent Message Faking– Ensures that Message was sent by who claims to have it sent– Message is left unaltered, with secure hash appended

[email protected] at Jax2002

Page 178: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

178

JMS is suited to EAI because…

• MOM is mature and x-platform (provides not only a JMS interface)

• Message format conversion (also custom)• No need to run systems within single executable image• Systems remain in their native environment (host, Linux,

Windows, …)• No need to synchronise execution of systems

– but beware of queue overflow

[email protected] at Jax2002

Page 179: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

179

Task Tracker and messaging

EntryServiceSession BeancreateEntry()

TTQ

EntryReplicatorMDB

onMessage()

Entry

JMS Message

Entry

Entry

JMS Message

App Server

Page 180: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

180

JMS administered objects in Sun application server

Page 181: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

181

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 182: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

182

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 183: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

183

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 184: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

184

J2EE component environment and references

Page 185: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

185

Componentʹs environment entries

• Defined in component's deployment descriptor– <env-entry>

<description>my age</description><env-entry-name>age</env-entry-name><env-entry-type>java.lang.Integer</env-entry-type><env-entry-value>35</env-entry-value>

</env-entry>

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

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

Page 186: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

186

J2EE component and dependencies (references)

Component

Page 187: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

187

Componentʹs EJB references 1/2

• To refer to EJB homes using logical names defined by the(using) component

• Defined in (using) component's deployment descriptor in "ejb" sub-context:– <ejb-ref>

<ejb-ref-name>ejb/MyEntryService</ejb-ref-name><ejb-ref-type>Session</ejb-ref-type><home>com.sun.tasktracker...EntryServiceHome</home><remote>com.sun.tasktracker...EntryService</remote><ejb-link>EntryServiceEJB</ejb-link>

</ejb-ref>

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

Page 188: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

188

Componentʹs EJB references 2/2

• Using component uses logical name in JNDI lookup– Context ctx = new InitialContext();

Object o = ctx.lookup("java:comp/env/ejb/MyEntryService");

EntryServiceHome home = (EntryServiceHome)PortableRemoteObject.narrow(o,EntryServiceHome.class);

• Example: TTFrontController, EntryServiceDelegate, web.xml, ejb-jar.xml

Page 189: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

189

Componentʹs resource manager connection factory references 1/2• E.g. a javax.sql.DataSource is a resource manager connection

factory for resource manager connections (of type java.sql.Connection) to a RDBMS

• To refer to resource manager connection factories using logical names defined by the (using) component

• Defined in (using) component's deployment descriptor in 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 190: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

190

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

– <resource-ref><description>bla</description><res-ref-name>jdbc/TheDB</res-ref-name><res-type>javax.sql.DataSource</res-type><res-auth>Container</res-auth><res-sharing-scope>Shareable</res-sharing-scope>

</resource-ref>

• Use LinkRef in deployment descriptor to resolve reference• Using component uses its logical name in JNDI lookup and

obtains connection from factory– Context ctx = new InitialContext();

DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/TheDB");

Connection con = ds.getConnection();

Page 191: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

191

Componentʹs message destination references 1/2

• To refer to JMS Queues and Topics using logical names defined by the (using) component

• Definition in (using) components deployment descriptor:<message-destination-ref><description>bla</description><message-destination-ref-name>

jms/StockQeue</message-destination-ref-name><message-destination-type>

javax.jms.Queue</message-destination-type><message-destination-usage>

Produces</message-destination-usage>

</message-destination-ref>

Page 192: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

192

Componentʹs message destination references 2/2

• Use message-destination-link in deployment descriptor to resolve reference

• Using component uses its logical name in JNDI 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 193: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

193

Transactions

Page 194: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

194

Transaction fundamentals 1/4

• A transaction is a unit of work that has the ACID properties– atomicity:either the complete unit of work is performed or none at

all - all or nothing– consistency:by executing the unit of work, a system is transferred

from one consistent state to another consistent state, irrespective of whether the transaction succeeds or fails

– isolation:the effects of a transaction are invisible to other transactions as long as the (original) transaction has not succeeded(cf. transaction isolation level)

– durability: the effect of a transaction is (usually) persistent and survives system failures/shutdowns

• Local transaction vs. global (distributed) transaction– a local transaction involves exactly one transactional resource, e.g.

a relational database– a distributed transaction involves several transactional resources,

e.g. a relational database and a messaging system (JMS provider)

Page 195: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

195

Transaction fundamentals 2/4

• Participants in a distributed transaction:– application: uses the facilities of the application server to

begin/commit/rollback transactions, which in turn delegates this responsibility to the transaction manager

– application server: uses a transaction manager (which is usually part of the application server) to coordinate transactions by calling begin(), commit(), etc. on the transaction manager

– transaction manager: coordinates transactions across several transactional resources by enlisting them and orchestrating a 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 196: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

196

Transaction fundamentals 3/4

• The Distributed Transaction Processing (DTP) model of theOpen 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 197: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

197

Transaction fundamentals 4/4

• Two-phase commit is the protocol executed by the transaction manager in a distributed transactionto ensure ACID properties– e.g. in a successful scenario:

Page 198: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

198

Transactions in J2EE

• Distributed transactions must be supported by app server– involve multiple transactional resources– involve multiple components (in particular EJBs)– app server contains transaction manager that coordinates 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 199: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

199

A distributed transaction scenario

Page 200: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

200

Another distributed transaction scenario

Page 201: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

201

Transaction demarcation in servlets/JSPs 1/2

• Not recommended (use EJB methods instead)• Demarcation with javax.transaction.UserTransaction

– begin(), commit(), rollback()– all within one call to service() (TX can not span requests)

• UserTransaction object retrieved through JNDI-lookup with name "java:comp/UserTransaction"– Context ctx = new InitialContext();

UserTransaction tx = (UserTransaction) ctx.lookup("java:comp/UserTransaction");

tx.begin();// ...tx.commit();

Page 202: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

202

Transaction demarcation in servlets/JSPs 2/2

• Access multiple resource managers and/or EJBs within one TX– TX context propagated automatically– EJBs must be deployed in same app server for TX context

propagation• Servlet/JSP can begin a transaction but not continue it

– TX context does not flow with HTTP requests– but: Invocation with RequestDispatcher also "imports" TX

Page 203: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

203

Transaction demarcation in EJBs

• The EJB developer decides whether transaction demarcation(i.e. begin and commit/rollback of transactions) for an EJB is done– either programmatically in the EJB's source code (bean-managed

transaction demarcation)– or by the EJB container according to declarations in the EJB's

deployment descriptor (container-managed transaction demarcation)

• The transactions for an EJB are either completely bean- orcontainer-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 204: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

204

Container‐managed transaction demarcation 1/2

• Deployment descriptor specifies transaction-type "Container" for the EJB

• Deployment descriptor contains instructions (transaction attributes) to EJB container that state (in essence) if a method requires a transaction or not– transaction attribute applies to methods of component interface, i.e.

the business methods (exception: entity beans)– possible values: NotSupported, Required, Supports, RequiresNew,

Mandatory, Never (for some EJBs only sub-set allowed)• In the EJB's code, EJBContext.setRollbackOnly() marks the

current transaction for rollback (which is initiated by the container after return from the method)– if setRollbackOnly() is not called, the transaction is commit()-ed– all other methods of fiddling with transactions are forbidden!

Page 205: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

205

Container‐managed transaction demarcation 2/2

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

Page 206: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

206

Transaction attributes for container‐managed tx

Page 207: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

207

Bean‐managed transaction demarcation 1/2

• Deployment descriptor specifies transaction-type "Bean" for theEJB

• 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 methodsto 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 completedin the method invocation that started it, i.e. a transaction may span several method invocations on a stateful session bean– stateless session beans and message-driven beans must complete

transaction within the method invocation that started it• Not an option for entity beans

Page 208: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

208

Bean‐managed transaction demarcation 2/2

InitialContext ctx = new InitialContext();

DataSource ds1 = (DataSource) ctx.lookup("java:comp/env/jdbc/DB1");

Connection con1 = ds1.getConnection();PreparedStatement stmt1 = con1.prepareStatement("...");DataSource ds2 = (DataSource) ctx.lookup(

"java:comp/env/jdbc/DB2");Connection con2 = ds2.getConnection();

PreparedStatement stmt2 = con2.createStatement("...");UserTransaction ut = ejbContext.getUserTransaction();ut.begin();

stmt1.executeUpdate();stmt2.executeUpdate();

ut.commit();stmt1.close(); stmt2.close();

con1.close(); con2.close();

Page 209: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

209

Exceptions thrown from EJB methods 1/3

• Application exceptions– are all checked exceptions (not a sub-class of RuntimeException)

that are not sub-classes of RemoteException– are used to report business logic problems, not technical problems

• the intention of an application exception is to signal to the client that theEJB ran into an expected condition that prevents it from fulfilling the request, e.g. illegal arguments supplied to the EJB method, precondition of calling the EJB method not met

– e.g. javax.ejb.CreateException, javax.ejb.RemoveException,com.sun.tasktracker.....EntryServiceArgumentException

– can be thrown from any method in home or component interface• An application exception thrown from an EJB method does not

cause an automatic rollback of a pending transaction: in the EJB method you need to– either explicitly rollback transaction (EJBContext.setRollbackOnly())– or make sure that a commit leads to a consistent state of the EJB

Page 210: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

210

Exceptions thrown from EJB methods 2/3

• System exceptions– are all sub-classes of RuntimeException including EJBException

• EJB methods must not throw RemoteException– are used to report unexpected problems or problems that the EJB

can not recover from• e.g., OutOfMemoryError occured in method body, inability to obtain

database connection/make JNDI lookup/send JMS message, unexpected RuntimeExceptions occured in method body

– should be thrown by the EJB method as follows:• EJB method bodies should not catch RuntimeException (but pass it

through as a system exception)• EJB method bodies must catch unrecoverable checked exceptions

(e.g. JNDI's NamingException) and throw an EJBException• throw EJBException if anything else unrecoverable happens

Page 211: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

211

Exceptions thrown from EJB methods 3/3

• A system exception thrown from an EJB method is caught by the EJB container and– causes a rollback of the current transaction (regardless of whether

the transaction was started by the container or by the bean (and is not commited or rolled back))

– causes the client to receive a RemoteException (for remote clients) or EJBException (for local clients)

– the EJB instance is not used by the container any more• The EJB method does not have to worry about clean-up if it

throws a system exception• transction is rolled-back (see before)• the container releases any resources (DB connections, etc.) that are

declared in the EJB's environment (!)

Page 212: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

212

Persistence in J2EE applications

Page 213: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

213

Object/relational mapping (ORM) ‐ object graph

bc

e

a

d

A1

B2

C4

C2 C3

class B {int d;C e;

}

Set

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

}

class C {}

Page 214: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

214

Object/relational mapping (ORM) ‐ relations

a b2

A

d e

4

B

pk12...

pk12... pk

1234...

CfkA

11

Page 215: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

215

ORM of inheritance hierarchies 1/4

abstract class A {int a1;float a2;

}

Type hierarchy

class B extends A {int b1;float b2;

}

class C extends A {int c1;float c2;

}

class D extends C {int d1;float d2;

}

Page 216: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

216

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 217: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

217

ORM of inheritance hierarchies 3/4One table per type (ʺsub‐classʺ)

type a1 a2

b1 b2

c1 c2pk

1

2

3

C

B

D

x x x

x x

x

x

x x

x

pk

1

3

A C

d1 d2

x x x x

pk

2

pk

3

B D

Page 218: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

218

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

pk

1

B

Ca1 a2

pk

2 x x

D

xx x x

pk

3

a1 a2 c1 c2

x x

Page 219: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

219

Entity beans 1/2

• Entity beans are a class of EJBs– should only have local interfaces (for performance reasons)– must use container managed transaction demarcation

• An entity bean type represents a persistent type, e.g. a table• An entity bean instance represents an instance of that persistent

type, e.g. a column of that table– an entity bean instance has an identiy (primary key)– the instance variables of an entity bean typically correspond to the

columns in the table• Entity beans must implement additional container callbacks that

have to do with reading/writing from/to persistent store– ejbLoad(), ejbStore()

Page 220: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

220

Entity beans 2/2

• Two approaches to implementing the database access for an entity bean:– bean-managed persistence (BMP)

• developer of BMP entity bean codes explicit database access (typically using JDBC) in the appropriate methods/callbacks of the entity bean

– container-managed persistence (CMP)• developer uses a ORM tool (the CMP engine) to "generate" the

database access code for a CMP entity bean• queries are expressed in the EJB query language (EJB QL) in a

portable fashion centered around objects (entity beans) not tables

• CMP is usually preferred over BMP because the performance of the database access code of a good CMP engine is typically much better than that of hand-written JDBC

Page 221: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

221

Java Data Objects (JDO)

• Provide programmers with a transparent Java-centric view of persistent information

• Enables pluggable implementations of datastores into application servers

• The Java Data Objects architecture defines a standard API to data contained in local storage systems and heterogeneous enterprise information systems, such as ERP, 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 222: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

222

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

Page 223: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

223

Lightweight ORM solutions• Transparent persistence (POJO/JavaBeans)

– as opposed to entity beans• Persistent/transient instances

– instances of the same class can be either transient or persistent• Automatic dirty Cchecking• Transitive persistence (≈ persistence-by-reachability)

– dependent (child) objects are automatically persisted when parent object (which holds a reference to the child object) is persisted

• Lazy fetching– fetch members of collections when they are needed and not when the

parent object (which owns the collection) is read from the database• Outer join fetching• Runtime SQL generation• Three basic inheritance mapping strategies

– one table per class hierarchy– one table per sub-class– (one table per concrete class: no polymorphism in collections)

Page 224: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

224

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

Page 225: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

225

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

approach very similar to Hibernate!

Page 226: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

226

What do RDBMs do well?• Work with large amounts of data

– searching, sorting• Work with sets of data

– joining, aggregating• Sharing

– concurrency (transactions, locking)– many applications

• Integrity– constraints– transaction isolation

Page 227: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

227

What do RDBMs do badly?

• Modeling– no polymorphism (inheritance)– fine grained models usually result in performance problems

• Business logic– stored procedures should be ruled out unless performance

requirements are extremely demanding• Distribution

– Oracle 10g?

Page 228: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

228

Data is important

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

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

Page 229: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

229

The goal

• Take advantage of those things that relational databases do well• Without leaving the language of objects / classes• Reduce the effort (number of artefacts, lines-of-code) required

for accessing RDBMs from Java• Improve the performance of DB-access from Java that is

achievable under "normal project conditions"

Page 230: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

230

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 231: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

231

Hibernate

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

Page 232: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

232

Auction object model and DB schema

BIDbid_idamountdatetimeitem_id

AUCTION_ITEMitem_iddescsuccessful_bid_id

Page 233: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

233

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

}

Persistent class

• Default constructor• Get/set pairs• Collection property

is an interface type• Identifier property

Page 234: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

234

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

• Readable metadata• Column / table

mappings• Surrogate key

generation strategy• Collection metadata• Fetching strategies

Page 235: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

235

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 236: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

236

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 237: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

237

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 238: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

238

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

Page 239: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

239

Transparent lazy fetching

AuctionItem item = (AuctionItem) session.get(AuctionItem.class, itemId);

SELECT … FROM AUCTION_ITEM ITEM WHERE ITEM.ITEM_ID = ?

Iterator iter = item.getBids().iterator();

SELECT … FROM BID BID WHERE BID.ITEM_ID = ?

item.getSuccessfulBid().getAmount();

SELECT … FROM BID BID WHERE BID.BID_ID = ?

Page 240: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

240

Eager (outer join) fetching 1/2<class name=“AuctionItem” table=“AUCTION_ITEM”>

<id name=“id” column=“ITEM_ID”><generator class=“native”/>

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

outer-join=“true”column=“SUCCESSFUL_BID_ID”/>

<set name=“bids” cascade=“all” outer-join=“true”><key column=“ITEM_ID”/><one-to-many class=“Bid”/>

</set></class>

Page 241: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

241

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 242: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

242

Optimizing data access

• Minimize row reads– use lazy fetching

• N+1 selects problem (=> too many roundtrips)

• Minimize database roundtrips– use outer join fetching

• cartesian product problem (=> huge result set)• (Much less important) Minimize column reads

– see later

• Solution to optimization dilemma are runtime fetch strategies:– just say what objects you need and navigate the object

graph

Page 243: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

243

Hibernate query options• Hibernate Query Language (HQL)

– “minimal” OO dialect of ANSI SQL– "SQL formulated in terms of objects and properties instead of tables and

columns"– a HQL query is a string

• Criteria queries– extensible framework for expressing query criteria as objects– includes “query by example”– a Criteria query is an object

• Native SQL queries– as a last resort when a query can not be expressed (in a performant way)

otherwise

Page 244: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

244

Hibernate Query Language (HQL)• Make SQL be object oriented

– classes and properties instead of tables and columns– polymorphism– associations– much less verbose than SQL

• Full support for relational operations– inner/outer/full joins, cartesian products– projection (!)– aggregation (max, avg) and grouping– ordering– subqueries– SQL function calls

• HQL is a language for talking about “sets of objects”• It unifies relational operations with object models

Page 245: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

245

HQL examples 1/5

Simplest HQL Query:

from AuctionItem

i.e. get all the AuctionItems:

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

Page 246: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

246

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 247: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

247

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 248: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

248

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 249: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

249

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 250: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

250

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 251: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

251

Criteria query as ʺquery by exampleʺAuctionItem item = new AuctionItem();item.setDescription(“hib”);Bid bid = new Bid();bid.setAmount(1.0);List auctionItems =

session.createCriteria(AuctionItem.class).add( Example.create(item).enableLike(MatchMode.START) ).createCriteria(“bids”)

.add( Example.create(bid) ).list();

Equivalent HQL:

from AuctionItem itemjoin item.bids bid

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

Page 252: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

252

Fine‐grained persistence

• “More classes than tables”• Fine-grained object models are good

– greater code reuse– more typesafety– better encapsulation– come naturally with the application of many popular OO patterns

• Support in Hibernate mainly through components– "component" as in "composition" not in the J2EE sense!

Page 253: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

253

Components• Address class• street, city, postCode properties• STREET, CITY, POST_CODE columns of the PERSON and

ORGANIZATION tables• Mutable class

<class name=“Person” table=“PERSON”>…<component name=“address”>

<property name=“street” column=“STREET”/><property name=“city” column=“CITY”/><property name=“postCode” column=“POST_CODE”/>

</component>

</class>

Page 254: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

254

Detached object support 1/5• With detached object support, the objects of persistent classes

can be used as Data Transfer Objects (DTOs)– classical DTOs are just serializable data holders

• “useless” extra LOC• not objects (no behavior)• parallel class hierarchies usually are bad design

– no need for classical DTOs with detached object support• For applications using servlets + session beans

– serialize objects to the web tier, then serialize them back to the EJB tier in the next request

• You don’t need to select a row when you only want to updateit!

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

Page 255: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

255

Detached object support 2/5

Step 1: Retrieve some objects in a session bean:

public List getItems() throws … {return getSession().createQuery("from AuctionItem item " +

"where item.type = :itemType").setParameter(“itemType”, itemType).list();

}

Page 256: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

256

Detached object support 3/5

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

item.setDescription(newDescription);

Page 257: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

257

Detached object support 4/5

Step 3: Make the changes persistent, back in the session bean:

public void updateItem(AuctionItem item) throws … {getSession().update(item);

}

Page 258: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

258

Detached object support 5/5

Detached objects and transitive persistence:

Session session = sf.openSession();Transaction tx = session.beginTransaction();AuctionItem item =

(AuctionItem) session.get(AuctionItem.class, itemId);tx.commit(); session.close();

Bid bid = new Bid();bid.setAmount(bidAmount);bid.setItem(item);item.getBids().add(bid);

Session session2 = sf.openSession();Transaction tx = session2.beginTransaction();session2.update(item);tx.commit(); session2.close();

Page 259: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

259

Detached objects and transitive persistence

• How do we distinguish between newly instantiated objects and detached objects that are already persistent in the database?

– version property (if there is one)– identifier value e.g. null or unsaved-value=“0” (only works for

generated surrogate keys, not for natural keys in legacy data)– write your own strategy, implement Interceptor.isUnsaved()

Page 260: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

260

Using Hibernate in a web component or EJB

• C.f. Task Tracker hibernate.cfg.xml, spring_dao.xml and e.g. EntryDAOImpl

• Use the Spring DAO helpers for Hibernate!– HibernateDaoSupport

• correct transaction synchronization and flushing• translation of checked HibernateException to unchecked

DataAccessException• resource clean-up, thread-local Hibernate sessions, and many more

• Configure Hibernate– to get database connections from (XA-capable) DataSource– to integrate with JTA– with an application server specific (!) class that tells Hibernate how

to lookup the JTA TransactionManager• Using Hibernate with bean managed transactions

– use JTA to demarcate transactions as usual

Page 261: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

261

Using Hibernate in a web component or EJB

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

• and rely on Spring helpers to call Session.flush() where you would normally call commit()

• may call EJBContext.setRollbackOnly()– Doesn‘t really fit into the data access layer philosophy in which DAOs

should be written (hence TaskTracker does not use this approach but ratherthrows a RuntimeException to trigger a transaction rollback)

Page 262: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

262

Hibernate tools

• XDoclet supports Hibernate (in addition to EJBs, etc.)– generates mapping files from JavaDoc-like markup in Java source

• SchemaExport, hbm2ddl– generates DDL ("create table") from mapping file– appreciates (indeed requires) SQL dialect– relies on additional attributes in mapping file (e.g. length, not-null)

• CodeGenerator, hbm2java– generates Java source from mapping file: skeleton implementation

of persistent classes• MapGenerator, class2hbm

– generates skeletal (!) mapping files from Java class files

Page 263: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

263

Persistence J2EE administration details

Page 264: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

264

Creating a DataSource in Sun app server 1/3

• The jar containing the JDBC driver must be on the classpath– either: copy jar to domain/lib directory– or: add jar to "classpath suffix" in admin console JVM settings

• PointBase jars (pbclient.jar, pbembedded.jar) are on classpath by default

• Create a connection pool, e.g. to PointBase embedded for Task Tracker:– name: TTDBPool– DataSource class name: com.pointbase.xa.xaDataSource– resource type: user– review pool setting– turn on connection validation and close connections on failure– choose transaction isolation level

Page 265: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

265

Creating a DataSource in Sun app server 2/3

– additional properties:• databaseName: jdbc:pointbase:embedded:sample;database.home=

C:/Sun/AppServer/pointbase/databases• User: PBPUBLIC• Password: pbpublic

• Create the DataSource itself ("JDBC resource"):– provide JNDI name, e.g. jdbc/TTDB– reference the previously created connection pool– enable the resource

• To achieve all configuration changes, add this to domain.xml file for your app server domain (e.g. C:\Sun\AppServer\domains\domain1\config\domain.xml):– <jdbc-resource enabled="true" jndi-

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

Page 266: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

266

Creating a DataSource in Sun 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 267: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

267

Hibernate

• Hibernate needs a read and write PropertyPermission and permission to reflect on and access non-public class members– both permissions are usually not granted by default by app servers– add the following grant-statement to the app server's policy file (e.g.

in C:\Sun\AppServer\domains\domain1\config\server.policygrant {

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

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

permission java.lang.RuntimePermission"getProtectionDomain";

};};

Page 268: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

268

Epilogue

Page 269: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

269

Portability of J2EE applications 1/3

• Most areas of J2EE are sufficiently standardised so that theJava 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 270: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

270

Portability of J2EE applications 2/3

• Porting a J2EE application from one app server to another app server usually involves the re-writing of the app server specific deployment descriptors

• Runtime behaviour can vary significantly between app servers, and can to a certain degree be configured in the DDs:– thread pool size, timeouts, ...– clustering capabilities

• whether several instances of an app server cluster can share the stateof 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 271: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

271

Portability of J2EE applications 3/3

• Services offered by different application servers can vary significantly– clustering capabilities– access to "user stores" via security realms

• local to app server: file-based, own DB or LDAP• enterprise-wide: Unix passwd, "central" LDAP, Windows domains, ...

– integration with system management tools (e.g. via SNMP)• Installation, administration and montoring of application servers

is highly product-dependent• Deployment of J2EE modules/applications to an app server is

highly product dependent and may use– command-line tools– Ant tasks– GUI tools, probably as plug-in to IDE (Integrated Development Env)

Page 272: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

272

What we didnʹt talk about (in sufficient detail) 1/3

• Web components– HTTP filters– Web event listeners

• Client-side components– Applets (and the applet container)– Application clients (and the application client container)

• Entity Beans• Resource adapters ("connectors), J2EE connector architecture

and a component's resource environment entries• The service providers view (SPIs) of J2EE• J2EE platform roles• JavaIDL, IIOP and a component's ORB references

Page 273: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

273

What we didnʹt talk about (in sufficient detail) 2/3

• Some J2EE APIs– JavaIDL (and IIOP)– JavaMail– JAXP– JAX-RPC– SAAJ– JAAS– J2EE Management, JMX– JNDI beyond accessing the app server naming service

• Advanced security concepts• Web services, both from the implementers view (web service

view of a stateless session bean) and the client's view (JAX-RPC)

Page 274: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

274

What we didnʹt talk about (in sufficient detail) 3/3

• Additional EJB concepts– EJB handle, session bean identity, SessionSynchronization, timer

service, run-as identity• Packaging of jar-files by reference• Automated build/deploy (Ant)• Version control (CVS)

Page 275: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

‐ The End ‐

Dr. Gerald LoefflerJava ArchitectSun Software Services, Sun Microsystems

Page 276: Dr. Gerald Loeffler Java Architect Sun Client Solutions ... · PDF fileMarch 2005 J2EE, Gerald Loeffler, Sun Microsystems 3 About this course – be able to develop web/EJB/database

March 2005 J2EE, Gerald Loeffler, Sun Microsystems

276

Sub‐section heading here